SelectionDAGBuilder.cpp 240 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207
  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. #define DEBUG_TYPE "isel"
  14. #include "SDNodeDbgValue.h"
  15. #include "SelectionDAGBuilder.h"
  16. #include "FunctionLoweringInfo.h"
  17. #include "llvm/ADT/BitVector.h"
  18. #include "llvm/ADT/SmallSet.h"
  19. #include "llvm/Analysis/AliasAnalysis.h"
  20. #include "llvm/Analysis/ConstantFolding.h"
  21. #include "llvm/Constants.h"
  22. #include "llvm/CallingConv.h"
  23. #include "llvm/DerivedTypes.h"
  24. #include "llvm/Function.h"
  25. #include "llvm/GlobalVariable.h"
  26. #include "llvm/InlineAsm.h"
  27. #include "llvm/Instructions.h"
  28. #include "llvm/Intrinsics.h"
  29. #include "llvm/IntrinsicInst.h"
  30. #include "llvm/Module.h"
  31. #include "llvm/CodeGen/FastISel.h"
  32. #include "llvm/CodeGen/GCStrategy.h"
  33. #include "llvm/CodeGen/GCMetadata.h"
  34. #include "llvm/CodeGen/MachineFunction.h"
  35. #include "llvm/CodeGen/MachineFrameInfo.h"
  36. #include "llvm/CodeGen/MachineInstrBuilder.h"
  37. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  38. #include "llvm/CodeGen/MachineModuleInfo.h"
  39. #include "llvm/CodeGen/MachineRegisterInfo.h"
  40. #include "llvm/CodeGen/PseudoSourceValue.h"
  41. #include "llvm/CodeGen/SelectionDAG.h"
  42. #include "llvm/CodeGen/DwarfWriter.h"
  43. #include "llvm/Analysis/DebugInfo.h"
  44. #include "llvm/Target/TargetRegisterInfo.h"
  45. #include "llvm/Target/TargetData.h"
  46. #include "llvm/Target/TargetFrameInfo.h"
  47. #include "llvm/Target/TargetInstrInfo.h"
  48. #include "llvm/Target/TargetIntrinsicInfo.h"
  49. #include "llvm/Target/TargetLowering.h"
  50. #include "llvm/Target/TargetOptions.h"
  51. #include "llvm/Support/Compiler.h"
  52. #include "llvm/Support/CommandLine.h"
  53. #include "llvm/Support/Debug.h"
  54. #include "llvm/Support/ErrorHandling.h"
  55. #include "llvm/Support/MathExtras.h"
  56. #include "llvm/Support/raw_ostream.h"
  57. #include <algorithm>
  58. using namespace llvm;
  59. /// LimitFloatPrecision - Generate low-precision inline sequences for
  60. /// some float libcalls (6, 8 or 12 bits).
  61. static unsigned LimitFloatPrecision;
  62. static cl::opt<unsigned, true>
  63. LimitFPPrecision("limit-float-precision",
  64. cl::desc("Generate low-precision inline sequences "
  65. "for some float libcalls"),
  66. cl::location(LimitFloatPrecision),
  67. cl::init(0));
  68. namespace {
  69. /// RegsForValue - This struct represents the registers (physical or virtual)
  70. /// that a particular set of values is assigned, and the type information
  71. /// about the value. The most common situation is to represent one value at a
  72. /// time, but struct or array values are handled element-wise as multiple
  73. /// values. The splitting of aggregates is performed recursively, so that we
  74. /// never have aggregate-typed registers. The values at this point do not
  75. /// necessarily have legal types, so each value may require one or more
  76. /// registers of some legal type.
  77. ///
  78. struct RegsForValue {
  79. /// TLI - The TargetLowering object.
  80. ///
  81. const TargetLowering *TLI;
  82. /// ValueVTs - The value types of the values, which may not be legal, and
  83. /// may need be promoted or synthesized from one or more registers.
  84. ///
  85. SmallVector<EVT, 4> ValueVTs;
  86. /// RegVTs - The value types of the registers. This is the same size as
  87. /// ValueVTs and it records, for each value, what the type of the assigned
  88. /// register or registers are. (Individual values are never synthesized
  89. /// from more than one type of register.)
  90. ///
  91. /// With virtual registers, the contents of RegVTs is redundant with TLI's
  92. /// getRegisterType member function, however when with physical registers
  93. /// it is necessary to have a separate record of the types.
  94. ///
  95. SmallVector<EVT, 4> RegVTs;
  96. /// Regs - This list holds the registers assigned to the values.
  97. /// Each legal or promoted value requires one register, and each
  98. /// expanded value requires multiple registers.
  99. ///
  100. SmallVector<unsigned, 4> Regs;
  101. RegsForValue() : TLI(0) {}
  102. RegsForValue(const TargetLowering &tli,
  103. const SmallVector<unsigned, 4> &regs,
  104. EVT regvt, EVT valuevt)
  105. : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
  106. RegsForValue(const TargetLowering &tli,
  107. const SmallVector<unsigned, 4> &regs,
  108. const SmallVector<EVT, 4> &regvts,
  109. const SmallVector<EVT, 4> &valuevts)
  110. : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
  111. RegsForValue(LLVMContext &Context, const TargetLowering &tli,
  112. unsigned Reg, const Type *Ty) : TLI(&tli) {
  113. ComputeValueVTs(tli, Ty, ValueVTs);
  114. for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
  115. EVT ValueVT = ValueVTs[Value];
  116. unsigned NumRegs = TLI->getNumRegisters(Context, ValueVT);
  117. EVT RegisterVT = TLI->getRegisterType(Context, ValueVT);
  118. for (unsigned i = 0; i != NumRegs; ++i)
  119. Regs.push_back(Reg + i);
  120. RegVTs.push_back(RegisterVT);
  121. Reg += NumRegs;
  122. }
  123. }
  124. /// areValueTypesLegal - Return true if types of all the values are legal.
  125. bool areValueTypesLegal() {
  126. for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
  127. EVT RegisterVT = RegVTs[Value];
  128. if (!TLI->isTypeLegal(RegisterVT))
  129. return false;
  130. }
  131. return true;
  132. }
  133. /// append - Add the specified values to this one.
  134. void append(const RegsForValue &RHS) {
  135. TLI = RHS.TLI;
  136. ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
  137. RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
  138. Regs.append(RHS.Regs.begin(), RHS.Regs.end());
  139. }
  140. /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
  141. /// this value and returns the result as a ValueVTs value. This uses
  142. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  143. /// If the Flag pointer is NULL, no flag is used.
  144. SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
  145. SDValue &Chain, SDValue *Flag) const;
  146. /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
  147. /// specified value into the registers specified by this object. This uses
  148. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  149. /// If the Flag pointer is NULL, no flag is used.
  150. void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
  151. SDValue &Chain, SDValue *Flag) const;
  152. /// AddInlineAsmOperands - Add this value to the specified inlineasm node
  153. /// operand list. This adds the code marker, matching input operand index
  154. /// (if applicable), and includes the number of values added into it.
  155. void AddInlineAsmOperands(unsigned Code,
  156. bool HasMatching, unsigned MatchingIdx,
  157. SelectionDAG &DAG,
  158. std::vector<SDValue> &Ops) const;
  159. };
  160. }
  161. /// getCopyFromParts - Create a value that contains the specified legal parts
  162. /// combined into the value they represent. If the parts combine to a type
  163. /// larger then ValueVT then AssertOp can be used to specify whether the extra
  164. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  165. /// (ISD::AssertSext).
  166. static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
  167. const SDValue *Parts,
  168. unsigned NumParts, EVT PartVT, EVT ValueVT,
  169. ISD::NodeType AssertOp = ISD::DELETED_NODE) {
  170. assert(NumParts > 0 && "No parts to assemble!");
  171. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  172. SDValue Val = Parts[0];
  173. if (NumParts > 1) {
  174. // Assemble the value from multiple parts.
  175. if (!ValueVT.isVector() && ValueVT.isInteger()) {
  176. unsigned PartBits = PartVT.getSizeInBits();
  177. unsigned ValueBits = ValueVT.getSizeInBits();
  178. // Assemble the power of 2 part.
  179. unsigned RoundParts = NumParts & (NumParts - 1) ?
  180. 1 << Log2_32(NumParts) : NumParts;
  181. unsigned RoundBits = PartBits * RoundParts;
  182. EVT RoundVT = RoundBits == ValueBits ?
  183. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  184. SDValue Lo, Hi;
  185. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  186. if (RoundParts > 2) {
  187. Lo = getCopyFromParts(DAG, dl, Parts, RoundParts / 2,
  188. PartVT, HalfVT);
  189. Hi = getCopyFromParts(DAG, dl, Parts + RoundParts / 2,
  190. RoundParts / 2, PartVT, HalfVT);
  191. } else {
  192. Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
  193. Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
  194. }
  195. if (TLI.isBigEndian())
  196. std::swap(Lo, Hi);
  197. Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
  198. if (RoundParts < NumParts) {
  199. // Assemble the trailing non-power-of-2 part.
  200. unsigned OddParts = NumParts - RoundParts;
  201. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  202. Hi = getCopyFromParts(DAG, dl,
  203. Parts + RoundParts, OddParts, PartVT, OddVT);
  204. // Combine the round and odd parts.
  205. Lo = Val;
  206. if (TLI.isBigEndian())
  207. std::swap(Lo, Hi);
  208. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  209. Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
  210. Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
  211. DAG.getConstant(Lo.getValueType().getSizeInBits(),
  212. TLI.getPointerTy()));
  213. Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
  214. Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
  215. }
  216. } else if (ValueVT.isVector()) {
  217. // Handle a multi-element vector.
  218. EVT IntermediateVT, RegisterVT;
  219. unsigned NumIntermediates;
  220. unsigned NumRegs =
  221. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  222. NumIntermediates, RegisterVT);
  223. assert(NumRegs == NumParts
  224. && "Part count doesn't match vector breakdown!");
  225. NumParts = NumRegs; // Silence a compiler warning.
  226. assert(RegisterVT == PartVT
  227. && "Part type doesn't match vector breakdown!");
  228. assert(RegisterVT == Parts[0].getValueType() &&
  229. "Part type doesn't match part!");
  230. // Assemble the parts into intermediate operands.
  231. SmallVector<SDValue, 8> Ops(NumIntermediates);
  232. if (NumIntermediates == NumParts) {
  233. // If the register was not expanded, truncate or copy the value,
  234. // as appropriate.
  235. for (unsigned i = 0; i != NumParts; ++i)
  236. Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
  237. PartVT, IntermediateVT);
  238. } else if (NumParts > 0) {
  239. // If the intermediate type was expanded, build the intermediate
  240. // operands from the parts.
  241. assert(NumParts % NumIntermediates == 0 &&
  242. "Must expand into a divisible number of parts!");
  243. unsigned Factor = NumParts / NumIntermediates;
  244. for (unsigned i = 0; i != NumIntermediates; ++i)
  245. Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
  246. PartVT, IntermediateVT);
  247. }
  248. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  249. // intermediate operands.
  250. Val = DAG.getNode(IntermediateVT.isVector() ?
  251. ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
  252. ValueVT, &Ops[0], NumIntermediates);
  253. } else if (PartVT.isFloatingPoint()) {
  254. // FP split into multiple FP parts (for ppcf128)
  255. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
  256. "Unexpected split");
  257. SDValue Lo, Hi;
  258. Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]);
  259. Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]);
  260. if (TLI.isBigEndian())
  261. std::swap(Lo, Hi);
  262. Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
  263. } else {
  264. // FP split into integer parts (soft fp)
  265. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  266. !PartVT.isVector() && "Unexpected split");
  267. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  268. Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
  269. }
  270. }
  271. // There is now one part, held in Val. Correct it to match ValueVT.
  272. PartVT = Val.getValueType();
  273. if (PartVT == ValueVT)
  274. return Val;
  275. if (PartVT.isVector()) {
  276. assert(ValueVT.isVector() && "Unknown vector conversion!");
  277. return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
  278. }
  279. if (ValueVT.isVector()) {
  280. assert(ValueVT.getVectorElementType() == PartVT &&
  281. ValueVT.getVectorNumElements() == 1 &&
  282. "Only trivial scalar-to-vector conversions should get here!");
  283. return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
  284. }
  285. if (PartVT.isInteger() &&
  286. ValueVT.isInteger()) {
  287. if (ValueVT.bitsLT(PartVT)) {
  288. // For a truncate, see if we have any information to
  289. // indicate whether the truncated bits will always be
  290. // zero or sign-extension.
  291. if (AssertOp != ISD::DELETED_NODE)
  292. Val = DAG.getNode(AssertOp, dl, PartVT, Val,
  293. DAG.getValueType(ValueVT));
  294. return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
  295. } else {
  296. return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
  297. }
  298. }
  299. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  300. if (ValueVT.bitsLT(Val.getValueType())) {
  301. // FP_ROUND's are always exact here.
  302. return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
  303. DAG.getIntPtrConstant(1));
  304. }
  305. return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
  306. }
  307. if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
  308. return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
  309. llvm_unreachable("Unknown mismatch!");
  310. return SDValue();
  311. }
  312. /// getCopyToParts - Create a series of nodes that contain the specified value
  313. /// split into legal parts. If the parts contain more bits than Val, then, for
  314. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  315. static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl,
  316. SDValue Val, SDValue *Parts, unsigned NumParts,
  317. EVT PartVT,
  318. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  319. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  320. EVT PtrVT = TLI.getPointerTy();
  321. EVT ValueVT = Val.getValueType();
  322. unsigned PartBits = PartVT.getSizeInBits();
  323. unsigned OrigNumParts = NumParts;
  324. assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
  325. if (!NumParts)
  326. return;
  327. if (!ValueVT.isVector()) {
  328. if (PartVT == ValueVT) {
  329. assert(NumParts == 1 && "No-op copy with multiple parts!");
  330. Parts[0] = Val;
  331. return;
  332. }
  333. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  334. // If the parts cover more bits than the value has, promote the value.
  335. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  336. assert(NumParts == 1 && "Do not know what to promote to!");
  337. Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
  338. } else if (PartVT.isInteger() && ValueVT.isInteger()) {
  339. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  340. Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
  341. } else {
  342. llvm_unreachable("Unknown mismatch!");
  343. }
  344. } else if (PartBits == ValueVT.getSizeInBits()) {
  345. // Different types of the same size.
  346. assert(NumParts == 1 && PartVT != ValueVT);
  347. Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
  348. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  349. // If the parts cover less bits than value has, truncate the value.
  350. if (PartVT.isInteger() && ValueVT.isInteger()) {
  351. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  352. Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
  353. } else {
  354. llvm_unreachable("Unknown mismatch!");
  355. }
  356. }
  357. // The value may have changed - recompute ValueVT.
  358. ValueVT = Val.getValueType();
  359. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  360. "Failed to tile the value with PartVT!");
  361. if (NumParts == 1) {
  362. assert(PartVT == ValueVT && "Type conversion failed!");
  363. Parts[0] = Val;
  364. return;
  365. }
  366. // Expand the value into multiple parts.
  367. if (NumParts & (NumParts - 1)) {
  368. // The number of parts is not a power of 2. Split off and copy the tail.
  369. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  370. "Do not know what to expand to!");
  371. unsigned RoundParts = 1 << Log2_32(NumParts);
  372. unsigned RoundBits = RoundParts * PartBits;
  373. unsigned OddParts = NumParts - RoundParts;
  374. SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
  375. DAG.getConstant(RoundBits,
  376. TLI.getPointerTy()));
  377. getCopyToParts(DAG, dl, OddVal, Parts + RoundParts,
  378. OddParts, PartVT);
  379. if (TLI.isBigEndian())
  380. // The odd parts were reversed by getCopyToParts - unreverse them.
  381. std::reverse(Parts + RoundParts, Parts + NumParts);
  382. NumParts = RoundParts;
  383. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  384. Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
  385. }
  386. // The number of parts is a power of 2. Repeatedly bisect the value using
  387. // EXTRACT_ELEMENT.
  388. Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
  389. EVT::getIntegerVT(*DAG.getContext(),
  390. ValueVT.getSizeInBits()),
  391. Val);
  392. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  393. for (unsigned i = 0; i < NumParts; i += StepSize) {
  394. unsigned ThisBits = StepSize * PartBits / 2;
  395. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  396. SDValue &Part0 = Parts[i];
  397. SDValue &Part1 = Parts[i+StepSize/2];
  398. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
  399. ThisVT, Part0,
  400. DAG.getConstant(1, PtrVT));
  401. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
  402. ThisVT, Part0,
  403. DAG.getConstant(0, PtrVT));
  404. if (ThisBits == PartBits && ThisVT != PartVT) {
  405. Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
  406. PartVT, Part0);
  407. Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
  408. PartVT, Part1);
  409. }
  410. }
  411. }
  412. if (TLI.isBigEndian())
  413. std::reverse(Parts, Parts + OrigNumParts);
  414. return;
  415. }
  416. // Vector ValueVT.
  417. if (NumParts == 1) {
  418. if (PartVT != ValueVT) {
  419. if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  420. Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
  421. } else {
  422. assert(ValueVT.getVectorElementType() == PartVT &&
  423. ValueVT.getVectorNumElements() == 1 &&
  424. "Only trivial vector-to-scalar conversions should get here!");
  425. Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
  426. PartVT, Val,
  427. DAG.getConstant(0, PtrVT));
  428. }
  429. }
  430. Parts[0] = Val;
  431. return;
  432. }
  433. // Handle a multi-element vector.
  434. EVT IntermediateVT, RegisterVT;
  435. unsigned NumIntermediates;
  436. unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
  437. IntermediateVT, NumIntermediates, RegisterVT);
  438. unsigned NumElements = ValueVT.getVectorNumElements();
  439. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  440. NumParts = NumRegs; // Silence a compiler warning.
  441. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  442. // Split the vector into intermediate operands.
  443. SmallVector<SDValue, 8> Ops(NumIntermediates);
  444. for (unsigned i = 0; i != NumIntermediates; ++i) {
  445. if (IntermediateVT.isVector())
  446. Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
  447. IntermediateVT, Val,
  448. DAG.getConstant(i * (NumElements / NumIntermediates),
  449. PtrVT));
  450. else
  451. Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
  452. IntermediateVT, Val,
  453. DAG.getConstant(i, PtrVT));
  454. }
  455. // Split the intermediate operands into legal parts.
  456. if (NumParts == NumIntermediates) {
  457. // If the register was not expanded, promote or copy the value,
  458. // as appropriate.
  459. for (unsigned i = 0; i != NumParts; ++i)
  460. getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
  461. } else if (NumParts > 0) {
  462. // If the intermediate type was expanded, split each the value into
  463. // legal parts.
  464. assert(NumParts % NumIntermediates == 0 &&
  465. "Must expand into a divisible number of parts!");
  466. unsigned Factor = NumParts / NumIntermediates;
  467. for (unsigned i = 0; i != NumIntermediates; ++i)
  468. getCopyToParts(DAG, dl, Ops[i], &Parts[i*Factor], Factor, PartVT);
  469. }
  470. }
  471. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
  472. AA = &aa;
  473. GFI = gfi;
  474. TD = DAG.getTarget().getTargetData();
  475. }
  476. /// clear - Clear out the curret SelectionDAG and the associated
  477. /// state and prepare this SelectionDAGBuilder object to be used
  478. /// for a new block. This doesn't clear out information about
  479. /// additional blocks that are needed to complete switch lowering
  480. /// or PHI node updating; that information is cleared out as it is
  481. /// consumed.
  482. void SelectionDAGBuilder::clear() {
  483. NodeMap.clear();
  484. PendingLoads.clear();
  485. PendingExports.clear();
  486. EdgeMapping.clear();
  487. DAG.clear();
  488. CurDebugLoc = DebugLoc::getUnknownLoc();
  489. HasTailCall = false;
  490. }
  491. /// getRoot - Return the current virtual root of the Selection DAG,
  492. /// flushing any PendingLoad items. This must be done before emitting
  493. /// a store or any other node that may need to be ordered after any
  494. /// prior load instructions.
  495. ///
  496. SDValue SelectionDAGBuilder::getRoot() {
  497. if (PendingLoads.empty())
  498. return DAG.getRoot();
  499. if (PendingLoads.size() == 1) {
  500. SDValue Root = PendingLoads[0];
  501. DAG.setRoot(Root);
  502. PendingLoads.clear();
  503. return Root;
  504. }
  505. // Otherwise, we have to make a token factor node.
  506. SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
  507. &PendingLoads[0], PendingLoads.size());
  508. PendingLoads.clear();
  509. DAG.setRoot(Root);
  510. return Root;
  511. }
  512. /// getControlRoot - Similar to getRoot, but instead of flushing all the
  513. /// PendingLoad items, flush all the PendingExports items. It is necessary
  514. /// to do this before emitting a terminator instruction.
  515. ///
  516. SDValue SelectionDAGBuilder::getControlRoot() {
  517. SDValue Root = DAG.getRoot();
  518. if (PendingExports.empty())
  519. return Root;
  520. // Turn all of the CopyToReg chains into one factored node.
  521. if (Root.getOpcode() != ISD::EntryToken) {
  522. unsigned i = 0, e = PendingExports.size();
  523. for (; i != e; ++i) {
  524. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  525. if (PendingExports[i].getNode()->getOperand(0) == Root)
  526. break; // Don't add the root if we already indirectly depend on it.
  527. }
  528. if (i == e)
  529. PendingExports.push_back(Root);
  530. }
  531. Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
  532. &PendingExports[0],
  533. PendingExports.size());
  534. PendingExports.clear();
  535. DAG.setRoot(Root);
  536. return Root;
  537. }
  538. void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) {
  539. if (DAG.GetOrdering(Node) != 0) return; // Already has ordering.
  540. DAG.AssignOrdering(Node, SDNodeOrder);
  541. for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
  542. AssignOrderingToNode(Node->getOperand(I).getNode());
  543. }
  544. void SelectionDAGBuilder::visit(Instruction &I) {
  545. visit(I.getOpcode(), I);
  546. }
  547. void SelectionDAGBuilder::visit(unsigned Opcode, User &I) {
  548. // Note: this doesn't use InstVisitor, because it has to work with
  549. // ConstantExpr's in addition to instructions.
  550. switch (Opcode) {
  551. default: llvm_unreachable("Unknown instruction type encountered!");
  552. // Build the switch statement using the Instruction.def file.
  553. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  554. case Instruction::OPCODE: visit##OPCODE((CLASS&)I); break;
  555. #include "llvm/Instruction.def"
  556. }
  557. // Assign the ordering to the freshly created DAG nodes.
  558. if (NodeMap.count(&I)) {
  559. ++SDNodeOrder;
  560. AssignOrderingToNode(getValue(&I).getNode());
  561. }
  562. }
  563. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  564. SDValue &N = NodeMap[V];
  565. if (N.getNode()) return N;
  566. if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
  567. EVT VT = TLI.getValueType(V->getType(), true);
  568. if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
  569. return N = DAG.getConstant(*CI, VT);
  570. if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
  571. return N = DAG.getGlobalAddress(GV, VT);
  572. if (isa<ConstantPointerNull>(C))
  573. return N = DAG.getConstant(0, TLI.getPointerTy());
  574. if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  575. return N = DAG.getConstantFP(*CFP, VT);
  576. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  577. return N = DAG.getUNDEF(VT);
  578. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  579. visit(CE->getOpcode(), *CE);
  580. SDValue N1 = NodeMap[V];
  581. assert(N1.getNode() && "visit didn't populate the ValueMap!");
  582. return N1;
  583. }
  584. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  585. SmallVector<SDValue, 4> Constants;
  586. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  587. OI != OE; ++OI) {
  588. SDNode *Val = getValue(*OI).getNode();
  589. // If the operand is an empty aggregate, there are no values.
  590. if (!Val) continue;
  591. // Add each leaf value from the operand to the Constants list
  592. // to form a flattened list of all the values.
  593. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  594. Constants.push_back(SDValue(Val, i));
  595. }
  596. return DAG.getMergeValues(&Constants[0], Constants.size(),
  597. getCurDebugLoc());
  598. }
  599. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  600. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  601. "Unknown struct or array constant!");
  602. SmallVector<EVT, 4> ValueVTs;
  603. ComputeValueVTs(TLI, C->getType(), ValueVTs);
  604. unsigned NumElts = ValueVTs.size();
  605. if (NumElts == 0)
  606. return SDValue(); // empty struct
  607. SmallVector<SDValue, 4> Constants(NumElts);
  608. for (unsigned i = 0; i != NumElts; ++i) {
  609. EVT EltVT = ValueVTs[i];
  610. if (isa<UndefValue>(C))
  611. Constants[i] = DAG.getUNDEF(EltVT);
  612. else if (EltVT.isFloatingPoint())
  613. Constants[i] = DAG.getConstantFP(0, EltVT);
  614. else
  615. Constants[i] = DAG.getConstant(0, EltVT);
  616. }
  617. return DAG.getMergeValues(&Constants[0], NumElts,
  618. getCurDebugLoc());
  619. }
  620. if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
  621. return DAG.getBlockAddress(BA, VT);
  622. const VectorType *VecTy = cast<VectorType>(V->getType());
  623. unsigned NumElements = VecTy->getNumElements();
  624. // Now that we know the number and type of the elements, get that number of
  625. // elements into the Ops array based on what kind of constant it is.
  626. SmallVector<SDValue, 16> Ops;
  627. if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
  628. for (unsigned i = 0; i != NumElements; ++i)
  629. Ops.push_back(getValue(CP->getOperand(i)));
  630. } else {
  631. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  632. EVT EltVT = TLI.getValueType(VecTy->getElementType());
  633. SDValue Op;
  634. if (EltVT.isFloatingPoint())
  635. Op = DAG.getConstantFP(0, EltVT);
  636. else
  637. Op = DAG.getConstant(0, EltVT);
  638. Ops.assign(NumElements, Op);
  639. }
  640. // Create a BUILD_VECTOR node.
  641. return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
  642. VT, &Ops[0], Ops.size());
  643. }
  644. // If this is a static alloca, generate it as the frameindex instead of
  645. // computation.
  646. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  647. DenseMap<const AllocaInst*, int>::iterator SI =
  648. FuncInfo.StaticAllocaMap.find(AI);
  649. if (SI != FuncInfo.StaticAllocaMap.end())
  650. return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
  651. }
  652. unsigned InReg = FuncInfo.ValueMap[V];
  653. assert(InReg && "Value not in map!");
  654. RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
  655. SDValue Chain = DAG.getEntryNode();
  656. return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
  657. }
  658. /// Get the EVTs and ArgFlags collections that represent the legalized return
  659. /// type of the given function. This does not require a DAG or a return value,
  660. /// and is suitable for use before any DAGs for the function are constructed.
  661. static void getReturnInfo(const Type* ReturnType,
  662. Attributes attr, SmallVectorImpl<EVT> &OutVTs,
  663. SmallVectorImpl<ISD::ArgFlagsTy> &OutFlags,
  664. TargetLowering &TLI,
  665. SmallVectorImpl<uint64_t> *Offsets = 0) {
  666. SmallVector<EVT, 4> ValueVTs;
  667. ComputeValueVTs(TLI, ReturnType, ValueVTs);
  668. unsigned NumValues = ValueVTs.size();
  669. if (NumValues == 0) return;
  670. unsigned Offset = 0;
  671. for (unsigned j = 0, f = NumValues; j != f; ++j) {
  672. EVT VT = ValueVTs[j];
  673. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  674. if (attr & Attribute::SExt)
  675. ExtendKind = ISD::SIGN_EXTEND;
  676. else if (attr & Attribute::ZExt)
  677. ExtendKind = ISD::ZERO_EXTEND;
  678. // FIXME: C calling convention requires the return type to be promoted to
  679. // at least 32-bit. But this is not necessary for non-C calling
  680. // conventions. The frontend should mark functions whose return values
  681. // require promoting with signext or zeroext attributes.
  682. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
  683. EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
  684. if (VT.bitsLT(MinVT))
  685. VT = MinVT;
  686. }
  687. unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
  688. EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
  689. unsigned PartSize = TLI.getTargetData()->getTypeAllocSize(
  690. PartVT.getTypeForEVT(ReturnType->getContext()));
  691. // 'inreg' on function refers to return value
  692. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  693. if (attr & Attribute::InReg)
  694. Flags.setInReg();
  695. // Propagate extension type if any
  696. if (attr & Attribute::SExt)
  697. Flags.setSExt();
  698. else if (attr & Attribute::ZExt)
  699. Flags.setZExt();
  700. for (unsigned i = 0; i < NumParts; ++i) {
  701. OutVTs.push_back(PartVT);
  702. OutFlags.push_back(Flags);
  703. if (Offsets)
  704. {
  705. Offsets->push_back(Offset);
  706. Offset += PartSize;
  707. }
  708. }
  709. }
  710. }
  711. void SelectionDAGBuilder::visitRet(ReturnInst &I) {
  712. SDValue Chain = getControlRoot();
  713. SmallVector<ISD::OutputArg, 8> Outs;
  714. FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
  715. if (!FLI.CanLowerReturn) {
  716. unsigned DemoteReg = FLI.DemoteRegister;
  717. const Function *F = I.getParent()->getParent();
  718. // Emit a store of the return value through the virtual register.
  719. // Leave Outs empty so that LowerReturn won't try to load return
  720. // registers the usual way.
  721. SmallVector<EVT, 1> PtrValueVTs;
  722. ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
  723. PtrValueVTs);
  724. SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
  725. SDValue RetOp = getValue(I.getOperand(0));
  726. SmallVector<EVT, 4> ValueVTs;
  727. SmallVector<uint64_t, 4> Offsets;
  728. ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
  729. unsigned NumValues = ValueVTs.size();
  730. SmallVector<SDValue, 4> Chains(NumValues);
  731. EVT PtrVT = PtrValueVTs[0];
  732. for (unsigned i = 0; i != NumValues; ++i) {
  733. SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, RetPtr,
  734. DAG.getConstant(Offsets[i], PtrVT));
  735. Chains[i] =
  736. DAG.getStore(Chain, getCurDebugLoc(),
  737. SDValue(RetOp.getNode(), RetOp.getResNo() + i),
  738. Add, NULL, Offsets[i], false, false, 0);
  739. }
  740. Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
  741. MVT::Other, &Chains[0], NumValues);
  742. } else if (I.getNumOperands() != 0) {
  743. SmallVector<EVT, 4> ValueVTs;
  744. ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
  745. unsigned NumValues = ValueVTs.size();
  746. if (NumValues) {
  747. SDValue RetOp = getValue(I.getOperand(0));
  748. for (unsigned j = 0, f = NumValues; j != f; ++j) {
  749. EVT VT = ValueVTs[j];
  750. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  751. const Function *F = I.getParent()->getParent();
  752. if (F->paramHasAttr(0, Attribute::SExt))
  753. ExtendKind = ISD::SIGN_EXTEND;
  754. else if (F->paramHasAttr(0, Attribute::ZExt))
  755. ExtendKind = ISD::ZERO_EXTEND;
  756. // FIXME: C calling convention requires the return type to be promoted
  757. // to at least 32-bit. But this is not necessary for non-C calling
  758. // conventions. The frontend should mark functions whose return values
  759. // require promoting with signext or zeroext attributes.
  760. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
  761. EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
  762. if (VT.bitsLT(MinVT))
  763. VT = MinVT;
  764. }
  765. unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
  766. EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
  767. SmallVector<SDValue, 4> Parts(NumParts);
  768. getCopyToParts(DAG, getCurDebugLoc(),
  769. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  770. &Parts[0], NumParts, PartVT, ExtendKind);
  771. // 'inreg' on function refers to return value
  772. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  773. if (F->paramHasAttr(0, Attribute::InReg))
  774. Flags.setInReg();
  775. // Propagate extension type if any
  776. if (F->paramHasAttr(0, Attribute::SExt))
  777. Flags.setSExt();
  778. else if (F->paramHasAttr(0, Attribute::ZExt))
  779. Flags.setZExt();
  780. for (unsigned i = 0; i < NumParts; ++i)
  781. Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
  782. }
  783. }
  784. }
  785. bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
  786. CallingConv::ID CallConv =
  787. DAG.getMachineFunction().getFunction()->getCallingConv();
  788. Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
  789. Outs, getCurDebugLoc(), DAG);
  790. // Verify that the target's LowerReturn behaved as expected.
  791. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  792. "LowerReturn didn't return a valid chain!");
  793. // Update the DAG with the new chain value resulting from return lowering.
  794. DAG.setRoot(Chain);
  795. }
  796. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  797. /// created for it, emit nodes to copy the value into the virtual
  798. /// registers.
  799. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(Value *V) {
  800. if (!V->use_empty()) {
  801. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  802. if (VMI != FuncInfo.ValueMap.end())
  803. CopyValueToVirtualRegister(V, VMI->second);
  804. }
  805. }
  806. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  807. /// the current basic block, add it to ValueMap now so that we'll get a
  808. /// CopyTo/FromReg.
  809. void SelectionDAGBuilder::ExportFromCurrentBlock(Value *V) {
  810. // No need to export constants.
  811. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  812. // Already exported?
  813. if (FuncInfo.isExportedInst(V)) return;
  814. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  815. CopyValueToVirtualRegister(V, Reg);
  816. }
  817. bool SelectionDAGBuilder::isExportableFromCurrentBlock(Value *V,
  818. const BasicBlock *FromBB) {
  819. // The operands of the setcc have to be in this block. We don't know
  820. // how to export them from some other block.
  821. if (Instruction *VI = dyn_cast<Instruction>(V)) {
  822. // Can export from current BB.
  823. if (VI->getParent() == FromBB)
  824. return true;
  825. // Is already exported, noop.
  826. return FuncInfo.isExportedInst(V);
  827. }
  828. // If this is an argument, we can export it if the BB is the entry block or
  829. // if it is already exported.
  830. if (isa<Argument>(V)) {
  831. if (FromBB == &FromBB->getParent()->getEntryBlock())
  832. return true;
  833. // Otherwise, can only export this if it is already exported.
  834. return FuncInfo.isExportedInst(V);
  835. }
  836. // Otherwise, constants can always be exported.
  837. return true;
  838. }
  839. static bool InBlock(const Value *V, const BasicBlock *BB) {
  840. if (const Instruction *I = dyn_cast<Instruction>(V))
  841. return I->getParent() == BB;
  842. return true;
  843. }
  844. /// getFCmpCondCode - Return the ISD condition code corresponding to
  845. /// the given LLVM IR floating-point condition code. This includes
  846. /// consideration of global floating-point math flags.
  847. ///
  848. static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
  849. ISD::CondCode FPC, FOC;
  850. switch (Pred) {
  851. case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
  852. case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
  853. case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
  854. case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
  855. case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
  856. case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
  857. case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
  858. case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
  859. case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
  860. case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
  861. case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
  862. case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
  863. case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
  864. case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
  865. case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
  866. case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
  867. default:
  868. llvm_unreachable("Invalid FCmp predicate opcode!");
  869. FOC = FPC = ISD::SETFALSE;
  870. break;
  871. }
  872. if (FiniteOnlyFPMath())
  873. return FOC;
  874. else
  875. return FPC;
  876. }
  877. /// getICmpCondCode - Return the ISD condition code corresponding to
  878. /// the given LLVM IR integer condition code.
  879. ///
  880. static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
  881. switch (Pred) {
  882. case ICmpInst::ICMP_EQ: return ISD::SETEQ;
  883. case ICmpInst::ICMP_NE: return ISD::SETNE;
  884. case ICmpInst::ICMP_SLE: return ISD::SETLE;
  885. case ICmpInst::ICMP_ULE: return ISD::SETULE;
  886. case ICmpInst::ICMP_SGE: return ISD::SETGE;
  887. case ICmpInst::ICMP_UGE: return ISD::SETUGE;
  888. case ICmpInst::ICMP_SLT: return ISD::SETLT;
  889. case ICmpInst::ICMP_ULT: return ISD::SETULT;
  890. case ICmpInst::ICMP_SGT: return ISD::SETGT;
  891. case ICmpInst::ICMP_UGT: return ISD::SETUGT;
  892. default:
  893. llvm_unreachable("Invalid ICmp predicate opcode!");
  894. return ISD::SETNE;
  895. }
  896. }
  897. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  898. /// This function emits a branch and is used at the leaves of an OR or an
  899. /// AND operator tree.
  900. ///
  901. void
  902. SelectionDAGBuilder::EmitBranchForMergedCondition(Value *Cond,
  903. MachineBasicBlock *TBB,
  904. MachineBasicBlock *FBB,
  905. MachineBasicBlock *CurBB) {
  906. const BasicBlock *BB = CurBB->getBasicBlock();
  907. // If the leaf of the tree is a comparison, merge the condition into
  908. // the caseblock.
  909. if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  910. // The operands of the cmp have to be in this block. We don't know
  911. // how to export them from some other block. If this is the first block
  912. // of the sequence, no exporting is needed.
  913. if (CurBB == CurMBB ||
  914. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  915. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  916. ISD::CondCode Condition;
  917. if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  918. Condition = getICmpCondCode(IC->getPredicate());
  919. } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
  920. Condition = getFCmpCondCode(FC->getPredicate());
  921. } else {
  922. Condition = ISD::SETEQ; // silence warning.
  923. llvm_unreachable("Unknown compare instruction");
  924. }
  925. CaseBlock CB(Condition, BOp->getOperand(0),
  926. BOp->getOperand(1), NULL, TBB, FBB, CurBB);
  927. SwitchCases.push_back(CB);
  928. return;
  929. }
  930. }
  931. // Create a CaseBlock record representing this branch.
  932. CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
  933. NULL, TBB, FBB, CurBB);
  934. SwitchCases.push_back(CB);
  935. }
  936. /// FindMergedConditions - If Cond is an expression like
  937. void SelectionDAGBuilder::FindMergedConditions(Value *Cond,
  938. MachineBasicBlock *TBB,
  939. MachineBasicBlock *FBB,
  940. MachineBasicBlock *CurBB,
  941. unsigned Opc) {
  942. // If this node is not part of the or/and tree, emit it as a branch.
  943. Instruction *BOp = dyn_cast<Instruction>(Cond);
  944. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  945. (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
  946. BOp->getParent() != CurBB->getBasicBlock() ||
  947. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  948. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  949. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
  950. return;
  951. }
  952. // Create TmpBB after CurBB.
  953. MachineFunction::iterator BBI = CurBB;
  954. MachineFunction &MF = DAG.getMachineFunction();
  955. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  956. CurBB->getParent()->insert(++BBI, TmpBB);
  957. if (Opc == Instruction::Or) {
  958. // Codegen X | Y as:
  959. // jmp_if_X TBB
  960. // jmp TmpBB
  961. // TmpBB:
  962. // jmp_if_Y TBB
  963. // jmp FBB
  964. //
  965. // Emit the LHS condition.
  966. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
  967. // Emit the RHS condition into TmpBB.
  968. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
  969. } else {
  970. assert(Opc == Instruction::And && "Unknown merge op!");
  971. // Codegen X & Y as:
  972. // jmp_if_X TmpBB
  973. // jmp FBB
  974. // TmpBB:
  975. // jmp_if_Y TBB
  976. // jmp FBB
  977. //
  978. // This requires creation of TmpBB after CurBB.
  979. // Emit the LHS condition.
  980. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
  981. // Emit the RHS condition into TmpBB.
  982. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
  983. }
  984. }
  985. /// If the set of cases should be emitted as a series of branches, return true.
  986. /// If we should emit this as a bunch of and/or'd together conditions, return
  987. /// false.
  988. bool
  989. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
  990. if (Cases.size() != 2) return true;
  991. // If this is two comparisons of the same values or'd or and'd together, they
  992. // will get folded into a single comparison, so don't emit two blocks.
  993. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  994. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  995. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  996. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  997. return false;
  998. }
  999. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1000. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1001. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1002. Cases[0].CC == Cases[1].CC &&
  1003. isa<Constant>(Cases[0].CmpRHS) &&
  1004. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1005. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1006. return false;
  1007. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1008. return false;
  1009. }
  1010. return true;
  1011. }
  1012. void SelectionDAGBuilder::visitBr(BranchInst &I) {
  1013. // Update machine-CFG edges.
  1014. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1015. // Figure out which block is immediately after the current one.
  1016. MachineBasicBlock *NextBlock = 0;
  1017. MachineFunction::iterator BBI = CurMBB;
  1018. if (++BBI != FuncInfo.MF->end())
  1019. NextBlock = BBI;
  1020. if (I.isUnconditional()) {
  1021. // Update machine-CFG edges.
  1022. CurMBB->addSuccessor(Succ0MBB);
  1023. // If this is not a fall-through branch, emit the branch.
  1024. if (Succ0MBB != NextBlock)
  1025. DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
  1026. MVT::Other, getControlRoot(),
  1027. DAG.getBasicBlock(Succ0MBB)));
  1028. return;
  1029. }
  1030. // If this condition is one of the special cases we handle, do special stuff
  1031. // now.
  1032. Value *CondVal = I.getCondition();
  1033. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1034. // If this is a series of conditions that are or'd or and'd together, emit
  1035. // this as a sequence of branches instead of setcc's with and/or operations.
  1036. // For example, instead of something like:
  1037. // cmp A, B
  1038. // C = seteq
  1039. // cmp D, E
  1040. // F = setle
  1041. // or C, F
  1042. // jnz foo
  1043. // Emit:
  1044. // cmp A, B
  1045. // je foo
  1046. // cmp D, E
  1047. // jle foo
  1048. //
  1049. if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1050. if (BOp->hasOneUse() &&
  1051. (BOp->getOpcode() == Instruction::And ||
  1052. BOp->getOpcode() == Instruction::Or)) {
  1053. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
  1054. // If the compares in later blocks need to use values not currently
  1055. // exported from this block, export them now. This block should always
  1056. // be the first entry.
  1057. assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
  1058. // Allow some cases to be rejected.
  1059. if (ShouldEmitAsBranches(SwitchCases)) {
  1060. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
  1061. ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
  1062. ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
  1063. }
  1064. // Emit the branch for this block.
  1065. visitSwitchCase(SwitchCases[0]);
  1066. SwitchCases.erase(SwitchCases.begin());
  1067. return;
  1068. }
  1069. // Okay, we decided not to do this, remove any inserted MBB's and clear
  1070. // SwitchCases.
  1071. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
  1072. FuncInfo.MF->erase(SwitchCases[i].ThisBB);
  1073. SwitchCases.clear();
  1074. }
  1075. }
  1076. // Create a CaseBlock record representing this branch.
  1077. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  1078. NULL, Succ0MBB, Succ1MBB, CurMBB);
  1079. // Use visitSwitchCase to actually insert the fast branch sequence for this
  1080. // cond branch.
  1081. visitSwitchCase(CB);
  1082. }
  1083. /// visitSwitchCase - Emits the necessary code to represent a single node in
  1084. /// the binary search tree resulting from lowering a switch instruction.
  1085. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB) {
  1086. SDValue Cond;
  1087. SDValue CondLHS = getValue(CB.CmpLHS);
  1088. DebugLoc dl = getCurDebugLoc();
  1089. // Build the setcc now.
  1090. if (CB.CmpMHS == NULL) {
  1091. // Fold "(X == true)" to X and "(X == false)" to !X to
  1092. // handle common cases produced by branch lowering.
  1093. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  1094. CB.CC == ISD::SETEQ)
  1095. Cond = CondLHS;
  1096. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  1097. CB.CC == ISD::SETEQ) {
  1098. SDValue True = DAG.getConstant(1, CondLHS.getValueType());
  1099. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  1100. } else
  1101. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
  1102. } else {
  1103. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  1104. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  1105. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  1106. SDValue CmpOp = getValue(CB.CmpMHS);
  1107. EVT VT = CmpOp.getValueType();
  1108. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  1109. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
  1110. ISD::SETLE);
  1111. } else {
  1112. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  1113. VT, CmpOp, DAG.getConstant(Low, VT));
  1114. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  1115. DAG.getConstant(High-Low, VT), ISD::SETULE);
  1116. }
  1117. }
  1118. // Update successor info
  1119. CurMBB->addSuccessor(CB.TrueBB);
  1120. CurMBB->addSuccessor(CB.FalseBB);
  1121. // Set NextBlock to be the MBB immediately after the current one, if any.
  1122. // This is used to avoid emitting unnecessary branches to the next block.
  1123. MachineBasicBlock *NextBlock = 0;
  1124. MachineFunction::iterator BBI = CurMBB;
  1125. if (++BBI != FuncInfo.MF->end())
  1126. NextBlock = BBI;
  1127. // If the lhs block is the next block, invert the condition so that we can
  1128. // fall through to the lhs instead of the rhs block.
  1129. if (CB.TrueBB == NextBlock) {
  1130. std::swap(CB.TrueBB, CB.FalseBB);
  1131. SDValue True = DAG.getConstant(1, Cond.getValueType());
  1132. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  1133. }
  1134. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1135. MVT::Other, getControlRoot(), Cond,
  1136. DAG.getBasicBlock(CB.TrueBB));
  1137. // If the branch was constant folded, fix up the CFG.
  1138. if (BrCond.getOpcode() == ISD::BR) {
  1139. CurMBB->removeSuccessor(CB.FalseBB);
  1140. } else {
  1141. // Otherwise, go ahead and insert the false branch.
  1142. if (BrCond == getControlRoot())
  1143. CurMBB->removeSuccessor(CB.TrueBB);
  1144. if (CB.FalseBB != NextBlock)
  1145. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  1146. DAG.getBasicBlock(CB.FalseBB));
  1147. }
  1148. DAG.setRoot(BrCond);
  1149. }
  1150. /// visitJumpTable - Emit JumpTable node in the current MBB
  1151. void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
  1152. // Emit the code for the jump table
  1153. assert(JT.Reg != -1U && "Should lower JT Header first!");
  1154. EVT PTy = TLI.getPointerTy();
  1155. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
  1156. JT.Reg, PTy);
  1157. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  1158. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
  1159. MVT::Other, Index.getValue(1),
  1160. Table, Index);
  1161. DAG.setRoot(BrJumpTable);
  1162. }
  1163. /// visitJumpTableHeader - This function emits necessary code to produce index
  1164. /// in the JumpTable from switch case.
  1165. void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
  1166. JumpTableHeader &JTH) {
  1167. // Subtract the lowest switch case value from the value being switched on and
  1168. // conditional branch to default mbb if the result is greater than the
  1169. // difference between smallest and largest cases.
  1170. SDValue SwitchOp = getValue(JTH.SValue);
  1171. EVT VT = SwitchOp.getValueType();
  1172. SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
  1173. DAG.getConstant(JTH.First, VT));
  1174. // The SDNode we just created, which holds the value being switched on minus
  1175. // the smallest case value, needs to be copied to a virtual register so it
  1176. // can be used as an index into the jump table in a subsequent basic block.
  1177. // This value may be smaller or larger than the target's pointer type, and
  1178. // therefore require extension or truncating.
  1179. SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
  1180. unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
  1181. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
  1182. JumpTableReg, SwitchOp);
  1183. JT.Reg = JumpTableReg;
  1184. // Emit the range check for the jump table, and branch to the default block
  1185. // for the switch statement if the value being switched on exceeds the largest
  1186. // case in the switch.
  1187. SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
  1188. TLI.getSetCCResultType(Sub.getValueType()), Sub,
  1189. DAG.getConstant(JTH.Last-JTH.First,VT),
  1190. ISD::SETUGT);
  1191. // Set NextBlock to be the MBB immediately after the current one, if any.
  1192. // This is used to avoid emitting unnecessary branches to the next block.
  1193. MachineBasicBlock *NextBlock = 0;
  1194. MachineFunction::iterator BBI = CurMBB;
  1195. if (++BBI != FuncInfo.MF->end())
  1196. NextBlock = BBI;
  1197. SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
  1198. MVT::Other, CopyTo, CMP,
  1199. DAG.getBasicBlock(JT.Default));
  1200. if (JT.MBB != NextBlock)
  1201. BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
  1202. DAG.getBasicBlock(JT.MBB));
  1203. DAG.setRoot(BrCond);
  1204. }
  1205. /// visitBitTestHeader - This function emits necessary code to produce value
  1206. /// suitable for "bit tests"
  1207. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B) {
  1208. // Subtract the minimum value
  1209. SDValue SwitchOp = getValue(B.SValue);
  1210. EVT VT = SwitchOp.getValueType();
  1211. SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
  1212. DAG.getConstant(B.First, VT));
  1213. // Check range
  1214. SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
  1215. TLI.getSetCCResultType(Sub.getValueType()),
  1216. Sub, DAG.getConstant(B.Range, VT),
  1217. ISD::SETUGT);
  1218. SDValue ShiftOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(),
  1219. TLI.getPointerTy());
  1220. B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
  1221. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
  1222. B.Reg, ShiftOp);
  1223. // Set NextBlock to be the MBB immediately after the current one, if any.
  1224. // This is used to avoid emitting unnecessary branches to the next block.
  1225. MachineBasicBlock *NextBlock = 0;
  1226. MachineFunction::iterator BBI = CurMBB;
  1227. if (++BBI != FuncInfo.MF->end())
  1228. NextBlock = BBI;
  1229. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  1230. CurMBB->addSuccessor(B.Default);
  1231. CurMBB->addSuccessor(MBB);
  1232. SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
  1233. MVT::Other, CopyTo, RangeCmp,
  1234. DAG.getBasicBlock(B.Default));
  1235. if (MBB != NextBlock)
  1236. BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
  1237. DAG.getBasicBlock(MBB));
  1238. DAG.setRoot(BrRange);
  1239. }
  1240. /// visitBitTestCase - this function produces one "bit test"
  1241. void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB,
  1242. unsigned Reg,
  1243. BitTestCase &B) {
  1244. // Make desired shift
  1245. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
  1246. TLI.getPointerTy());
  1247. SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
  1248. TLI.getPointerTy(),
  1249. DAG.getConstant(1, TLI.getPointerTy()),
  1250. ShiftOp);
  1251. // Emit bit tests and jumps
  1252. SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
  1253. TLI.getPointerTy(), SwitchVal,
  1254. DAG.getConstant(B.Mask, TLI.getPointerTy()));
  1255. SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
  1256. TLI.getSetCCResultType(AndOp.getValueType()),
  1257. AndOp, DAG.getConstant(0, TLI.getPointerTy()),
  1258. ISD::SETNE);
  1259. CurMBB->addSuccessor(B.TargetBB);
  1260. CurMBB->addSuccessor(NextMBB);
  1261. SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
  1262. MVT::Other, getControlRoot(),
  1263. AndCmp, DAG.getBasicBlock(B.TargetBB));
  1264. // Set NextBlock to be the MBB immediately after the current one, if any.
  1265. // This is used to avoid emitting unnecessary branches to the next block.
  1266. MachineBasicBlock *NextBlock = 0;
  1267. MachineFunction::iterator BBI = CurMBB;
  1268. if (++BBI != FuncInfo.MF->end())
  1269. NextBlock = BBI;
  1270. if (NextMBB != NextBlock)
  1271. BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
  1272. DAG.getBasicBlock(NextMBB));
  1273. DAG.setRoot(BrAnd);
  1274. }
  1275. void SelectionDAGBuilder::visitInvoke(InvokeInst &I) {
  1276. // Retrieve successors.
  1277. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  1278. MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
  1279. const Value *Callee(I.getCalledValue());
  1280. if (isa<InlineAsm>(Callee))
  1281. visitInlineAsm(&I);
  1282. else
  1283. LowerCallTo(&I, getValue(Callee), false, LandingPad);
  1284. // If the value of the invoke is used outside of its defining block, make it
  1285. // available as a virtual register.
  1286. CopyToExportRegsIfNeeded(&I);
  1287. // Update successor info
  1288. CurMBB->addSuccessor(Return);
  1289. CurMBB->addSuccessor(LandingPad);
  1290. // Drop into normal successor.
  1291. DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
  1292. MVT::Other, getControlRoot(),
  1293. DAG.getBasicBlock(Return)));
  1294. }
  1295. void SelectionDAGBuilder::visitUnwind(UnwindInst &I) {
  1296. }
  1297. /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
  1298. /// small case ranges).
  1299. bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
  1300. CaseRecVector& WorkList,
  1301. Value* SV,
  1302. MachineBasicBlock* Default) {
  1303. Case& BackCase = *(CR.Range.second-1);
  1304. // Size is the number of Cases represented by this range.
  1305. size_t Size = CR.Range.second - CR.Range.first;
  1306. if (Size > 3)
  1307. return false;
  1308. // Get the MachineFunction which holds the current MBB. This is used when
  1309. // inserting any additional MBBs necessary to represent the switch.
  1310. MachineFunction *CurMF = FuncInfo.MF;
  1311. // Figure out which block is immediately after the current one.
  1312. MachineBasicBlock *NextBlock = 0;
  1313. MachineFunction::iterator BBI = CR.CaseBB;
  1314. if (++BBI != FuncInfo.MF->end())
  1315. NextBlock = BBI;
  1316. // TODO: If any two of the cases has the same destination, and if one value
  1317. // is the same as the other, but has one bit unset that the other has set,
  1318. // use bit manipulation to do two compares at once. For example:
  1319. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  1320. // Rearrange the case blocks so that the last one falls through if possible.
  1321. if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
  1322. // The last case block won't fall through into 'NextBlock' if we emit the
  1323. // branches in this order. See if rearranging a case value would help.
  1324. for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
  1325. if (I->BB == NextBlock) {
  1326. std::swap(*I, BackCase);
  1327. break;
  1328. }
  1329. }
  1330. }
  1331. // Create a CaseBlock record representing a conditional branch to
  1332. // the Case's target mbb if the value being switched on SV is equal
  1333. // to C.
  1334. MachineBasicBlock *CurBlock = CR.CaseBB;
  1335. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
  1336. MachineBasicBlock *FallThrough;
  1337. if (I != E-1) {
  1338. FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
  1339. CurMF->insert(BBI, FallThrough);
  1340. // Put SV in a virtual register to make it available from the new blocks.
  1341. ExportFromCurrentBlock(SV);
  1342. } else {
  1343. // If the last case doesn't match, go to the default block.
  1344. FallThrough = Default;
  1345. }
  1346. Value *RHS, *LHS, *MHS;
  1347. ISD::CondCode CC;
  1348. if (I->High == I->Low) {
  1349. // This is just small small case range :) containing exactly 1 case
  1350. CC = ISD::SETEQ;
  1351. LHS = SV; RHS = I->High; MHS = NULL;
  1352. } else {
  1353. CC = ISD::SETLE;
  1354. LHS = I->Low; MHS = SV; RHS = I->High;
  1355. }
  1356. CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
  1357. // If emitting the first comparison, just call visitSwitchCase to emit the
  1358. // code into the current block. Otherwise, push the CaseBlock onto the
  1359. // vector to be later processed by SDISel, and insert the node's MBB
  1360. // before the next MBB.
  1361. if (CurBlock == CurMBB)
  1362. visitSwitchCase(CB);
  1363. else
  1364. SwitchCases.push_back(CB);
  1365. CurBlock = FallThrough;
  1366. }
  1367. return true;
  1368. }
  1369. static inline bool areJTsAllowed(const TargetLowering &TLI) {
  1370. return !DisableJumpTables &&
  1371. (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
  1372. TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
  1373. }
  1374. static APInt ComputeRange(const APInt &First, const APInt &Last) {
  1375. APInt LastExt(Last), FirstExt(First);
  1376. uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
  1377. LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
  1378. return (LastExt - FirstExt + 1ULL);
  1379. }
  1380. /// handleJTSwitchCase - Emit jumptable for current switch case range
  1381. bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
  1382. CaseRecVector& WorkList,
  1383. Value* SV,
  1384. MachineBasicBlock* Default) {
  1385. Case& FrontCase = *CR.Range.first;
  1386. Case& BackCase = *(CR.Range.second-1);
  1387. const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
  1388. const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
  1389. APInt TSize(First.getBitWidth(), 0);
  1390. for (CaseItr I = CR.Range.first, E = CR.Range.second;
  1391. I!=E; ++I)
  1392. TSize += I->size();
  1393. if (!areJTsAllowed(TLI) || TSize.ult(APInt(First.getBitWidth(), 4)))
  1394. return false;
  1395. APInt Range = ComputeRange(First, Last);
  1396. double Density = TSize.roundToDouble() / Range.roundToDouble();
  1397. if (Density < 0.4)
  1398. return false;
  1399. DEBUG(dbgs() << "Lowering jump table\n"
  1400. << "First entry: " << First << ". Last entry: " << Last << '\n'
  1401. << "Range: " << Range
  1402. << "Size: " << TSize << ". Density: " << Density << "\n\n");
  1403. // Get the MachineFunction which holds the current MBB. This is used when
  1404. // inserting any additional MBBs necessary to represent the switch.
  1405. MachineFunction *CurMF = FuncInfo.MF;
  1406. // Figure out which block is immediately after the current one.
  1407. MachineFunction::iterator BBI = CR.CaseBB;
  1408. ++BBI;
  1409. const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
  1410. // Create a new basic block to hold the code for loading the address
  1411. // of the jump table, and jumping to it. Update successor information;
  1412. // we will either branch to the default case for the switch, or the jump
  1413. // table.
  1414. MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  1415. CurMF->insert(BBI, JumpTableBB);
  1416. CR.CaseBB->addSuccessor(Default);
  1417. CR.CaseBB->addSuccessor(JumpTableBB);
  1418. // Build a vector of destination BBs, corresponding to each target
  1419. // of the jump table. If the value of the jump table slot corresponds to
  1420. // a case statement, push the case's BB onto the vector, otherwise, push
  1421. // the default BB.
  1422. std::vector<MachineBasicBlock*> DestBBs;
  1423. APInt TEI = First;
  1424. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
  1425. const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
  1426. const APInt &High = cast<ConstantInt>(I->High)->getValue();
  1427. if (Low.sle(TEI) && TEI.sle(High)) {
  1428. DestBBs.push_back(I->BB);
  1429. if (TEI==High)
  1430. ++I;
  1431. } else {
  1432. DestBBs.push_back(Default);
  1433. }
  1434. }
  1435. // Update successor info. Add one edge to each unique successor.
  1436. BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
  1437. for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
  1438. E = DestBBs.end(); I != E; ++I) {
  1439. if (!SuccsHandled[(*I)->getNumber()]) {
  1440. SuccsHandled[(*I)->getNumber()] = true;
  1441. JumpTableBB->addSuccessor(*I);
  1442. }
  1443. }
  1444. // Create a jump table index for this jump table, or return an existing
  1445. // one.
  1446. unsigned JTEncoding = TLI.getJumpTableEncoding();
  1447. unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
  1448. ->getJumpTableIndex(DestBBs);
  1449. // Set the jump table information so that we can codegen it as a second
  1450. // MachineBasicBlock
  1451. JumpTable JT(-1U, JTI, JumpTableBB, Default);
  1452. JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
  1453. if (CR.CaseBB == CurMBB)
  1454. visitJumpTableHeader(JT, JTH);
  1455. JTCases.push_back(JumpTableBlock(JTH, JT));
  1456. return true;
  1457. }
  1458. /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
  1459. /// 2 subtrees.
  1460. bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
  1461. CaseRecVector& WorkList,
  1462. Value* SV,
  1463. MachineBasicBlock* Default) {
  1464. // Get the MachineFunction which holds the current MBB. This is used when
  1465. // inserting any additional MBBs necessary to represent the switch.
  1466. MachineFunction *CurMF = FuncInfo.MF;
  1467. // Figure out which block is immediately after the current one.
  1468. MachineFunction::iterator BBI = CR.CaseBB;
  1469. ++BBI;
  1470. Case& FrontCase = *CR.Range.first;
  1471. Case& BackCase = *(CR.Range.second-1);
  1472. const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
  1473. // Size is the number of Cases represented by this range.
  1474. unsigned Size = CR.Range.second - CR.Range.first;
  1475. const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
  1476. const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
  1477. double FMetric = 0;
  1478. CaseItr Pivot = CR.Range.first + Size/2;
  1479. // Select optimal pivot, maximizing sum density of LHS and RHS. This will
  1480. // (heuristically) allow us to emit JumpTable's later.
  1481. APInt TSize(First.getBitWidth(), 0);
  1482. for (CaseItr I = CR.Range.first, E = CR.Range.second;
  1483. I!=E; ++I)
  1484. TSize += I->size();
  1485. APInt LSize = FrontCase.size();
  1486. APInt RSize = TSize-LSize;
  1487. DEBUG(dbgs() << "Selecting best pivot: \n"
  1488. << "First: " << First << ", Last: " << Last <<'\n'
  1489. << "LSize: " << LSize << ", RSize: " << RSize << '\n');
  1490. for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
  1491. J!=E; ++I, ++J) {
  1492. const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
  1493. const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
  1494. APInt Range = ComputeRange(LEnd, RBegin);
  1495. assert((Range - 2ULL).isNonNegative() &&
  1496. "Invalid case distance");
  1497. double LDensity = (double)LSize.roundToDouble() /
  1498. (LEnd - First + 1ULL).roundToDouble();
  1499. double RDensity = (double)RSize.roundToDouble() /
  1500. (Last - RBegin + 1ULL).roundToDouble();
  1501. double Metric = Range.logBase2()*(LDensity+RDensity);
  1502. // Should always split in some non-trivial place
  1503. DEBUG(dbgs() <<"=>Step\n"
  1504. << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
  1505. << "LDensity: " << LDensity
  1506. << ", RDensity: " << RDensity << '\n'
  1507. << "Metric: " << Metric << '\n');
  1508. if (FMetric < Metric) {
  1509. Pivot = J;
  1510. FMetric = Metric;
  1511. DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
  1512. }
  1513. LSize += J->size();
  1514. RSize -= J->size();
  1515. }
  1516. if (areJTsAllowed(TLI)) {
  1517. // If our case is dense we *really* should handle it earlier!
  1518. assert((FMetric > 0) && "Should handle dense range earlier!");
  1519. } else {
  1520. Pivot = CR.Range.first + Size/2;
  1521. }
  1522. CaseRange LHSR(CR.Range.first, Pivot);
  1523. CaseRange RHSR(Pivot, CR.Range.second);
  1524. Constant *C = Pivot->Low;
  1525. MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
  1526. // We know that we branch to the LHS if the Value being switched on is
  1527. // less than the Pivot value, C. We use this to optimize our binary
  1528. // tree a bit, by recognizing that if SV is greater than or equal to the
  1529. // LHS's Case Value, and that Case Value is exactly one less than the
  1530. // Pivot's Value, then we can branch directly to the LHS's Target,
  1531. // rather than creating a leaf node for it.
  1532. if ((LHSR.second - LHSR.first) == 1 &&
  1533. LHSR.first->High == CR.GE &&
  1534. cast<ConstantInt>(C)->getValue() ==
  1535. (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
  1536. TrueBB = LHSR.first->BB;
  1537. } else {
  1538. TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  1539. CurMF->insert(BBI, TrueBB);
  1540. WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
  1541. // Put SV in a virtual register to make it available from the new blocks.
  1542. ExportFromCurrentBlock(SV);
  1543. }
  1544. // Similar to the optimization above, if the Value being switched on is
  1545. // known to be less than the Constant CR.LT, and the current Case Value
  1546. // is CR.LT - 1, then we can branch directly to the target block for
  1547. // the current Case Value, rather than emitting a RHS leaf node for it.
  1548. if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
  1549. cast<ConstantInt>(RHSR.first->Low)->getValue() ==
  1550. (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
  1551. FalseBB = RHSR.first->BB;
  1552. } else {
  1553. FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  1554. CurMF->insert(BBI, FalseBB);
  1555. WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
  1556. // Put SV in a virtual register to make it available from the new blocks.
  1557. ExportFromCurrentBlock(SV);
  1558. }
  1559. // Create a CaseBlock record representing a conditional branch to
  1560. // the LHS node if the value being switched on SV is less than C.
  1561. // Otherwise, branch to LHS.
  1562. CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
  1563. if (CR.CaseBB == CurMBB)
  1564. visitSwitchCase(CB);
  1565. else
  1566. SwitchCases.push_back(CB);
  1567. return true;
  1568. }
  1569. /// handleBitTestsSwitchCase - if current case range has few destination and
  1570. /// range span less, than machine word bitwidth, encode case range into series
  1571. /// of masks and emit bit tests with these masks.
  1572. bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
  1573. CaseRecVector& WorkList,
  1574. Value* SV,
  1575. MachineBasicBlock* Default){
  1576. EVT PTy = TLI.getPointerTy();
  1577. unsigned IntPtrBits = PTy.getSizeInBits();
  1578. Case& FrontCase = *CR.Range.first;
  1579. Case& BackCase = *(CR.Range.second-1);
  1580. // Get the MachineFunction which holds the current MBB. This is used when
  1581. // inserting any additional MBBs necessary to represent the switch.
  1582. MachineFunction *CurMF = FuncInfo.MF;
  1583. // If target does not have legal shift left, do not emit bit tests at all.
  1584. if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
  1585. return false;
  1586. size_t numCmps = 0;
  1587. for (CaseItr I = CR.Range.first, E = CR.Range.second;
  1588. I!=E; ++I) {
  1589. // Single case counts one, case range - two.
  1590. numCmps += (I->Low == I->High ? 1 : 2);
  1591. }
  1592. // Count unique destinations
  1593. SmallSet<MachineBasicBlock*, 4> Dests;
  1594. for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
  1595. Dests.insert(I->BB);
  1596. if (Dests.size() > 3)
  1597. // Don't bother the code below, if there are too much unique destinations
  1598. return false;
  1599. }
  1600. DEBUG(dbgs() << "Total number of unique destinations: "
  1601. << Dests.size() << '\n'
  1602. << "Total number of comparisons: " << numCmps << '\n');
  1603. // Compute span of values.
  1604. const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
  1605. const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
  1606. APInt cmpRange = maxValue - minValue;
  1607. DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
  1608. << "Low bound: " << minValue << '\n'
  1609. << "High bound: " << maxValue << '\n');
  1610. if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
  1611. (!(Dests.size() == 1 && numCmps >= 3) &&
  1612. !(Dests.size() == 2 && numCmps >= 5) &&
  1613. !(Dests.size() >= 3 && numCmps >= 6)))
  1614. return false;
  1615. DEBUG(dbgs() << "Emitting bit tests\n");
  1616. APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
  1617. // Optimize the case where all the case values fit in a
  1618. // word without having to subtract minValue. In this case,
  1619. // we can optimize away the subtraction.
  1620. if (minValue.isNonNegative() &&
  1621. maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
  1622. cmpRange = maxValue;
  1623. } else {
  1624. lowBound = minValue;
  1625. }
  1626. CaseBitsVector CasesBits;
  1627. unsigned i, count = 0;
  1628. for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
  1629. MachineBasicBlock* Dest = I->BB;
  1630. for (i = 0; i < count; ++i)
  1631. if (Dest == CasesBits[i].BB)
  1632. break;
  1633. if (i == count) {
  1634. assert((count < 3) && "Too much destinations to test!");
  1635. CasesBits.push_back(CaseBits(0, Dest, 0));
  1636. count++;
  1637. }
  1638. const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
  1639. const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
  1640. uint64_t lo = (lowValue - lowBound).getZExtValue();
  1641. uint64_t hi = (highValue - lowBound).getZExtValue();
  1642. for (uint64_t j = lo; j <= hi; j++) {
  1643. CasesBits[i].Mask |= 1ULL << j;
  1644. CasesBits[i].Bits++;
  1645. }
  1646. }
  1647. std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
  1648. BitTestInfo BTC;
  1649. // Figure out which block is immediately after the current one.
  1650. MachineFunction::iterator BBI = CR.CaseBB;
  1651. ++BBI;
  1652. const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
  1653. DEBUG(dbgs() << "Cases:\n");
  1654. for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
  1655. DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
  1656. << ", Bits: " << CasesBits[i].Bits
  1657. << ", BB: " << CasesBits[i].BB << '\n');
  1658. MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  1659. CurMF->insert(BBI, CaseBB);
  1660. BTC.push_back(BitTestCase(CasesBits[i].Mask,
  1661. CaseBB,
  1662. CasesBits[i].BB));
  1663. // Put SV in a virtual register to make it available from the new blocks.
  1664. ExportFromCurrentBlock(SV);
  1665. }
  1666. BitTestBlock BTB(lowBound, cmpRange, SV,
  1667. -1U, (CR.CaseBB == CurMBB),
  1668. CR.CaseBB, Default, BTC);
  1669. if (CR.CaseBB == CurMBB)
  1670. visitBitTestHeader(BTB);
  1671. BitTestCases.push_back(BTB);
  1672. return true;
  1673. }
  1674. /// Clusterify - Transform simple list of Cases into list of CaseRange's
  1675. size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
  1676. const SwitchInst& SI) {
  1677. size_t numCmps = 0;
  1678. // Start with "simple" cases
  1679. for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
  1680. MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
  1681. Cases.push_back(Case(SI.getSuccessorValue(i),
  1682. SI.getSuccessorValue(i),
  1683. SMBB));
  1684. }
  1685. std::sort(Cases.begin(), Cases.end(), CaseCmp());
  1686. // Merge case into clusters
  1687. if (Cases.size() >= 2)
  1688. // Must recompute end() each iteration because it may be
  1689. // invalidated by erase if we hold on to it
  1690. for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
  1691. const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
  1692. const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
  1693. MachineBasicBlock* nextBB = J->BB;
  1694. MachineBasicBlock* currentBB = I->BB;
  1695. // If the two neighboring cases go to the same destination, merge them
  1696. // into a single case.
  1697. if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
  1698. I->High = J->High;
  1699. J = Cases.erase(J);
  1700. } else {
  1701. I = J++;
  1702. }
  1703. }
  1704. for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
  1705. if (I->Low != I->High)
  1706. // A range counts double, since it requires two compares.
  1707. ++numCmps;
  1708. }
  1709. return numCmps;
  1710. }
  1711. void SelectionDAGBuilder::visitSwitch(SwitchInst &SI) {
  1712. // Figure out which block is immediately after the current one.
  1713. MachineBasicBlock *NextBlock = 0;
  1714. MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
  1715. // If there is only the default destination, branch to it if it is not the
  1716. // next basic block. Otherwise, just fall through.
  1717. if (SI.getNumOperands() == 2) {
  1718. // Update machine-CFG edges.
  1719. // If this is not a fall-through branch, emit the branch.
  1720. CurMBB->addSuccessor(Default);
  1721. if (Default != NextBlock)
  1722. DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
  1723. MVT::Other, getControlRoot(),
  1724. DAG.getBasicBlock(Default)));
  1725. return;
  1726. }
  1727. // If there are any non-default case statements, create a vector of Cases
  1728. // representing each one, and sort the vector so that we can efficiently
  1729. // create a binary search tree from them.
  1730. CaseVector Cases;
  1731. size_t numCmps = Clusterify(Cases, SI);
  1732. DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
  1733. << ". Total compares: " << numCmps << '\n');
  1734. numCmps = 0;
  1735. // Get the Value to be switched on and default basic blocks, which will be
  1736. // inserted into CaseBlock records, representing basic blocks in the binary
  1737. // search tree.
  1738. Value *SV = SI.getOperand(0);
  1739. // Push the initial CaseRec onto the worklist
  1740. CaseRecVector WorkList;
  1741. WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
  1742. while (!WorkList.empty()) {
  1743. // Grab a record representing a case range to process off the worklist
  1744. CaseRec CR = WorkList.back();
  1745. WorkList.pop_back();
  1746. if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
  1747. continue;
  1748. // If the range has few cases (two or less) emit a series of specific
  1749. // tests.
  1750. if (handleSmallSwitchRange(CR, WorkList, SV, Default))
  1751. continue;
  1752. // If the switch has more than 5 blocks, and at least 40% dense, and the
  1753. // target supports indirect branches, then emit a jump table rather than
  1754. // lowering the switch to a binary tree of conditional branches.
  1755. if (handleJTSwitchCase(CR, WorkList, SV, Default))
  1756. continue;
  1757. // Emit binary tree. We need to pick a pivot, and push left and right ranges
  1758. // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
  1759. handleBTSplitSwitchCase(CR, WorkList, SV, Default);
  1760. }
  1761. }
  1762. void SelectionDAGBuilder::visitIndirectBr(IndirectBrInst &I) {
  1763. // Update machine-CFG edges with unique successors.
  1764. SmallVector<BasicBlock*, 32> succs;
  1765. succs.reserve(I.getNumSuccessors());
  1766. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
  1767. succs.push_back(I.getSuccessor(i));
  1768. array_pod_sort(succs.begin(), succs.end());
  1769. succs.erase(std::unique(succs.begin(), succs.end()), succs.end());
  1770. for (unsigned i = 0, e = succs.size(); i != e; ++i)
  1771. CurMBB->addSuccessor(FuncInfo.MBBMap[succs[i]]);
  1772. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
  1773. MVT::Other, getControlRoot(),
  1774. getValue(I.getAddress())));
  1775. }
  1776. void SelectionDAGBuilder::visitFSub(User &I) {
  1777. // -0.0 - X --> fneg
  1778. const Type *Ty = I.getType();
  1779. if (Ty->isVectorTy()) {
  1780. if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
  1781. const VectorType *DestTy = cast<VectorType>(I.getType());
  1782. const Type *ElTy = DestTy->getElementType();
  1783. unsigned VL = DestTy->getNumElements();
  1784. std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
  1785. Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
  1786. if (CV == CNZ) {
  1787. SDValue Op2 = getValue(I.getOperand(1));
  1788. setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
  1789. Op2.getValueType(), Op2));
  1790. return;
  1791. }
  1792. }
  1793. }
  1794. if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
  1795. if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
  1796. SDValue Op2 = getValue(I.getOperand(1));
  1797. setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
  1798. Op2.getValueType(), Op2));
  1799. return;
  1800. }
  1801. visitBinary(I, ISD::FSUB);
  1802. }
  1803. void SelectionDAGBuilder::visitBinary(User &I, unsigned OpCode) {
  1804. SDValue Op1 = getValue(I.getOperand(0));
  1805. SDValue Op2 = getValue(I.getOperand(1));
  1806. setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
  1807. Op1.getValueType(), Op1, Op2));
  1808. }
  1809. void SelectionDAGBuilder::visitShift(User &I, unsigned Opcode) {
  1810. SDValue Op1 = getValue(I.getOperand(0));
  1811. SDValue Op2 = getValue(I.getOperand(1));
  1812. if (!I.getType()->isVectorTy() &&
  1813. Op2.getValueType() != TLI.getShiftAmountTy()) {
  1814. // If the operand is smaller than the shift count type, promote it.
  1815. EVT PTy = TLI.getPointerTy();
  1816. EVT STy = TLI.getShiftAmountTy();
  1817. if (STy.bitsGT(Op2.getValueType()))
  1818. Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
  1819. TLI.getShiftAmountTy(), Op2);
  1820. // If the operand is larger than the shift count type but the shift
  1821. // count type has enough bits to represent any shift value, truncate
  1822. // it now. This is a common case and it exposes the truncate to
  1823. // optimization early.
  1824. else if (STy.getSizeInBits() >=
  1825. Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
  1826. Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
  1827. TLI.getShiftAmountTy(), Op2);
  1828. // Otherwise we'll need to temporarily settle for some other
  1829. // convenient type; type legalization will make adjustments as
  1830. // needed.
  1831. else if (PTy.bitsLT(Op2.getValueType()))
  1832. Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
  1833. TLI.getPointerTy(), Op2);
  1834. else if (PTy.bitsGT(Op2.getValueType()))
  1835. Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
  1836. TLI.getPointerTy(), Op2);
  1837. }
  1838. setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
  1839. Op1.getValueType(), Op1, Op2));
  1840. }
  1841. void SelectionDAGBuilder::visitICmp(User &I) {
  1842. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  1843. if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  1844. predicate = IC->getPredicate();
  1845. else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  1846. predicate = ICmpInst::Predicate(IC->getPredicate());
  1847. SDValue Op1 = getValue(I.getOperand(0));
  1848. SDValue Op2 = getValue(I.getOperand(1));
  1849. ISD::CondCode Opcode = getICmpCondCode(predicate);
  1850. EVT DestVT = TLI.getValueType(I.getType());
  1851. setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
  1852. }
  1853. void SelectionDAGBuilder::visitFCmp(User &I) {
  1854. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  1855. if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  1856. predicate = FC->getPredicate();
  1857. else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  1858. predicate = FCmpInst::Predicate(FC->getPredicate());
  1859. SDValue Op1 = getValue(I.getOperand(0));
  1860. SDValue Op2 = getValue(I.getOperand(1));
  1861. ISD::CondCode Condition = getFCmpCondCode(predicate);
  1862. EVT DestVT = TLI.getValueType(I.getType());
  1863. setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
  1864. }
  1865. void SelectionDAGBuilder::visitSelect(User &I) {
  1866. SmallVector<EVT, 4> ValueVTs;
  1867. ComputeValueVTs(TLI, I.getType(), ValueVTs);
  1868. unsigned NumValues = ValueVTs.size();
  1869. if (NumValues == 0) return;
  1870. SmallVector<SDValue, 4> Values(NumValues);
  1871. SDValue Cond = getValue(I.getOperand(0));
  1872. SDValue TrueVal = getValue(I.getOperand(1));
  1873. SDValue FalseVal = getValue(I.getOperand(2));
  1874. for (unsigned i = 0; i != NumValues; ++i)
  1875. Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
  1876. TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
  1877. Cond,
  1878. SDValue(TrueVal.getNode(),
  1879. TrueVal.getResNo() + i),
  1880. SDValue(FalseVal.getNode(),
  1881. FalseVal.getResNo() + i));
  1882. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
  1883. DAG.getVTList(&ValueVTs[0], NumValues),
  1884. &Values[0], NumValues));
  1885. }
  1886. void SelectionDAGBuilder::visitTrunc(User &I) {
  1887. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  1888. SDValue N = getValue(I.getOperand(0));
  1889. EVT DestVT = TLI.getValueType(I.getType());
  1890. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
  1891. }
  1892. void SelectionDAGBuilder::visitZExt(User &I) {
  1893. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  1894. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  1895. SDValue N = getValue(I.getOperand(0));
  1896. EVT DestVT = TLI.getValueType(I.getType());
  1897. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
  1898. }
  1899. void SelectionDAGBuilder::visitSExt(User &I) {
  1900. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  1901. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  1902. SDValue N = getValue(I.getOperand(0));
  1903. EVT DestVT = TLI.getValueType(I.getType());
  1904. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
  1905. }
  1906. void SelectionDAGBuilder::visitFPTrunc(User &I) {
  1907. // FPTrunc is never a no-op cast, no need to check
  1908. SDValue N = getValue(I.getOperand(0));
  1909. EVT DestVT = TLI.getValueType(I.getType());
  1910. setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
  1911. DestVT, N, DAG.getIntPtrConstant(0)));
  1912. }
  1913. void SelectionDAGBuilder::visitFPExt(User &I){
  1914. // FPTrunc is never a no-op cast, no need to check
  1915. SDValue N = getValue(I.getOperand(0));
  1916. EVT DestVT = TLI.getValueType(I.getType());
  1917. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
  1918. }
  1919. void SelectionDAGBuilder::visitFPToUI(User &I) {
  1920. // FPToUI is never a no-op cast, no need to check
  1921. SDValue N = getValue(I.getOperand(0));
  1922. EVT DestVT = TLI.getValueType(I.getType());
  1923. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
  1924. }
  1925. void SelectionDAGBuilder::visitFPToSI(User &I) {
  1926. // FPToSI is never a no-op cast, no need to check
  1927. SDValue N = getValue(I.getOperand(0));
  1928. EVT DestVT = TLI.getValueType(I.getType());
  1929. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
  1930. }
  1931. void SelectionDAGBuilder::visitUIToFP(User &I) {
  1932. // UIToFP is never a no-op cast, no need to check
  1933. SDValue N = getValue(I.getOperand(0));
  1934. EVT DestVT = TLI.getValueType(I.getType());
  1935. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
  1936. }
  1937. void SelectionDAGBuilder::visitSIToFP(User &I){
  1938. // SIToFP is never a no-op cast, no need to check
  1939. SDValue N = getValue(I.getOperand(0));
  1940. EVT DestVT = TLI.getValueType(I.getType());
  1941. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
  1942. }
  1943. void SelectionDAGBuilder::visitPtrToInt(User &I) {
  1944. // What to do depends on the size of the integer and the size of the pointer.
  1945. // We can either truncate, zero extend, or no-op, accordingly.
  1946. SDValue N = getValue(I.getOperand(0));
  1947. EVT SrcVT = N.getValueType();
  1948. EVT DestVT = TLI.getValueType(I.getType());
  1949. setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
  1950. }
  1951. void SelectionDAGBuilder::visitIntToPtr(User &I) {
  1952. // What to do depends on the size of the integer and the size of the pointer.
  1953. // We can either truncate, zero extend, or no-op, accordingly.
  1954. SDValue N = getValue(I.getOperand(0));
  1955. EVT SrcVT = N.getValueType();
  1956. EVT DestVT = TLI.getValueType(I.getType());
  1957. setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
  1958. }
  1959. void SelectionDAGBuilder::visitBitCast(User &I) {
  1960. SDValue N = getValue(I.getOperand(0));
  1961. EVT DestVT = TLI.getValueType(I.getType());
  1962. // BitCast assures us that source and destination are the same size so this is
  1963. // either a BIT_CONVERT or a no-op.
  1964. if (DestVT != N.getValueType())
  1965. setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
  1966. DestVT, N)); // convert types.
  1967. else
  1968. setValue(&I, N); // noop cast.
  1969. }
  1970. void SelectionDAGBuilder::visitInsertElement(User &I) {
  1971. SDValue InVec = getValue(I.getOperand(0));
  1972. SDValue InVal = getValue(I.getOperand(1));
  1973. SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
  1974. TLI.getPointerTy(),
  1975. getValue(I.getOperand(2)));
  1976. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
  1977. TLI.getValueType(I.getType()),
  1978. InVec, InVal, InIdx));
  1979. }
  1980. void SelectionDAGBuilder::visitExtractElement(User &I) {
  1981. SDValue InVec = getValue(I.getOperand(0));
  1982. SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
  1983. TLI.getPointerTy(),
  1984. getValue(I.getOperand(1)));
  1985. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
  1986. TLI.getValueType(I.getType()), InVec, InIdx));
  1987. }
  1988. // Utility for visitShuffleVector - Returns true if the mask is mask starting
  1989. // from SIndx and increasing to the element length (undefs are allowed).
  1990. static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
  1991. unsigned MaskNumElts = Mask.size();
  1992. for (unsigned i = 0; i != MaskNumElts; ++i)
  1993. if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
  1994. return false;
  1995. return true;
  1996. }
  1997. void SelectionDAGBuilder::visitShuffleVector(User &I) {
  1998. SmallVector<int, 8> Mask;
  1999. SDValue Src1 = getValue(I.getOperand(0));
  2000. SDValue Src2 = getValue(I.getOperand(1));
  2001. // Convert the ConstantVector mask operand into an array of ints, with -1
  2002. // representing undef values.
  2003. SmallVector<Constant*, 8> MaskElts;
  2004. cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
  2005. unsigned MaskNumElts = MaskElts.size();
  2006. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2007. if (isa<UndefValue>(MaskElts[i]))
  2008. Mask.push_back(-1);
  2009. else
  2010. Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
  2011. }
  2012. EVT VT = TLI.getValueType(I.getType());
  2013. EVT SrcVT = Src1.getValueType();
  2014. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  2015. if (SrcNumElts == MaskNumElts) {
  2016. setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
  2017. &Mask[0]));
  2018. return;
  2019. }
  2020. // Normalize the shuffle vector since mask and vector length don't match.
  2021. if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
  2022. // Mask is longer than the source vectors and is a multiple of the source
  2023. // vectors. We can use concatenate vector to make the mask and vectors
  2024. // lengths match.
  2025. if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
  2026. // The shuffle is concatenating two vectors together.
  2027. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
  2028. VT, Src1, Src2));
  2029. return;
  2030. }
  2031. // Pad both vectors with undefs to make them the same length as the mask.
  2032. unsigned NumConcat = MaskNumElts / SrcNumElts;
  2033. bool Src1U = Src1.getOpcode() == ISD::UNDEF;
  2034. bool Src2U = Src2.getOpcode() == ISD::UNDEF;
  2035. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  2036. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  2037. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  2038. MOps1[0] = Src1;
  2039. MOps2[0] = Src2;
  2040. Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
  2041. getCurDebugLoc(), VT,
  2042. &MOps1[0], NumConcat);
  2043. Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
  2044. getCurDebugLoc(), VT,
  2045. &MOps2[0], NumConcat);
  2046. // Readjust mask for new input vector length.
  2047. SmallVector<int, 8> MappedOps;
  2048. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2049. int Idx = Mask[i];
  2050. if (Idx < (int)SrcNumElts)
  2051. MappedOps.push_back(Idx);
  2052. else
  2053. MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
  2054. }
  2055. setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
  2056. &MappedOps[0]));
  2057. return;
  2058. }
  2059. if (SrcNumElts > MaskNumElts) {
  2060. // Analyze the access pattern of the vector to see if we can extract
  2061. // two subvectors and do the shuffle. The analysis is done by calculating
  2062. // the range of elements the mask access on both vectors.
  2063. int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
  2064. int MaxRange[2] = {-1, -1};
  2065. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2066. int Idx = Mask[i];
  2067. int Input = 0;
  2068. if (Idx < 0)
  2069. continue;
  2070. if (Idx >= (int)SrcNumElts) {
  2071. Input = 1;
  2072. Idx -= SrcNumElts;
  2073. }
  2074. if (Idx > MaxRange[Input])
  2075. MaxRange[Input] = Idx;
  2076. if (Idx < MinRange[Input])
  2077. MinRange[Input] = Idx;
  2078. }
  2079. // Check if the access is smaller than the vector size and can we find
  2080. // a reasonable extract index.
  2081. int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
  2082. // Extract.
  2083. int StartIdx[2]; // StartIdx to extract from
  2084. for (int Input=0; Input < 2; ++Input) {
  2085. if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
  2086. RangeUse[Input] = 0; // Unused
  2087. StartIdx[Input] = 0;
  2088. } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
  2089. // Fits within range but we should see if we can find a good
  2090. // start index that is a multiple of the mask length.
  2091. if (MaxRange[Input] < (int)MaskNumElts) {
  2092. RangeUse[Input] = 1; // Extract from beginning of the vector
  2093. StartIdx[Input] = 0;
  2094. } else {
  2095. StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
  2096. if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
  2097. StartIdx[Input] + MaskNumElts < SrcNumElts)
  2098. RangeUse[Input] = 1; // Extract from a multiple of the mask length.
  2099. }
  2100. }
  2101. }
  2102. if (RangeUse[0] == 0 && RangeUse[1] == 0) {
  2103. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  2104. return;
  2105. }
  2106. else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
  2107. // Extract appropriate subvector and generate a vector shuffle
  2108. for (int Input=0; Input < 2; ++Input) {
  2109. SDValue &Src = Input == 0 ? Src1 : Src2;
  2110. if (RangeUse[Input] == 0)
  2111. Src = DAG.getUNDEF(VT);
  2112. else
  2113. Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
  2114. Src, DAG.getIntPtrConstant(StartIdx[Input]));
  2115. }
  2116. // Calculate new mask.
  2117. SmallVector<int, 8> MappedOps;
  2118. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2119. int Idx = Mask[i];
  2120. if (Idx < 0)
  2121. MappedOps.push_back(Idx);
  2122. else if (Idx < (int)SrcNumElts)
  2123. MappedOps.push_back(Idx - StartIdx[0]);
  2124. else
  2125. MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
  2126. }
  2127. setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
  2128. &MappedOps[0]));
  2129. return;
  2130. }
  2131. }
  2132. // We can't use either concat vectors or extract subvectors so fall back to
  2133. // replacing the shuffle with extract and build vector.
  2134. // to insert and build vector.
  2135. EVT EltVT = VT.getVectorElementType();
  2136. EVT PtrVT = TLI.getPointerTy();
  2137. SmallVector<SDValue,8> Ops;
  2138. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2139. if (Mask[i] < 0) {
  2140. Ops.push_back(DAG.getUNDEF(EltVT));
  2141. } else {
  2142. int Idx = Mask[i];
  2143. SDValue Res;
  2144. if (Idx < (int)SrcNumElts)
  2145. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
  2146. EltVT, Src1, DAG.getConstant(Idx, PtrVT));
  2147. else
  2148. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
  2149. EltVT, Src2,
  2150. DAG.getConstant(Idx - SrcNumElts, PtrVT));
  2151. Ops.push_back(Res);
  2152. }
  2153. }
  2154. setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
  2155. VT, &Ops[0], Ops.size()));
  2156. }
  2157. void SelectionDAGBuilder::visitInsertValue(InsertValueInst &I) {
  2158. const Value *Op0 = I.getOperand(0);
  2159. const Value *Op1 = I.getOperand(1);
  2160. const Type *AggTy = I.getType();
  2161. const Type *ValTy = Op1->getType();
  2162. bool IntoUndef = isa<UndefValue>(Op0);
  2163. bool FromUndef = isa<UndefValue>(Op1);
  2164. unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
  2165. I.idx_begin(), I.idx_end());
  2166. SmallVector<EVT, 4> AggValueVTs;
  2167. ComputeValueVTs(TLI, AggTy, AggValueVTs);
  2168. SmallVector<EVT, 4> ValValueVTs;
  2169. ComputeValueVTs(TLI, ValTy, ValValueVTs);
  2170. unsigned NumAggValues = AggValueVTs.size();
  2171. unsigned NumValValues = ValValueVTs.size();
  2172. SmallVector<SDValue, 4> Values(NumAggValues);
  2173. SDValue Agg = getValue(Op0);
  2174. SDValue Val = getValue(Op1);
  2175. unsigned i = 0;
  2176. // Copy the beginning value(s) from the original aggregate.
  2177. for (; i != LinearIndex; ++i)
  2178. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2179. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2180. // Copy values from the inserted value(s).
  2181. for (; i != LinearIndex + NumValValues; ++i)
  2182. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2183. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  2184. // Copy remaining value(s) from the original aggregate.
  2185. for (; i != NumAggValues; ++i)
  2186. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2187. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2188. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
  2189. DAG.getVTList(&AggValueVTs[0], NumAggValues),
  2190. &Values[0], NumAggValues));
  2191. }
  2192. void SelectionDAGBuilder::visitExtractValue(ExtractValueInst &I) {
  2193. const Value *Op0 = I.getOperand(0);
  2194. const Type *AggTy = Op0->getType();
  2195. const Type *ValTy = I.getType();
  2196. bool OutOfUndef = isa<UndefValue>(Op0);
  2197. unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
  2198. I.idx_begin(), I.idx_end());
  2199. SmallVector<EVT, 4> ValValueVTs;
  2200. ComputeValueVTs(TLI, ValTy, ValValueVTs);
  2201. unsigned NumValValues = ValValueVTs.size();
  2202. SmallVector<SDValue, 4> Values(NumValValues);
  2203. SDValue Agg = getValue(Op0);
  2204. // Copy out the selected value(s).
  2205. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  2206. Values[i - LinearIndex] =
  2207. OutOfUndef ?
  2208. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  2209. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2210. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
  2211. DAG.getVTList(&ValValueVTs[0], NumValValues),
  2212. &Values[0], NumValValues));
  2213. }
  2214. void SelectionDAGBuilder::visitGetElementPtr(User &I) {
  2215. SDValue N = getValue(I.getOperand(0));
  2216. const Type *Ty = I.getOperand(0)->getType();
  2217. for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
  2218. OI != E; ++OI) {
  2219. Value *Idx = *OI;
  2220. if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
  2221. unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
  2222. if (Field) {
  2223. // N = N + Offset
  2224. uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
  2225. N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
  2226. DAG.getIntPtrConstant(Offset));
  2227. }
  2228. Ty = StTy->getElementType(Field);
  2229. } else if (const UnionType *UnTy = dyn_cast<UnionType>(Ty)) {
  2230. unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
  2231. // Offset canonically 0 for unions, but type changes
  2232. Ty = UnTy->getElementType(Field);
  2233. } else {
  2234. Ty = cast<SequentialType>(Ty)->getElementType();
  2235. // If this is a constant subscript, handle it quickly.
  2236. if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
  2237. if (CI->getZExtValue() == 0) continue;
  2238. uint64_t Offs =
  2239. TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
  2240. SDValue OffsVal;
  2241. EVT PTy = TLI.getPointerTy();
  2242. unsigned PtrBits = PTy.getSizeInBits();
  2243. if (PtrBits < 64)
  2244. OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
  2245. TLI.getPointerTy(),
  2246. DAG.getConstant(Offs, MVT::i64));
  2247. else
  2248. OffsVal = DAG.getIntPtrConstant(Offs);
  2249. N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
  2250. OffsVal);
  2251. continue;
  2252. }
  2253. // N = N + Idx * ElementSize;
  2254. APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
  2255. TD->getTypeAllocSize(Ty));
  2256. SDValue IdxN = getValue(Idx);
  2257. // If the index is smaller or larger than intptr_t, truncate or extend
  2258. // it.
  2259. IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
  2260. // If this is a multiply by a power of two, turn it into a shl
  2261. // immediately. This is a very common case.
  2262. if (ElementSize != 1) {
  2263. if (ElementSize.isPowerOf2()) {
  2264. unsigned Amt = ElementSize.logBase2();
  2265. IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
  2266. N.getValueType(), IdxN,
  2267. DAG.getConstant(Amt, TLI.getPointerTy()));
  2268. } else {
  2269. SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
  2270. IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
  2271. N.getValueType(), IdxN, Scale);
  2272. }
  2273. }
  2274. N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
  2275. N.getValueType(), N, IdxN);
  2276. }
  2277. }
  2278. setValue(&I, N);
  2279. }
  2280. void SelectionDAGBuilder::visitAlloca(AllocaInst &I) {
  2281. // If this is a fixed sized alloca in the entry block of the function,
  2282. // allocate it statically on the stack.
  2283. if (FuncInfo.StaticAllocaMap.count(&I))
  2284. return; // getValue will auto-populate this.
  2285. const Type *Ty = I.getAllocatedType();
  2286. uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
  2287. unsigned Align =
  2288. std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
  2289. I.getAlignment());
  2290. SDValue AllocSize = getValue(I.getArraySize());
  2291. AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
  2292. AllocSize,
  2293. DAG.getConstant(TySize, AllocSize.getValueType()));
  2294. EVT IntPtr = TLI.getPointerTy();
  2295. AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
  2296. // Handle alignment. If the requested alignment is less than or equal to
  2297. // the stack alignment, ignore it. If the size is greater than or equal to
  2298. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  2299. unsigned StackAlign =
  2300. TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
  2301. if (Align <= StackAlign)
  2302. Align = 0;
  2303. // Round the size of the allocation up to the stack alignment size
  2304. // by add SA-1 to the size.
  2305. AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
  2306. AllocSize.getValueType(), AllocSize,
  2307. DAG.getIntPtrConstant(StackAlign-1));
  2308. // Mask out the low bits for alignment purposes.
  2309. AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
  2310. AllocSize.getValueType(), AllocSize,
  2311. DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
  2312. SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
  2313. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  2314. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
  2315. VTs, Ops, 3);
  2316. setValue(&I, DSA);
  2317. DAG.setRoot(DSA.getValue(1));
  2318. // Inform the Frame Information that we have just allocated a variable-sized
  2319. // object.
  2320. FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
  2321. }
  2322. void SelectionDAGBuilder::visitLoad(LoadInst &I) {
  2323. const Value *SV = I.getOperand(0);
  2324. SDValue Ptr = getValue(SV);
  2325. const Type *Ty = I.getType();
  2326. bool isVolatile = I.isVolatile();
  2327. bool isNonTemporal = I.getMetadata("nontemporal") != 0;
  2328. unsigned Alignment = I.getAlignment();
  2329. SmallVector<EVT, 4> ValueVTs;
  2330. SmallVector<uint64_t, 4> Offsets;
  2331. ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
  2332. unsigned NumValues = ValueVTs.size();
  2333. if (NumValues == 0)
  2334. return;
  2335. SDValue Root;
  2336. bool ConstantMemory = false;
  2337. if (I.isVolatile())
  2338. // Serialize volatile loads with other side effects.
  2339. Root = getRoot();
  2340. else if (AA->pointsToConstantMemory(SV)) {
  2341. // Do not serialize (non-volatile) loads of constant memory with anything.
  2342. Root = DAG.getEntryNode();
  2343. ConstantMemory = true;
  2344. } else {
  2345. // Do not serialize non-volatile loads against each other.
  2346. Root = DAG.getRoot();
  2347. }
  2348. SmallVector<SDValue, 4> Values(NumValues);
  2349. SmallVector<SDValue, 4> Chains(NumValues);
  2350. EVT PtrVT = Ptr.getValueType();
  2351. for (unsigned i = 0; i != NumValues; ++i) {
  2352. SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
  2353. PtrVT, Ptr,
  2354. DAG.getConstant(Offsets[i], PtrVT));
  2355. SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
  2356. A, SV, Offsets[i], isVolatile,
  2357. isNonTemporal, Alignment);
  2358. Values[i] = L;
  2359. Chains[i] = L.getValue(1);
  2360. }
  2361. if (!ConstantMemory) {
  2362. SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
  2363. MVT::Other, &Chains[0], NumValues);
  2364. if (isVolatile)
  2365. DAG.setRoot(Chain);
  2366. else
  2367. PendingLoads.push_back(Chain);
  2368. }
  2369. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
  2370. DAG.getVTList(&ValueVTs[0], NumValues),
  2371. &Values[0], NumValues));
  2372. }
  2373. void SelectionDAGBuilder::visitStore(StoreInst &I) {
  2374. Value *SrcV = I.getOperand(0);
  2375. Value *PtrV = I.getOperand(1);
  2376. SmallVector<EVT, 4> ValueVTs;
  2377. SmallVector<uint64_t, 4> Offsets;
  2378. ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
  2379. unsigned NumValues = ValueVTs.size();
  2380. if (NumValues == 0)
  2381. return;
  2382. // Get the lowered operands. Note that we do this after
  2383. // checking if NumResults is zero, because with zero results
  2384. // the operands won't have values in the map.
  2385. SDValue Src = getValue(SrcV);
  2386. SDValue Ptr = getValue(PtrV);
  2387. SDValue Root = getRoot();
  2388. SmallVector<SDValue, 4> Chains(NumValues);
  2389. EVT PtrVT = Ptr.getValueType();
  2390. bool isVolatile = I.isVolatile();
  2391. bool isNonTemporal = I.getMetadata("nontemporal") != 0;
  2392. unsigned Alignment = I.getAlignment();
  2393. for (unsigned i = 0; i != NumValues; ++i) {
  2394. SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
  2395. DAG.getConstant(Offsets[i], PtrVT));
  2396. Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
  2397. SDValue(Src.getNode(), Src.getResNo() + i),
  2398. Add, PtrV, Offsets[i], isVolatile,
  2399. isNonTemporal, Alignment);
  2400. }
  2401. DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
  2402. MVT::Other, &Chains[0], NumValues));
  2403. }
  2404. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  2405. /// node.
  2406. void SelectionDAGBuilder::visitTargetIntrinsic(CallInst &I,
  2407. unsigned Intrinsic) {
  2408. bool HasChain = !I.doesNotAccessMemory();
  2409. bool OnlyLoad = HasChain && I.onlyReadsMemory();
  2410. // Build the operand list.
  2411. SmallVector<SDValue, 8> Ops;
  2412. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  2413. if (OnlyLoad) {
  2414. // We don't need to serialize loads against other loads.
  2415. Ops.push_back(DAG.getRoot());
  2416. } else {
  2417. Ops.push_back(getRoot());
  2418. }
  2419. }
  2420. // Info is set by getTgtMemInstrinsic
  2421. TargetLowering::IntrinsicInfo Info;
  2422. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
  2423. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  2424. if (!IsTgtIntrinsic)
  2425. Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
  2426. // Add all operands of the call to the operand list.
  2427. for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
  2428. SDValue Op = getValue(I.getOperand(i));
  2429. assert(TLI.isTypeLegal(Op.getValueType()) &&
  2430. "Intrinsic uses a non-legal type?");
  2431. Ops.push_back(Op);
  2432. }
  2433. SmallVector<EVT, 4> ValueVTs;
  2434. ComputeValueVTs(TLI, I.getType(), ValueVTs);
  2435. #ifndef NDEBUG
  2436. for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
  2437. assert(TLI.isTypeLegal(ValueVTs[Val]) &&
  2438. "Intrinsic uses a non-legal type?");
  2439. }
  2440. #endif // NDEBUG
  2441. if (HasChain)
  2442. ValueVTs.push_back(MVT::Other);
  2443. SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
  2444. // Create the node.
  2445. SDValue Result;
  2446. if (IsTgtIntrinsic) {
  2447. // This is target intrinsic that touches memory
  2448. Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
  2449. VTs, &Ops[0], Ops.size(),
  2450. Info.memVT, Info.ptrVal, Info.offset,
  2451. Info.align, Info.vol,
  2452. Info.readMem, Info.writeMem);
  2453. } else if (!HasChain) {
  2454. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
  2455. VTs, &Ops[0], Ops.size());
  2456. } else if (!I.getType()->isVoidTy()) {
  2457. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
  2458. VTs, &Ops[0], Ops.size());
  2459. } else {
  2460. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
  2461. VTs, &Ops[0], Ops.size());
  2462. }
  2463. if (HasChain) {
  2464. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  2465. if (OnlyLoad)
  2466. PendingLoads.push_back(Chain);
  2467. else
  2468. DAG.setRoot(Chain);
  2469. }
  2470. if (!I.getType()->isVoidTy()) {
  2471. if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  2472. EVT VT = TLI.getValueType(PTy);
  2473. Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
  2474. }
  2475. setValue(&I, Result);
  2476. }
  2477. }
  2478. /// GetSignificand - Get the significand and build it into a floating-point
  2479. /// number with exponent of 1:
  2480. ///
  2481. /// Op = (Op & 0x007fffff) | 0x3f800000;
  2482. ///
  2483. /// where Op is the hexidecimal representation of floating point value.
  2484. static SDValue
  2485. GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
  2486. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  2487. DAG.getConstant(0x007fffff, MVT::i32));
  2488. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  2489. DAG.getConstant(0x3f800000, MVT::i32));
  2490. return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
  2491. }
  2492. /// GetExponent - Get the exponent:
  2493. ///
  2494. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  2495. ///
  2496. /// where Op is the hexidecimal representation of floating point value.
  2497. static SDValue
  2498. GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
  2499. DebugLoc dl) {
  2500. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  2501. DAG.getConstant(0x7f800000, MVT::i32));
  2502. SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
  2503. DAG.getConstant(23, TLI.getPointerTy()));
  2504. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  2505. DAG.getConstant(127, MVT::i32));
  2506. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  2507. }
  2508. /// getF32Constant - Get 32-bit floating point constant.
  2509. static SDValue
  2510. getF32Constant(SelectionDAG &DAG, unsigned Flt) {
  2511. return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
  2512. }
  2513. /// Inlined utility function to implement binary input atomic intrinsics for
  2514. /// visitIntrinsicCall: I is a call instruction
  2515. /// Op is the associated NodeType for I
  2516. const char *
  2517. SelectionDAGBuilder::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
  2518. SDValue Root = getRoot();
  2519. SDValue L =
  2520. DAG.getAtomic(Op, getCurDebugLoc(),
  2521. getValue(I.getOperand(2)).getValueType().getSimpleVT(),
  2522. Root,
  2523. getValue(I.getOperand(1)),
  2524. getValue(I.getOperand(2)),
  2525. I.getOperand(1));
  2526. setValue(&I, L);
  2527. DAG.setRoot(L.getValue(1));
  2528. return 0;
  2529. }
  2530. // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
  2531. const char *
  2532. SelectionDAGBuilder::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
  2533. SDValue Op1 = getValue(I.getOperand(1));
  2534. SDValue Op2 = getValue(I.getOperand(2));
  2535. SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
  2536. setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
  2537. return 0;
  2538. }
  2539. /// visitExp - Lower an exp intrinsic. Handles the special sequences for
  2540. /// limited-precision mode.
  2541. void
  2542. SelectionDAGBuilder::visitExp(CallInst &I) {
  2543. SDValue result;
  2544. DebugLoc dl = getCurDebugLoc();
  2545. if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
  2546. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  2547. SDValue Op = getValue(I.getOperand(1));
  2548. // Put the exponent in the right bit position for later addition to the
  2549. // final result:
  2550. //
  2551. // #define LOG2OFe 1.4426950f
  2552. // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
  2553. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  2554. getF32Constant(DAG, 0x3fb8aa3b));
  2555. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  2556. // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
  2557. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  2558. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  2559. // IntegerPartOfX <<= 23;
  2560. IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  2561. DAG.getConstant(23, TLI.getPointerTy()));
  2562. if (LimitFloatPrecision <= 6) {
  2563. // For floating-point precision of 6:
  2564. //
  2565. // TwoToFractionalPartOfX =
  2566. // 0.997535578f +
  2567. // (0.735607626f + 0.252464424f * x) * x;
  2568. //
  2569. // error 0.0144103317, which is 6 bits
  2570. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2571. getF32Constant(DAG, 0x3e814304));
  2572. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  2573. getF32Constant(DAG, 0x3f3c50c8));
  2574. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2575. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2576. getF32Constant(DAG, 0x3f7f5e7e));
  2577. SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
  2578. // Add the exponent into the result in integer domain.
  2579. SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
  2580. TwoToFracPartOfX, IntegerPartOfX);
  2581. result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
  2582. } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
  2583. // For floating-point precision of 12:
  2584. //
  2585. // TwoToFractionalPartOfX =
  2586. // 0.999892986f +
  2587. // (0.696457318f +
  2588. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  2589. //
  2590. // 0.000107046256 error, which is 13 to 14 bits
  2591. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2592. getF32Constant(DAG, 0x3da235e3));
  2593. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  2594. getF32Constant(DAG, 0x3e65b8f3));
  2595. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2596. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2597. getF32Constant(DAG, 0x3f324b07));
  2598. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  2599. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  2600. getF32Constant(DAG, 0x3f7ff8fd));
  2601. SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
  2602. // Add the exponent into the result in integer domain.
  2603. SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
  2604. TwoToFracPartOfX, IntegerPartOfX);
  2605. result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
  2606. } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
  2607. // For floating-point precision of 18:
  2608. //
  2609. // TwoToFractionalPartOfX =
  2610. // 0.999999982f +
  2611. // (0.693148872f +
  2612. // (0.240227044f +
  2613. // (0.554906021e-1f +
  2614. // (0.961591928e-2f +
  2615. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  2616. //
  2617. // error 2.47208000*10^(-7), which is better than 18 bits
  2618. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2619. getF32Constant(DAG, 0x3924b03e));
  2620. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  2621. getF32Constant(DAG, 0x3ab24b87));
  2622. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2623. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2624. getF32Constant(DAG, 0x3c1d8c17));
  2625. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  2626. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  2627. getF32Constant(DAG, 0x3d634a1d));
  2628. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  2629. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  2630. getF32Constant(DAG, 0x3e75fe14));
  2631. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  2632. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  2633. getF32Constant(DAG, 0x3f317234));
  2634. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  2635. SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  2636. getF32Constant(DAG, 0x3f800000));
  2637. SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
  2638. MVT::i32, t13);
  2639. // Add the exponent into the result in integer domain.
  2640. SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
  2641. TwoToFracPartOfX, IntegerPartOfX);
  2642. result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
  2643. }
  2644. } else {
  2645. // No special expansion.
  2646. result = DAG.getNode(ISD::FEXP, dl,
  2647. getValue(I.getOperand(1)).getValueType(),
  2648. getValue(I.getOperand(1)));
  2649. }
  2650. setValue(&I, result);
  2651. }
  2652. /// visitLog - Lower a log intrinsic. Handles the special sequences for
  2653. /// limited-precision mode.
  2654. void
  2655. SelectionDAGBuilder::visitLog(CallInst &I) {
  2656. SDValue result;
  2657. DebugLoc dl = getCurDebugLoc();
  2658. if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
  2659. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  2660. SDValue Op = getValue(I.getOperand(1));
  2661. SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
  2662. // Scale the exponent by log(2) [0.69314718f].
  2663. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  2664. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  2665. getF32Constant(DAG, 0x3f317218));
  2666. // Get the significand and build it into a floating-point number with
  2667. // exponent of 1.
  2668. SDValue X = GetSignificand(DAG, Op1, dl);
  2669. if (LimitFloatPrecision <= 6) {
  2670. // For floating-point precision of 6:
  2671. //
  2672. // LogofMantissa =
  2673. // -1.1609546f +
  2674. // (1.4034025f - 0.23903021f * x) * x;
  2675. //
  2676. // error 0.0034276066, which is better than 8 bits
  2677. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2678. getF32Constant(DAG, 0xbe74c456));
  2679. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  2680. getF32Constant(DAG, 0x3fb3a2b1));
  2681. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  2682. SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  2683. getF32Constant(DAG, 0x3f949a29));
  2684. result = DAG.getNode(ISD::FADD, dl,
  2685. MVT::f32, LogOfExponent, LogOfMantissa);
  2686. } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
  2687. // For floating-point precision of 12:
  2688. //
  2689. // LogOfMantissa =
  2690. // -1.7417939f +
  2691. // (2.8212026f +
  2692. // (-1.4699568f +
  2693. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  2694. //
  2695. // error 0.000061011436, which is 14 bits
  2696. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2697. getF32Constant(DAG, 0xbd67b6d6));
  2698. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  2699. getF32Constant(DAG, 0x3ee4f4b8));
  2700. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  2701. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  2702. getF32Constant(DAG, 0x3fbc278b));
  2703. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2704. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2705. getF32Constant(DAG, 0x40348e95));
  2706. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  2707. SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  2708. getF32Constant(DAG, 0x3fdef31a));
  2709. result = DAG.getNode(ISD::FADD, dl,
  2710. MVT::f32, LogOfExponent, LogOfMantissa);
  2711. } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
  2712. // For floating-point precision of 18:
  2713. //
  2714. // LogOfMantissa =
  2715. // -2.1072184f +
  2716. // (4.2372794f +
  2717. // (-3.7029485f +
  2718. // (2.2781945f +
  2719. // (-0.87823314f +
  2720. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  2721. //
  2722. // error 0.0000023660568, which is better than 18 bits
  2723. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2724. getF32Constant(DAG, 0xbc91e5ac));
  2725. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  2726. getF32Constant(DAG, 0x3e4350aa));
  2727. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  2728. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  2729. getF32Constant(DAG, 0x3f60d3e3));
  2730. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2731. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2732. getF32Constant(DAG, 0x4011cdf0));
  2733. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  2734. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  2735. getF32Constant(DAG, 0x406cfd1c));
  2736. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  2737. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  2738. getF32Constant(DAG, 0x408797cb));
  2739. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  2740. SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  2741. getF32Constant(DAG, 0x4006dcab));
  2742. result = DAG.getNode(ISD::FADD, dl,
  2743. MVT::f32, LogOfExponent, LogOfMantissa);
  2744. }
  2745. } else {
  2746. // No special expansion.
  2747. result = DAG.getNode(ISD::FLOG, dl,
  2748. getValue(I.getOperand(1)).getValueType(),
  2749. getValue(I.getOperand(1)));
  2750. }
  2751. setValue(&I, result);
  2752. }
  2753. /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
  2754. /// limited-precision mode.
  2755. void
  2756. SelectionDAGBuilder::visitLog2(CallInst &I) {
  2757. SDValue result;
  2758. DebugLoc dl = getCurDebugLoc();
  2759. if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
  2760. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  2761. SDValue Op = getValue(I.getOperand(1));
  2762. SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
  2763. // Get the exponent.
  2764. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  2765. // Get the significand and build it into a floating-point number with
  2766. // exponent of 1.
  2767. SDValue X = GetSignificand(DAG, Op1, dl);
  2768. // Different possible minimax approximations of significand in
  2769. // floating-point for various degrees of accuracy over [1,2].
  2770. if (LimitFloatPrecision <= 6) {
  2771. // For floating-point precision of 6:
  2772. //
  2773. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  2774. //
  2775. // error 0.0049451742, which is more than 7 bits
  2776. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2777. getF32Constant(DAG, 0xbeb08fe0));
  2778. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  2779. getF32Constant(DAG, 0x40019463));
  2780. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  2781. SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  2782. getF32Constant(DAG, 0x3fd6633d));
  2783. result = DAG.getNode(ISD::FADD, dl,
  2784. MVT::f32, LogOfExponent, Log2ofMantissa);
  2785. } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
  2786. // For floating-point precision of 12:
  2787. //
  2788. // Log2ofMantissa =
  2789. // -2.51285454f +
  2790. // (4.07009056f +
  2791. // (-2.12067489f +
  2792. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  2793. //
  2794. // error 0.0000876136000, which is better than 13 bits
  2795. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2796. getF32Constant(DAG, 0xbda7262e));
  2797. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  2798. getF32Constant(DAG, 0x3f25280b));
  2799. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  2800. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  2801. getF32Constant(DAG, 0x4007b923));
  2802. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2803. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2804. getF32Constant(DAG, 0x40823e2f));
  2805. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  2806. SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  2807. getF32Constant(DAG, 0x4020d29c));
  2808. result = DAG.getNode(ISD::FADD, dl,
  2809. MVT::f32, LogOfExponent, Log2ofMantissa);
  2810. } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
  2811. // For floating-point precision of 18:
  2812. //
  2813. // Log2ofMantissa =
  2814. // -3.0400495f +
  2815. // (6.1129976f +
  2816. // (-5.3420409f +
  2817. // (3.2865683f +
  2818. // (-1.2669343f +
  2819. // (0.27515199f -
  2820. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  2821. //
  2822. // error 0.0000018516, which is better than 18 bits
  2823. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2824. getF32Constant(DAG, 0xbcd2769e));
  2825. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  2826. getF32Constant(DAG, 0x3e8ce0b9));
  2827. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  2828. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  2829. getF32Constant(DAG, 0x3fa22ae7));
  2830. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2831. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2832. getF32Constant(DAG, 0x40525723));
  2833. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  2834. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  2835. getF32Constant(DAG, 0x40aaf200));
  2836. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  2837. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  2838. getF32Constant(DAG, 0x40c39dad));
  2839. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  2840. SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  2841. getF32Constant(DAG, 0x4042902c));
  2842. result = DAG.getNode(ISD::FADD, dl,
  2843. MVT::f32, LogOfExponent, Log2ofMantissa);
  2844. }
  2845. } else {
  2846. // No special expansion.
  2847. result = DAG.getNode(ISD::FLOG2, dl,
  2848. getValue(I.getOperand(1)).getValueType(),
  2849. getValue(I.getOperand(1)));
  2850. }
  2851. setValue(&I, result);
  2852. }
  2853. /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
  2854. /// limited-precision mode.
  2855. void
  2856. SelectionDAGBuilder::visitLog10(CallInst &I) {
  2857. SDValue result;
  2858. DebugLoc dl = getCurDebugLoc();
  2859. if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
  2860. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  2861. SDValue Op = getValue(I.getOperand(1));
  2862. SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
  2863. // Scale the exponent by log10(2) [0.30102999f].
  2864. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  2865. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  2866. getF32Constant(DAG, 0x3e9a209a));
  2867. // Get the significand and build it into a floating-point number with
  2868. // exponent of 1.
  2869. SDValue X = GetSignificand(DAG, Op1, dl);
  2870. if (LimitFloatPrecision <= 6) {
  2871. // For floating-point precision of 6:
  2872. //
  2873. // Log10ofMantissa =
  2874. // -0.50419619f +
  2875. // (0.60948995f - 0.10380950f * x) * x;
  2876. //
  2877. // error 0.0014886165, which is 6 bits
  2878. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2879. getF32Constant(DAG, 0xbdd49a13));
  2880. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  2881. getF32Constant(DAG, 0x3f1c0789));
  2882. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  2883. SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  2884. getF32Constant(DAG, 0x3f011300));
  2885. result = DAG.getNode(ISD::FADD, dl,
  2886. MVT::f32, LogOfExponent, Log10ofMantissa);
  2887. } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
  2888. // For floating-point precision of 12:
  2889. //
  2890. // Log10ofMantissa =
  2891. // -0.64831180f +
  2892. // (0.91751397f +
  2893. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  2894. //
  2895. // error 0.00019228036, which is better than 12 bits
  2896. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2897. getF32Constant(DAG, 0x3d431f31));
  2898. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  2899. getF32Constant(DAG, 0x3ea21fb2));
  2900. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  2901. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  2902. getF32Constant(DAG, 0x3f6ae232));
  2903. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2904. SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  2905. getF32Constant(DAG, 0x3f25f7c3));
  2906. result = DAG.getNode(ISD::FADD, dl,
  2907. MVT::f32, LogOfExponent, Log10ofMantissa);
  2908. } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
  2909. // For floating-point precision of 18:
  2910. //
  2911. // Log10ofMantissa =
  2912. // -0.84299375f +
  2913. // (1.5327582f +
  2914. // (-1.0688956f +
  2915. // (0.49102474f +
  2916. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  2917. //
  2918. // error 0.0000037995730, which is better than 18 bits
  2919. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2920. getF32Constant(DAG, 0x3c5d51ce));
  2921. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  2922. getF32Constant(DAG, 0x3e00685a));
  2923. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  2924. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  2925. getF32Constant(DAG, 0x3efb6798));
  2926. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2927. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  2928. getF32Constant(DAG, 0x3f88d192));
  2929. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  2930. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  2931. getF32Constant(DAG, 0x3fc4316c));
  2932. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  2933. SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  2934. getF32Constant(DAG, 0x3f57ce70));
  2935. result = DAG.getNode(ISD::FADD, dl,
  2936. MVT::f32, LogOfExponent, Log10ofMantissa);
  2937. }
  2938. } else {
  2939. // No special expansion.
  2940. result = DAG.getNode(ISD::FLOG10, dl,
  2941. getValue(I.getOperand(1)).getValueType(),
  2942. getValue(I.getOperand(1)));
  2943. }
  2944. setValue(&I, result);
  2945. }
  2946. /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  2947. /// limited-precision mode.
  2948. void
  2949. SelectionDAGBuilder::visitExp2(CallInst &I) {
  2950. SDValue result;
  2951. DebugLoc dl = getCurDebugLoc();
  2952. if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
  2953. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  2954. SDValue Op = getValue(I.getOperand(1));
  2955. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
  2956. // FractionalPartOfX = x - (float)IntegerPartOfX;
  2957. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  2958. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
  2959. // IntegerPartOfX <<= 23;
  2960. IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  2961. DAG.getConstant(23, TLI.getPointerTy()));
  2962. if (LimitFloatPrecision <= 6) {
  2963. // For floating-point precision of 6:
  2964. //
  2965. // TwoToFractionalPartOfX =
  2966. // 0.997535578f +
  2967. // (0.735607626f + 0.252464424f * x) * x;
  2968. //
  2969. // error 0.0144103317, which is 6 bits
  2970. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2971. getF32Constant(DAG, 0x3e814304));
  2972. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  2973. getF32Constant(DAG, 0x3f3c50c8));
  2974. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2975. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2976. getF32Constant(DAG, 0x3f7f5e7e));
  2977. SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
  2978. SDValue TwoToFractionalPartOfX =
  2979. DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
  2980. result = DAG.getNode(ISD::BIT_CONVERT, dl,
  2981. MVT::f32, TwoToFractionalPartOfX);
  2982. } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
  2983. // For floating-point precision of 12:
  2984. //
  2985. // TwoToFractionalPartOfX =
  2986. // 0.999892986f +
  2987. // (0.696457318f +
  2988. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  2989. //
  2990. // error 0.000107046256, which is 13 to 14 bits
  2991. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2992. getF32Constant(DAG, 0x3da235e3));
  2993. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  2994. getF32Constant(DAG, 0x3e65b8f3));
  2995. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2996. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2997. getF32Constant(DAG, 0x3f324b07));
  2998. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  2999. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3000. getF32Constant(DAG, 0x3f7ff8fd));
  3001. SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
  3002. SDValue TwoToFractionalPartOfX =
  3003. DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
  3004. result = DAG.getNode(ISD::BIT_CONVERT, dl,
  3005. MVT::f32, TwoToFractionalPartOfX);
  3006. } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
  3007. // For floating-point precision of 18:
  3008. //
  3009. // TwoToFractionalPartOfX =
  3010. // 0.999999982f +
  3011. // (0.693148872f +
  3012. // (0.240227044f +
  3013. // (0.554906021e-1f +
  3014. // (0.961591928e-2f +
  3015. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3016. // error 2.47208000*10^(-7), which is better than 18 bits
  3017. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3018. getF32Constant(DAG, 0x3924b03e));
  3019. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3020. getF32Constant(DAG, 0x3ab24b87));
  3021. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3022. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3023. getF32Constant(DAG, 0x3c1d8c17));
  3024. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3025. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3026. getF32Constant(DAG, 0x3d634a1d));
  3027. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3028. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3029. getF32Constant(DAG, 0x3e75fe14));
  3030. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3031. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3032. getF32Constant(DAG, 0x3f317234));
  3033. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3034. SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3035. getF32Constant(DAG, 0x3f800000));
  3036. SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
  3037. SDValue TwoToFractionalPartOfX =
  3038. DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
  3039. result = DAG.getNode(ISD::BIT_CONVERT, dl,
  3040. MVT::f32, TwoToFractionalPartOfX);
  3041. }
  3042. } else {
  3043. // No special expansion.
  3044. result = DAG.getNode(ISD::FEXP2, dl,
  3045. getValue(I.getOperand(1)).getValueType(),
  3046. getValue(I.getOperand(1)));
  3047. }
  3048. setValue(&I, result);
  3049. }
  3050. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  3051. /// limited-precision mode with x == 10.0f.
  3052. void
  3053. SelectionDAGBuilder::visitPow(CallInst &I) {
  3054. SDValue result;
  3055. Value *Val = I.getOperand(1);
  3056. DebugLoc dl = getCurDebugLoc();
  3057. bool IsExp10 = false;
  3058. if (getValue(Val).getValueType() == MVT::f32 &&
  3059. getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
  3060. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3061. if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
  3062. if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
  3063. APFloat Ten(10.0f);
  3064. IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
  3065. }
  3066. }
  3067. }
  3068. if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3069. SDValue Op = getValue(I.getOperand(2));
  3070. // Put the exponent in the right bit position for later addition to the
  3071. // final result:
  3072. //
  3073. // #define LOG2OF10 3.3219281f
  3074. // IntegerPartOfX = (int32_t)(x * LOG2OF10);
  3075. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  3076. getF32Constant(DAG, 0x40549a78));
  3077. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  3078. // FractionalPartOfX = x - (float)IntegerPartOfX;
  3079. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3080. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  3081. // IntegerPartOfX <<= 23;
  3082. IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3083. DAG.getConstant(23, TLI.getPointerTy()));
  3084. if (LimitFloatPrecision <= 6) {
  3085. // For floating-point precision of 6:
  3086. //
  3087. // twoToFractionalPartOfX =
  3088. // 0.997535578f +
  3089. // (0.735607626f + 0.252464424f * x) * x;
  3090. //
  3091. // error 0.0144103317, which is 6 bits
  3092. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3093. getF32Constant(DAG, 0x3e814304));
  3094. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3095. getF32Constant(DAG, 0x3f3c50c8));
  3096. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3097. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3098. getF32Constant(DAG, 0x3f7f5e7e));
  3099. SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
  3100. SDValue TwoToFractionalPartOfX =
  3101. DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
  3102. result = DAG.getNode(ISD::BIT_CONVERT, dl,
  3103. MVT::f32, TwoToFractionalPartOfX);
  3104. } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
  3105. // For floating-point precision of 12:
  3106. //
  3107. // TwoToFractionalPartOfX =
  3108. // 0.999892986f +
  3109. // (0.696457318f +
  3110. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3111. //
  3112. // error 0.000107046256, which is 13 to 14 bits
  3113. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3114. getF32Constant(DAG, 0x3da235e3));
  3115. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3116. getF32Constant(DAG, 0x3e65b8f3));
  3117. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3118. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3119. getF32Constant(DAG, 0x3f324b07));
  3120. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3121. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3122. getF32Constant(DAG, 0x3f7ff8fd));
  3123. SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
  3124. SDValue TwoToFractionalPartOfX =
  3125. DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
  3126. result = DAG.getNode(ISD::BIT_CONVERT, dl,
  3127. MVT::f32, TwoToFractionalPartOfX);
  3128. } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
  3129. // For floating-point precision of 18:
  3130. //
  3131. // TwoToFractionalPartOfX =
  3132. // 0.999999982f +
  3133. // (0.693148872f +
  3134. // (0.240227044f +
  3135. // (0.554906021e-1f +
  3136. // (0.961591928e-2f +
  3137. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3138. // error 2.47208000*10^(-7), which is better than 18 bits
  3139. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3140. getF32Constant(DAG, 0x3924b03e));
  3141. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3142. getF32Constant(DAG, 0x3ab24b87));
  3143. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3144. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3145. getF32Constant(DAG, 0x3c1d8c17));
  3146. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3147. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3148. getF32Constant(DAG, 0x3d634a1d));
  3149. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3150. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3151. getF32Constant(DAG, 0x3e75fe14));
  3152. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3153. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3154. getF32Constant(DAG, 0x3f317234));
  3155. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3156. SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3157. getF32Constant(DAG, 0x3f800000));
  3158. SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
  3159. SDValue TwoToFractionalPartOfX =
  3160. DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
  3161. result = DAG.getNode(ISD::BIT_CONVERT, dl,
  3162. MVT::f32, TwoToFractionalPartOfX);
  3163. }
  3164. } else {
  3165. // No special expansion.
  3166. result = DAG.getNode(ISD::FPOW, dl,
  3167. getValue(I.getOperand(1)).getValueType(),
  3168. getValue(I.getOperand(1)),
  3169. getValue(I.getOperand(2)));
  3170. }
  3171. setValue(&I, result);
  3172. }
  3173. /// ExpandPowI - Expand a llvm.powi intrinsic.
  3174. static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
  3175. SelectionDAG &DAG) {
  3176. // If RHS is a constant, we can expand this out to a multiplication tree,
  3177. // otherwise we end up lowering to a call to __powidf2 (for example). When
  3178. // optimizing for size, we only want to do this if the expansion would produce
  3179. // a small number of multiplies, otherwise we do the full expansion.
  3180. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  3181. // Get the exponent as a positive value.
  3182. unsigned Val = RHSC->getSExtValue();
  3183. if ((int)Val < 0) Val = -Val;
  3184. // powi(x, 0) -> 1.0
  3185. if (Val == 0)
  3186. return DAG.getConstantFP(1.0, LHS.getValueType());
  3187. Function *F = DAG.getMachineFunction().getFunction();
  3188. if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
  3189. // If optimizing for size, don't insert too many multiplies. This
  3190. // inserts up to 5 multiplies.
  3191. CountPopulation_32(Val)+Log2_32(Val) < 7) {
  3192. // We use the simple binary decomposition method to generate the multiply
  3193. // sequence. There are more optimal ways to do this (for example,
  3194. // powi(x,15) generates one more multiply than it should), but this has
  3195. // the benefit of being both really simple and much better than a libcall.
  3196. SDValue Res; // Logically starts equal to 1.0
  3197. SDValue CurSquare = LHS;
  3198. while (Val) {
  3199. if (Val & 1) {
  3200. if (Res.getNode())
  3201. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  3202. else
  3203. Res = CurSquare; // 1.0*CurSquare.
  3204. }
  3205. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  3206. CurSquare, CurSquare);
  3207. Val >>= 1;
  3208. }
  3209. // If the original was negative, invert the result, producing 1/(x*x*x).
  3210. if (RHSC->getSExtValue() < 0)
  3211. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  3212. DAG.getConstantFP(1.0, LHS.getValueType()), Res);
  3213. return Res;
  3214. }
  3215. }
  3216. // Otherwise, expand to a libcall.
  3217. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  3218. }
  3219. /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
  3220. /// we want to emit this as a call to a named external function, return the name
  3221. /// otherwise lower it and return null.
  3222. const char *
  3223. SelectionDAGBuilder::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
  3224. DebugLoc dl = getCurDebugLoc();
  3225. SDValue Res;
  3226. switch (Intrinsic) {
  3227. default:
  3228. // By default, turn this into a target intrinsic node.
  3229. visitTargetIntrinsic(I, Intrinsic);
  3230. return 0;
  3231. case Intrinsic::vastart: visitVAStart(I); return 0;
  3232. case Intrinsic::vaend: visitVAEnd(I); return 0;
  3233. case Intrinsic::vacopy: visitVACopy(I); return 0;
  3234. case Intrinsic::returnaddress:
  3235. setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
  3236. getValue(I.getOperand(1))));
  3237. return 0;
  3238. case Intrinsic::frameaddress:
  3239. setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
  3240. getValue(I.getOperand(1))));
  3241. return 0;
  3242. case Intrinsic::setjmp:
  3243. return "_setjmp"+!TLI.usesUnderscoreSetJmp();
  3244. case Intrinsic::longjmp:
  3245. return "_longjmp"+!TLI.usesUnderscoreLongJmp();
  3246. case Intrinsic::memcpy: {
  3247. SDValue Op1 = getValue(I.getOperand(1));
  3248. SDValue Op2 = getValue(I.getOperand(2));
  3249. SDValue Op3 = getValue(I.getOperand(3));
  3250. unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
  3251. DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
  3252. I.getOperand(1), 0, I.getOperand(2), 0));
  3253. return 0;
  3254. }
  3255. case Intrinsic::memset: {
  3256. SDValue Op1 = getValue(I.getOperand(1));
  3257. SDValue Op2 = getValue(I.getOperand(2));
  3258. SDValue Op3 = getValue(I.getOperand(3));
  3259. unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
  3260. DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
  3261. I.getOperand(1), 0));
  3262. return 0;
  3263. }
  3264. case Intrinsic::memmove: {
  3265. SDValue Op1 = getValue(I.getOperand(1));
  3266. SDValue Op2 = getValue(I.getOperand(2));
  3267. SDValue Op3 = getValue(I.getOperand(3));
  3268. unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
  3269. // If the source and destination are known to not be aliases, we can
  3270. // lower memmove as memcpy.
  3271. uint64_t Size = -1ULL;
  3272. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
  3273. Size = C->getZExtValue();
  3274. if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
  3275. AliasAnalysis::NoAlias) {
  3276. DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
  3277. I.getOperand(1), 0, I.getOperand(2), 0));
  3278. return 0;
  3279. }
  3280. DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
  3281. I.getOperand(1), 0, I.getOperand(2), 0));
  3282. return 0;
  3283. }
  3284. case Intrinsic::dbg_declare: {
  3285. // FIXME: currently, we get here only if OptLevel != CodeGenOpt::None.
  3286. // The real handling of this intrinsic is in FastISel.
  3287. if (OptLevel != CodeGenOpt::None)
  3288. // FIXME: Variable debug info is not supported here.
  3289. return 0;
  3290. DwarfWriter *DW = DAG.getDwarfWriter();
  3291. if (!DW)
  3292. return 0;
  3293. DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
  3294. if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
  3295. return 0;
  3296. MDNode *Variable = DI.getVariable();
  3297. Value *Address = DI.getAddress();
  3298. if (!Address)
  3299. return 0;
  3300. if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  3301. Address = BCI->getOperand(0);
  3302. AllocaInst *AI = dyn_cast<AllocaInst>(Address);
  3303. // Don't handle byval struct arguments or VLAs, for example.
  3304. if (!AI)
  3305. return 0;
  3306. DenseMap<const AllocaInst*, int>::iterator SI =
  3307. FuncInfo.StaticAllocaMap.find(AI);
  3308. if (SI == FuncInfo.StaticAllocaMap.end())
  3309. return 0; // VLAs.
  3310. int FI = SI->second;
  3311. if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo())
  3312. if (MDNode *Dbg = DI.getMetadata("dbg"))
  3313. MMI->setVariableDbgInfo(Variable, FI, Dbg);
  3314. return 0;
  3315. }
  3316. case Intrinsic::dbg_value: {
  3317. DwarfWriter *DW = DAG.getDwarfWriter();
  3318. if (!DW)
  3319. return 0;
  3320. DbgValueInst &DI = cast<DbgValueInst>(I);
  3321. if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
  3322. return 0;
  3323. MDNode *Variable = DI.getVariable();
  3324. uint64_t Offset = DI.getOffset();
  3325. Value *V = DI.getValue();
  3326. if (!V)
  3327. return 0;
  3328. // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
  3329. // but do not always have a corresponding SDNode built. The SDNodeOrder
  3330. // absolute, but not relative, values are different depending on whether
  3331. // debug info exists.
  3332. ++SDNodeOrder;
  3333. if (isa<ConstantInt>(V) || isa<ConstantFP>(V)) {
  3334. SDDbgValue* dv = new SDDbgValue(Variable, V, Offset, dl, SDNodeOrder);
  3335. DAG.RememberDbgInfo(dv);
  3336. } else {
  3337. SDValue &N = NodeMap[V];
  3338. if (N.getNode()) {
  3339. SDDbgValue *dv = new SDDbgValue(Variable, N.getNode(),
  3340. N.getResNo(), Offset, dl, SDNodeOrder);
  3341. DAG.AssignDbgInfo(N.getNode(), dv);
  3342. } else {
  3343. // We may expand this to cover more cases. One case where we have no
  3344. // data available is an unreferenced parameter; we need this fallback.
  3345. SDDbgValue* dv = new SDDbgValue(Variable,
  3346. UndefValue::get(V->getType()),
  3347. Offset, dl, SDNodeOrder);
  3348. DAG.RememberDbgInfo(dv);
  3349. }
  3350. }
  3351. // Build a debug info table entry.
  3352. if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
  3353. V = BCI->getOperand(0);
  3354. AllocaInst *AI = dyn_cast<AllocaInst>(V);
  3355. // Don't handle byval struct arguments or VLAs, for example.
  3356. if (!AI)
  3357. return 0;
  3358. DenseMap<const AllocaInst*, int>::iterator SI =
  3359. FuncInfo.StaticAllocaMap.find(AI);
  3360. if (SI == FuncInfo.StaticAllocaMap.end())
  3361. return 0; // VLAs.
  3362. int FI = SI->second;
  3363. if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo())
  3364. if (MDNode *Dbg = DI.getMetadata("dbg"))
  3365. MMI->setVariableDbgInfo(Variable, FI, Dbg);
  3366. return 0;
  3367. }
  3368. case Intrinsic::eh_exception: {
  3369. // Insert the EXCEPTIONADDR instruction.
  3370. assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
  3371. SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
  3372. SDValue Ops[1];
  3373. Ops[0] = DAG.getRoot();
  3374. SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
  3375. setValue(&I, Op);
  3376. DAG.setRoot(Op.getValue(1));
  3377. return 0;
  3378. }
  3379. case Intrinsic::eh_selector: {
  3380. MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
  3381. if (CurMBB->isLandingPad())
  3382. AddCatchInfo(I, MMI, CurMBB);
  3383. else {
  3384. #ifndef NDEBUG
  3385. FuncInfo.CatchInfoLost.insert(&I);
  3386. #endif
  3387. // FIXME: Mark exception selector register as live in. Hack for PR1508.
  3388. unsigned Reg = TLI.getExceptionSelectorRegister();
  3389. if (Reg) CurMBB->addLiveIn(Reg);
  3390. }
  3391. // Insert the EHSELECTION instruction.
  3392. SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
  3393. SDValue Ops[2];
  3394. Ops[0] = getValue(I.getOperand(1));
  3395. Ops[1] = getRoot();
  3396. SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
  3397. DAG.setRoot(Op.getValue(1));
  3398. setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
  3399. return 0;
  3400. }
  3401. case Intrinsic::eh_typeid_for: {
  3402. MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
  3403. if (MMI) {
  3404. // Find the type id for the given typeinfo.
  3405. GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
  3406. unsigned TypeID = MMI->getTypeIDFor(GV);
  3407. Res = DAG.getConstant(TypeID, MVT::i32);
  3408. } else {
  3409. // Return something different to eh_selector.
  3410. Res = DAG.getConstant(1, MVT::i32);
  3411. }
  3412. setValue(&I, Res);
  3413. return 0;
  3414. }
  3415. case Intrinsic::eh_return_i32:
  3416. case Intrinsic::eh_return_i64:
  3417. if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
  3418. MMI->setCallsEHReturn(true);
  3419. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
  3420. MVT::Other,
  3421. getControlRoot(),
  3422. getValue(I.getOperand(1)),
  3423. getValue(I.getOperand(2))));
  3424. } else {
  3425. setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
  3426. }
  3427. return 0;
  3428. case Intrinsic::eh_unwind_init:
  3429. if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
  3430. MMI->setCallsUnwindInit(true);
  3431. }
  3432. return 0;
  3433. case Intrinsic::eh_dwarf_cfa: {
  3434. EVT VT = getValue(I.getOperand(1)).getValueType();
  3435. SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
  3436. TLI.getPointerTy());
  3437. SDValue Offset = DAG.getNode(ISD::ADD, dl,
  3438. TLI.getPointerTy(),
  3439. DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
  3440. TLI.getPointerTy()),
  3441. CfaArg);
  3442. SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
  3443. TLI.getPointerTy(),
  3444. DAG.getConstant(0, TLI.getPointerTy()));
  3445. setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
  3446. FA, Offset));
  3447. return 0;
  3448. }
  3449. case Intrinsic::eh_sjlj_callsite: {
  3450. MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
  3451. ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
  3452. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  3453. assert(MMI->getCurrentCallSite() == 0 && "Overlapping call sites!");
  3454. MMI->setCurrentCallSite(CI->getZExtValue());
  3455. return 0;
  3456. }
  3457. case Intrinsic::convertff:
  3458. case Intrinsic::convertfsi:
  3459. case Intrinsic::convertfui:
  3460. case Intrinsic::convertsif:
  3461. case Intrinsic::convertuif:
  3462. case Intrinsic::convertss:
  3463. case Intrinsic::convertsu:
  3464. case Intrinsic::convertus:
  3465. case Intrinsic::convertuu: {
  3466. ISD::CvtCode Code = ISD::CVT_INVALID;
  3467. switch (Intrinsic) {
  3468. case Intrinsic::convertff: Code = ISD::CVT_FF; break;
  3469. case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
  3470. case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
  3471. case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
  3472. case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
  3473. case Intrinsic::convertss: Code = ISD::CVT_SS; break;
  3474. case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
  3475. case Intrinsic::convertus: Code = ISD::CVT_US; break;
  3476. case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
  3477. }
  3478. EVT DestVT = TLI.getValueType(I.getType());
  3479. Value *Op1 = I.getOperand(1);
  3480. Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
  3481. DAG.getValueType(DestVT),
  3482. DAG.getValueType(getValue(Op1).getValueType()),
  3483. getValue(I.getOperand(2)),
  3484. getValue(I.getOperand(3)),
  3485. Code);
  3486. setValue(&I, Res);
  3487. return 0;
  3488. }
  3489. case Intrinsic::sqrt:
  3490. setValue(&I, DAG.getNode(ISD::FSQRT, dl,
  3491. getValue(I.getOperand(1)).getValueType(),
  3492. getValue(I.getOperand(1))));
  3493. return 0;
  3494. case Intrinsic::powi:
  3495. setValue(&I, ExpandPowI(dl, getValue(I.getOperand(1)),
  3496. getValue(I.getOperand(2)), DAG));
  3497. return 0;
  3498. case Intrinsic::sin:
  3499. setValue(&I, DAG.getNode(ISD::FSIN, dl,
  3500. getValue(I.getOperand(1)).getValueType(),
  3501. getValue(I.getOperand(1))));
  3502. return 0;
  3503. case Intrinsic::cos:
  3504. setValue(&I, DAG.getNode(ISD::FCOS, dl,
  3505. getValue(I.getOperand(1)).getValueType(),
  3506. getValue(I.getOperand(1))));
  3507. return 0;
  3508. case Intrinsic::log:
  3509. visitLog(I);
  3510. return 0;
  3511. case Intrinsic::log2:
  3512. visitLog2(I);
  3513. return 0;
  3514. case Intrinsic::log10:
  3515. visitLog10(I);
  3516. return 0;
  3517. case Intrinsic::exp:
  3518. visitExp(I);
  3519. return 0;
  3520. case Intrinsic::exp2:
  3521. visitExp2(I);
  3522. return 0;
  3523. case Intrinsic::pow:
  3524. visitPow(I);
  3525. return 0;
  3526. case Intrinsic::convert_to_fp16:
  3527. setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl,
  3528. MVT::i16, getValue(I.getOperand(1))));
  3529. return 0;
  3530. case Intrinsic::convert_from_fp16:
  3531. setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl,
  3532. MVT::f32, getValue(I.getOperand(1))));
  3533. return 0;
  3534. case Intrinsic::pcmarker: {
  3535. SDValue Tmp = getValue(I.getOperand(1));
  3536. DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
  3537. return 0;
  3538. }
  3539. case Intrinsic::readcyclecounter: {
  3540. SDValue Op = getRoot();
  3541. Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
  3542. DAG.getVTList(MVT::i64, MVT::Other),
  3543. &Op, 1);
  3544. setValue(&I, Res);
  3545. DAG.setRoot(Res.getValue(1));
  3546. return 0;
  3547. }
  3548. case Intrinsic::bswap:
  3549. setValue(&I, DAG.getNode(ISD::BSWAP, dl,
  3550. getValue(I.getOperand(1)).getValueType(),
  3551. getValue(I.getOperand(1))));
  3552. return 0;
  3553. case Intrinsic::cttz: {
  3554. SDValue Arg = getValue(I.getOperand(1));
  3555. EVT Ty = Arg.getValueType();
  3556. setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
  3557. return 0;
  3558. }
  3559. case Intrinsic::ctlz: {
  3560. SDValue Arg = getValue(I.getOperand(1));
  3561. EVT Ty = Arg.getValueType();
  3562. setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
  3563. return 0;
  3564. }
  3565. case Intrinsic::ctpop: {
  3566. SDValue Arg = getValue(I.getOperand(1));
  3567. EVT Ty = Arg.getValueType();
  3568. setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
  3569. return 0;
  3570. }
  3571. case Intrinsic::stacksave: {
  3572. SDValue Op = getRoot();
  3573. Res = DAG.getNode(ISD::STACKSAVE, dl,
  3574. DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
  3575. setValue(&I, Res);
  3576. DAG.setRoot(Res.getValue(1));
  3577. return 0;
  3578. }
  3579. case Intrinsic::stackrestore: {
  3580. Res = getValue(I.getOperand(1));
  3581. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
  3582. return 0;
  3583. }
  3584. case Intrinsic::stackprotector: {
  3585. // Emit code into the DAG to store the stack guard onto the stack.
  3586. MachineFunction &MF = DAG.getMachineFunction();
  3587. MachineFrameInfo *MFI = MF.getFrameInfo();
  3588. EVT PtrTy = TLI.getPointerTy();
  3589. SDValue Src = getValue(I.getOperand(1)); // The guard's value.
  3590. AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
  3591. int FI = FuncInfo.StaticAllocaMap[Slot];
  3592. MFI->setStackProtectorIndex(FI);
  3593. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  3594. // Store the stack protector onto the stack.
  3595. Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
  3596. PseudoSourceValue::getFixedStack(FI),
  3597. 0, true, false, 0);
  3598. setValue(&I, Res);
  3599. DAG.setRoot(Res);
  3600. return 0;
  3601. }
  3602. case Intrinsic::objectsize: {
  3603. // If we don't know by now, we're never going to know.
  3604. ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
  3605. assert(CI && "Non-constant type in __builtin_object_size?");
  3606. SDValue Arg = getValue(I.getOperand(0));
  3607. EVT Ty = Arg.getValueType();
  3608. if (CI->getZExtValue() == 0)
  3609. Res = DAG.getConstant(-1ULL, Ty);
  3610. else
  3611. Res = DAG.getConstant(0, Ty);
  3612. setValue(&I, Res);
  3613. return 0;
  3614. }
  3615. case Intrinsic::var_annotation:
  3616. // Discard annotate attributes
  3617. return 0;
  3618. case Intrinsic::init_trampoline: {
  3619. const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
  3620. SDValue Ops[6];
  3621. Ops[0] = getRoot();
  3622. Ops[1] = getValue(I.getOperand(1));
  3623. Ops[2] = getValue(I.getOperand(2));
  3624. Ops[3] = getValue(I.getOperand(3));
  3625. Ops[4] = DAG.getSrcValue(I.getOperand(1));
  3626. Ops[5] = DAG.getSrcValue(F);
  3627. Res = DAG.getNode(ISD::TRAMPOLINE, dl,
  3628. DAG.getVTList(TLI.getPointerTy(), MVT::Other),
  3629. Ops, 6);
  3630. setValue(&I, Res);
  3631. DAG.setRoot(Res.getValue(1));
  3632. return 0;
  3633. }
  3634. case Intrinsic::gcroot:
  3635. if (GFI) {
  3636. Value *Alloca = I.getOperand(1);
  3637. Constant *TypeMap = cast<Constant>(I.getOperand(2));
  3638. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  3639. GFI->addStackRoot(FI->getIndex(), TypeMap);
  3640. }
  3641. return 0;
  3642. case Intrinsic::gcread:
  3643. case Intrinsic::gcwrite:
  3644. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  3645. return 0;
  3646. case Intrinsic::flt_rounds:
  3647. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
  3648. return 0;
  3649. case Intrinsic::trap:
  3650. DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
  3651. return 0;
  3652. case Intrinsic::uadd_with_overflow:
  3653. return implVisitAluOverflow(I, ISD::UADDO);
  3654. case Intrinsic::sadd_with_overflow:
  3655. return implVisitAluOverflow(I, ISD::SADDO);
  3656. case Intrinsic::usub_with_overflow:
  3657. return implVisitAluOverflow(I, ISD::USUBO);
  3658. case Intrinsic::ssub_with_overflow:
  3659. return implVisitAluOverflow(I, ISD::SSUBO);
  3660. case Intrinsic::umul_with_overflow:
  3661. return implVisitAluOverflow(I, ISD::UMULO);
  3662. case Intrinsic::smul_with_overflow:
  3663. return implVisitAluOverflow(I, ISD::SMULO);
  3664. case Intrinsic::prefetch: {
  3665. SDValue Ops[4];
  3666. Ops[0] = getRoot();
  3667. Ops[1] = getValue(I.getOperand(1));
  3668. Ops[2] = getValue(I.getOperand(2));
  3669. Ops[3] = getValue(I.getOperand(3));
  3670. DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
  3671. return 0;
  3672. }
  3673. case Intrinsic::memory_barrier: {
  3674. SDValue Ops[6];
  3675. Ops[0] = getRoot();
  3676. for (int x = 1; x < 6; ++x)
  3677. Ops[x] = getValue(I.getOperand(x));
  3678. DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
  3679. return 0;
  3680. }
  3681. case Intrinsic::atomic_cmp_swap: {
  3682. SDValue Root = getRoot();
  3683. SDValue L =
  3684. DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
  3685. getValue(I.getOperand(2)).getValueType().getSimpleVT(),
  3686. Root,
  3687. getValue(I.getOperand(1)),
  3688. getValue(I.getOperand(2)),
  3689. getValue(I.getOperand(3)),
  3690. I.getOperand(1));
  3691. setValue(&I, L);
  3692. DAG.setRoot(L.getValue(1));
  3693. return 0;
  3694. }
  3695. case Intrinsic::atomic_load_add:
  3696. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
  3697. case Intrinsic::atomic_load_sub:
  3698. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
  3699. case Intrinsic::atomic_load_or:
  3700. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
  3701. case Intrinsic::atomic_load_xor:
  3702. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
  3703. case Intrinsic::atomic_load_and:
  3704. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
  3705. case Intrinsic::atomic_load_nand:
  3706. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
  3707. case Intrinsic::atomic_load_max:
  3708. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
  3709. case Intrinsic::atomic_load_min:
  3710. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
  3711. case Intrinsic::atomic_load_umin:
  3712. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
  3713. case Intrinsic::atomic_load_umax:
  3714. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
  3715. case Intrinsic::atomic_swap:
  3716. return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
  3717. case Intrinsic::invariant_start:
  3718. case Intrinsic::lifetime_start:
  3719. // Discard region information.
  3720. setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
  3721. return 0;
  3722. case Intrinsic::invariant_end:
  3723. case Intrinsic::lifetime_end:
  3724. // Discard region information.
  3725. return 0;
  3726. }
  3727. }
  3728. /// Test if the given instruction is in a position to be optimized
  3729. /// with a tail-call. This roughly means that it's in a block with
  3730. /// a return and there's nothing that needs to be scheduled
  3731. /// between it and the return.
  3732. ///
  3733. /// This function only tests target-independent requirements.
  3734. static bool
  3735. isInTailCallPosition(CallSite CS, Attributes CalleeRetAttr,
  3736. const TargetLowering &TLI) {
  3737. const Instruction *I = CS.getInstruction();
  3738. const BasicBlock *ExitBB = I->getParent();
  3739. const TerminatorInst *Term = ExitBB->getTerminator();
  3740. const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
  3741. const Function *F = ExitBB->getParent();
  3742. // The block must end in a return statement or unreachable.
  3743. //
  3744. // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
  3745. // an unreachable, for now. The way tailcall optimization is currently
  3746. // implemented means it will add an epilogue followed by a jump. That is
  3747. // not profitable. Also, if the callee is a special function (e.g.
  3748. // longjmp on x86), it can end up causing miscompilation that has not
  3749. // been fully understood.
  3750. if (!Ret &&
  3751. (!GuaranteedTailCallOpt || !isa<UnreachableInst>(Term))) return false;
  3752. // If I will have a chain, make sure no other instruction that will have a
  3753. // chain interposes between I and the return.
  3754. if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
  3755. !I->isSafeToSpeculativelyExecute())
  3756. for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
  3757. --BBI) {
  3758. if (&*BBI == I)
  3759. break;
  3760. if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
  3761. !BBI->isSafeToSpeculativelyExecute())
  3762. return false;
  3763. }
  3764. // If the block ends with a void return or unreachable, it doesn't matter
  3765. // what the call's return type is.
  3766. if (!Ret || Ret->getNumOperands() == 0) return true;
  3767. // If the return value is undef, it doesn't matter what the call's
  3768. // return type is.
  3769. if (isa<UndefValue>(Ret->getOperand(0))) return true;
  3770. // Conservatively require the attributes of the call to match those of
  3771. // the return. Ignore noalias because it doesn't affect the call sequence.
  3772. unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
  3773. if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
  3774. return false;
  3775. // It's not safe to eliminate the sign / zero extension of the return value.
  3776. if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
  3777. return false;
  3778. // Otherwise, make sure the unmodified return value of I is the return value.
  3779. for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
  3780. U = dyn_cast<Instruction>(U->getOperand(0))) {
  3781. if (!U)
  3782. return false;
  3783. if (!U->hasOneUse())
  3784. return false;
  3785. if (U == I)
  3786. break;
  3787. // Check for a truly no-op truncate.
  3788. if (isa<TruncInst>(U) &&
  3789. TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
  3790. continue;
  3791. // Check for a truly no-op bitcast.
  3792. if (isa<BitCastInst>(U) &&
  3793. (U->getOperand(0)->getType() == U->getType() ||
  3794. (U->getOperand(0)->getType()->isPointerTy() &&
  3795. U->getType()->isPointerTy())))
  3796. continue;
  3797. // Otherwise it's not a true no-op.
  3798. return false;
  3799. }
  3800. return true;
  3801. }
  3802. void SelectionDAGBuilder::LowerCallTo(CallSite CS, SDValue Callee,
  3803. bool isTailCall,
  3804. MachineBasicBlock *LandingPad) {
  3805. const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
  3806. const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
  3807. const Type *RetTy = FTy->getReturnType();
  3808. MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
  3809. MCSymbol *BeginLabel = 0;
  3810. TargetLowering::ArgListTy Args;
  3811. TargetLowering::ArgListEntry Entry;
  3812. Args.reserve(CS.arg_size());
  3813. // Check whether the function can return without sret-demotion.
  3814. SmallVector<EVT, 4> OutVTs;
  3815. SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
  3816. SmallVector<uint64_t, 4> Offsets;
  3817. getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
  3818. OutVTs, OutsFlags, TLI, &Offsets);
  3819. bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
  3820. FTy->isVarArg(), OutVTs, OutsFlags, DAG);
  3821. SDValue DemoteStackSlot;
  3822. if (!CanLowerReturn) {
  3823. uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
  3824. FTy->getReturnType());
  3825. unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
  3826. FTy->getReturnType());
  3827. MachineFunction &MF = DAG.getMachineFunction();
  3828. int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
  3829. const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
  3830. DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
  3831. Entry.Node = DemoteStackSlot;
  3832. Entry.Ty = StackSlotPtrType;
  3833. Entry.isSExt = false;
  3834. Entry.isZExt = false;
  3835. Entry.isInReg = false;
  3836. Entry.isSRet = true;
  3837. Entry.isNest = false;
  3838. Entry.isByVal = false;
  3839. Entry.Alignment = Align;
  3840. Args.push_back(Entry);
  3841. RetTy = Type::getVoidTy(FTy->getContext());
  3842. }
  3843. for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  3844. i != e; ++i) {
  3845. SDValue ArgNode = getValue(*i);
  3846. Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
  3847. unsigned attrInd = i - CS.arg_begin() + 1;
  3848. Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
  3849. Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
  3850. Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
  3851. Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
  3852. Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
  3853. Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
  3854. Entry.Alignment = CS.getParamAlignment(attrInd);
  3855. Args.push_back(Entry);
  3856. }
  3857. if (LandingPad && MMI) {
  3858. // Insert a label before the invoke call to mark the try range. This can be
  3859. // used to detect deletion of the invoke via the MachineModuleInfo.
  3860. BeginLabel = MMI->getContext().CreateTempSymbol();
  3861. // For SjLj, keep track of which landing pads go with which invokes
  3862. // so as to maintain the ordering of pads in the LSDA.
  3863. unsigned CallSiteIndex = MMI->getCurrentCallSite();
  3864. if (CallSiteIndex) {
  3865. MMI->setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  3866. // Now that the call site is handled, stop tracking it.
  3867. MMI->setCurrentCallSite(0);
  3868. }
  3869. // Both PendingLoads and PendingExports must be flushed here;
  3870. // this call might not return.
  3871. (void)getRoot();
  3872. DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel));
  3873. }
  3874. // Check if target-independent constraints permit a tail call here.
  3875. // Target-dependent constraints are checked within TLI.LowerCallTo.
  3876. if (isTailCall &&
  3877. !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
  3878. isTailCall = false;
  3879. std::pair<SDValue,SDValue> Result =
  3880. TLI.LowerCallTo(getRoot(), RetTy,
  3881. CS.paramHasAttr(0, Attribute::SExt),
  3882. CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
  3883. CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
  3884. CS.getCallingConv(),
  3885. isTailCall,
  3886. !CS.getInstruction()->use_empty(),
  3887. Callee, Args, DAG, getCurDebugLoc());
  3888. assert((isTailCall || Result.second.getNode()) &&
  3889. "Non-null chain expected with non-tail call!");
  3890. assert((Result.second.getNode() || !Result.first.getNode()) &&
  3891. "Null value expected with tail call!");
  3892. if (Result.first.getNode()) {
  3893. setValue(CS.getInstruction(), Result.first);
  3894. } else if (!CanLowerReturn && Result.second.getNode()) {
  3895. // The instruction result is the result of loading from the
  3896. // hidden sret parameter.
  3897. SmallVector<EVT, 1> PVTs;
  3898. const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
  3899. ComputeValueVTs(TLI, PtrRetTy, PVTs);
  3900. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  3901. EVT PtrVT = PVTs[0];
  3902. unsigned NumValues = OutVTs.size();
  3903. SmallVector<SDValue, 4> Values(NumValues);
  3904. SmallVector<SDValue, 4> Chains(NumValues);
  3905. for (unsigned i = 0; i < NumValues; ++i) {
  3906. SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
  3907. DemoteStackSlot,
  3908. DAG.getConstant(Offsets[i], PtrVT));
  3909. SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
  3910. Add, NULL, Offsets[i], false, false, 1);
  3911. Values[i] = L;
  3912. Chains[i] = L.getValue(1);
  3913. }
  3914. SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
  3915. MVT::Other, &Chains[0], NumValues);
  3916. PendingLoads.push_back(Chain);
  3917. // Collect the legal value parts into potentially illegal values
  3918. // that correspond to the original function's return values.
  3919. SmallVector<EVT, 4> RetTys;
  3920. RetTy = FTy->getReturnType();
  3921. ComputeValueVTs(TLI, RetTy, RetTys);
  3922. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  3923. SmallVector<SDValue, 4> ReturnValues;
  3924. unsigned CurReg = 0;
  3925. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  3926. EVT VT = RetTys[I];
  3927. EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
  3928. unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
  3929. SDValue ReturnValue =
  3930. getCopyFromParts(DAG, getCurDebugLoc(), &Values[CurReg], NumRegs,
  3931. RegisterVT, VT, AssertOp);
  3932. ReturnValues.push_back(ReturnValue);
  3933. CurReg += NumRegs;
  3934. }
  3935. setValue(CS.getInstruction(),
  3936. DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
  3937. DAG.getVTList(&RetTys[0], RetTys.size()),
  3938. &ReturnValues[0], ReturnValues.size()));
  3939. }
  3940. // As a special case, a null chain means that a tail call has been emitted and
  3941. // the DAG root is already updated.
  3942. if (Result.second.getNode())
  3943. DAG.setRoot(Result.second);
  3944. else
  3945. HasTailCall = true;
  3946. if (LandingPad && MMI) {
  3947. // Insert a label at the end of the invoke call to mark the try range. This
  3948. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  3949. MCSymbol *EndLabel = MMI->getContext().CreateTempSymbol();
  3950. DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel));
  3951. // Inform MachineModuleInfo of range.
  3952. MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
  3953. }
  3954. }
  3955. /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
  3956. /// value is equal or not-equal to zero.
  3957. static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
  3958. for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
  3959. UI != E; ++UI) {
  3960. if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
  3961. if (IC->isEquality())
  3962. if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
  3963. if (C->isNullValue())
  3964. continue;
  3965. // Unknown instruction.
  3966. return false;
  3967. }
  3968. return true;
  3969. }
  3970. static SDValue getMemCmpLoad(Value *PtrVal, MVT LoadVT, const Type *LoadTy,
  3971. SelectionDAGBuilder &Builder) {
  3972. // Check to see if this load can be trivially constant folded, e.g. if the
  3973. // input is from a string literal.
  3974. if (Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  3975. // Cast pointer to the type we really want to load.
  3976. LoadInput = ConstantExpr::getBitCast(LoadInput,
  3977. PointerType::getUnqual(LoadTy));
  3978. if (Constant *LoadCst = ConstantFoldLoadFromConstPtr(LoadInput, Builder.TD))
  3979. return Builder.getValue(LoadCst);
  3980. }
  3981. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  3982. // still constant memory, the input chain can be the entry node.
  3983. SDValue Root;
  3984. bool ConstantMemory = false;
  3985. // Do not serialize (non-volatile) loads of constant memory with anything.
  3986. if (Builder.AA->pointsToConstantMemory(PtrVal)) {
  3987. Root = Builder.DAG.getEntryNode();
  3988. ConstantMemory = true;
  3989. } else {
  3990. // Do not serialize non-volatile loads against each other.
  3991. Root = Builder.DAG.getRoot();
  3992. }
  3993. SDValue Ptr = Builder.getValue(PtrVal);
  3994. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
  3995. Ptr, PtrVal /*SrcValue*/, 0/*SVOffset*/,
  3996. false /*volatile*/,
  3997. false /*nontemporal*/, 1 /* align=1 */);
  3998. if (!ConstantMemory)
  3999. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  4000. return LoadVal;
  4001. }
  4002. /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
  4003. /// If so, return true and lower it, otherwise return false and it will be
  4004. /// lowered like a normal call.
  4005. bool SelectionDAGBuilder::visitMemCmpCall(CallInst &I) {
  4006. // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
  4007. if (I.getNumOperands() != 4)
  4008. return false;
  4009. Value *LHS = I.getOperand(1), *RHS = I.getOperand(2);
  4010. if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
  4011. !I.getOperand(3)->getType()->isIntegerTy() ||
  4012. !I.getType()->isIntegerTy())
  4013. return false;
  4014. ConstantInt *Size = dyn_cast<ConstantInt>(I.getOperand(3));
  4015. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  4016. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  4017. if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
  4018. bool ActuallyDoIt = true;
  4019. MVT LoadVT;
  4020. const Type *LoadTy;
  4021. switch (Size->getZExtValue()) {
  4022. default:
  4023. LoadVT = MVT::Other;
  4024. LoadTy = 0;
  4025. ActuallyDoIt = false;
  4026. break;
  4027. case 2:
  4028. LoadVT = MVT::i16;
  4029. LoadTy = Type::getInt16Ty(Size->getContext());
  4030. break;
  4031. case 4:
  4032. LoadVT = MVT::i32;
  4033. LoadTy = Type::getInt32Ty(Size->getContext());
  4034. break;
  4035. case 8:
  4036. LoadVT = MVT::i64;
  4037. LoadTy = Type::getInt64Ty(Size->getContext());
  4038. break;
  4039. /*
  4040. case 16:
  4041. LoadVT = MVT::v4i32;
  4042. LoadTy = Type::getInt32Ty(Size->getContext());
  4043. LoadTy = VectorType::get(LoadTy, 4);
  4044. break;
  4045. */
  4046. }
  4047. // This turns into unaligned loads. We only do this if the target natively
  4048. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  4049. // we'll only produce a small number of byte loads.
  4050. // Require that we can find a legal MVT, and only do this if the target
  4051. // supports unaligned loads of that type. Expanding into byte loads would
  4052. // bloat the code.
  4053. if (ActuallyDoIt && Size->getZExtValue() > 4) {
  4054. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  4055. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  4056. if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
  4057. ActuallyDoIt = false;
  4058. }
  4059. if (ActuallyDoIt) {
  4060. SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
  4061. SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
  4062. SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
  4063. ISD::SETNE);
  4064. EVT CallVT = TLI.getValueType(I.getType(), true);
  4065. setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
  4066. return true;
  4067. }
  4068. }
  4069. return false;
  4070. }
  4071. void SelectionDAGBuilder::visitCall(CallInst &I) {
  4072. const char *RenameFn = 0;
  4073. if (Function *F = I.getCalledFunction()) {
  4074. if (F->isDeclaration()) {
  4075. const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
  4076. if (II) {
  4077. if (unsigned IID = II->getIntrinsicID(F)) {
  4078. RenameFn = visitIntrinsicCall(I, IID);
  4079. if (!RenameFn)
  4080. return;
  4081. }
  4082. }
  4083. if (unsigned IID = F->getIntrinsicID()) {
  4084. RenameFn = visitIntrinsicCall(I, IID);
  4085. if (!RenameFn)
  4086. return;
  4087. }
  4088. }
  4089. // Check for well-known libc/libm calls. If the function is internal, it
  4090. // can't be a library call.
  4091. if (!F->hasLocalLinkage() && F->hasName()) {
  4092. StringRef Name = F->getName();
  4093. if (Name == "copysign" || Name == "copysignf" || Name == "copysignl") {
  4094. if (I.getNumOperands() == 3 && // Basic sanity checks.
  4095. I.getOperand(1)->getType()->isFloatingPointTy() &&
  4096. I.getType() == I.getOperand(1)->getType() &&
  4097. I.getType() == I.getOperand(2)->getType()) {
  4098. SDValue LHS = getValue(I.getOperand(1));
  4099. SDValue RHS = getValue(I.getOperand(2));
  4100. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
  4101. LHS.getValueType(), LHS, RHS));
  4102. return;
  4103. }
  4104. } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
  4105. if (I.getNumOperands() == 2 && // Basic sanity checks.
  4106. I.getOperand(1)->getType()->isFloatingPointTy() &&
  4107. I.getType() == I.getOperand(1)->getType()) {
  4108. SDValue Tmp = getValue(I.getOperand(1));
  4109. setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
  4110. Tmp.getValueType(), Tmp));
  4111. return;
  4112. }
  4113. } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
  4114. if (I.getNumOperands() == 2 && // Basic sanity checks.
  4115. I.getOperand(1)->getType()->isFloatingPointTy() &&
  4116. I.getType() == I.getOperand(1)->getType() &&
  4117. I.onlyReadsMemory()) {
  4118. SDValue Tmp = getValue(I.getOperand(1));
  4119. setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
  4120. Tmp.getValueType(), Tmp));
  4121. return;
  4122. }
  4123. } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
  4124. if (I.getNumOperands() == 2 && // Basic sanity checks.
  4125. I.getOperand(1)->getType()->isFloatingPointTy() &&
  4126. I.getType() == I.getOperand(1)->getType() &&
  4127. I.onlyReadsMemory()) {
  4128. SDValue Tmp = getValue(I.getOperand(1));
  4129. setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
  4130. Tmp.getValueType(), Tmp));
  4131. return;
  4132. }
  4133. } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
  4134. if (I.getNumOperands() == 2 && // Basic sanity checks.
  4135. I.getOperand(1)->getType()->isFloatingPointTy() &&
  4136. I.getType() == I.getOperand(1)->getType() &&
  4137. I.onlyReadsMemory()) {
  4138. SDValue Tmp = getValue(I.getOperand(1));
  4139. setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
  4140. Tmp.getValueType(), Tmp));
  4141. return;
  4142. }
  4143. } else if (Name == "memcmp") {
  4144. if (visitMemCmpCall(I))
  4145. return;
  4146. }
  4147. }
  4148. } else if (isa<InlineAsm>(I.getOperand(0))) {
  4149. visitInlineAsm(&I);
  4150. return;
  4151. }
  4152. SDValue Callee;
  4153. if (!RenameFn)
  4154. Callee = getValue(I.getOperand(0));
  4155. else
  4156. Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
  4157. // Check if we can potentially perform a tail call. More detailed checking is
  4158. // be done within LowerCallTo, after more information about the call is known.
  4159. LowerCallTo(&I, Callee, I.isTailCall());
  4160. }
  4161. /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
  4162. /// this value and returns the result as a ValueVT value. This uses
  4163. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  4164. /// If the Flag pointer is NULL, no flag is used.
  4165. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
  4166. SDValue &Chain, SDValue *Flag) const {
  4167. // Assemble the legal parts into the final values.
  4168. SmallVector<SDValue, 4> Values(ValueVTs.size());
  4169. SmallVector<SDValue, 8> Parts;
  4170. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  4171. // Copy the legal parts from the registers.
  4172. EVT ValueVT = ValueVTs[Value];
  4173. unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
  4174. EVT RegisterVT = RegVTs[Value];
  4175. Parts.resize(NumRegs);
  4176. for (unsigned i = 0; i != NumRegs; ++i) {
  4177. SDValue P;
  4178. if (Flag == 0) {
  4179. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  4180. } else {
  4181. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  4182. *Flag = P.getValue(2);
  4183. }
  4184. Chain = P.getValue(1);
  4185. // If the source register was virtual and if we know something about it,
  4186. // add an assert node.
  4187. if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
  4188. RegisterVT.isInteger() && !RegisterVT.isVector()) {
  4189. unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
  4190. FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
  4191. if (FLI.LiveOutRegInfo.size() > SlotNo) {
  4192. FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
  4193. unsigned RegSize = RegisterVT.getSizeInBits();
  4194. unsigned NumSignBits = LOI.NumSignBits;
  4195. unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
  4196. // FIXME: We capture more information than the dag can represent. For
  4197. // now, just use the tightest assertzext/assertsext possible.
  4198. bool isSExt = true;
  4199. EVT FromVT(MVT::Other);
  4200. if (NumSignBits == RegSize)
  4201. isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
  4202. else if (NumZeroBits >= RegSize-1)
  4203. isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
  4204. else if (NumSignBits > RegSize-8)
  4205. isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
  4206. else if (NumZeroBits >= RegSize-8)
  4207. isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
  4208. else if (NumSignBits > RegSize-16)
  4209. isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
  4210. else if (NumZeroBits >= RegSize-16)
  4211. isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
  4212. else if (NumSignBits > RegSize-32)
  4213. isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
  4214. else if (NumZeroBits >= RegSize-32)
  4215. isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
  4216. if (FromVT != MVT::Other)
  4217. P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  4218. RegisterVT, P, DAG.getValueType(FromVT));
  4219. }
  4220. }
  4221. Parts[i] = P;
  4222. }
  4223. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
  4224. NumRegs, RegisterVT, ValueVT);
  4225. Part += NumRegs;
  4226. Parts.clear();
  4227. }
  4228. return DAG.getNode(ISD::MERGE_VALUES, dl,
  4229. DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
  4230. &Values[0], ValueVTs.size());
  4231. }
  4232. /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
  4233. /// specified value into the registers specified by this object. This uses
  4234. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  4235. /// If the Flag pointer is NULL, no flag is used.
  4236. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
  4237. SDValue &Chain, SDValue *Flag) const {
  4238. // Get the list of the values's legal parts.
  4239. unsigned NumRegs = Regs.size();
  4240. SmallVector<SDValue, 8> Parts(NumRegs);
  4241. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  4242. EVT ValueVT = ValueVTs[Value];
  4243. unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
  4244. EVT RegisterVT = RegVTs[Value];
  4245. getCopyToParts(DAG, dl,
  4246. Val.getValue(Val.getResNo() + Value),
  4247. &Parts[Part], NumParts, RegisterVT);
  4248. Part += NumParts;
  4249. }
  4250. // Copy the parts into the registers.
  4251. SmallVector<SDValue, 8> Chains(NumRegs);
  4252. for (unsigned i = 0; i != NumRegs; ++i) {
  4253. SDValue Part;
  4254. if (Flag == 0) {
  4255. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  4256. } else {
  4257. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  4258. *Flag = Part.getValue(1);
  4259. }
  4260. Chains[i] = Part.getValue(0);
  4261. }
  4262. if (NumRegs == 1 || Flag)
  4263. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  4264. // flagged to it. That is the CopyToReg nodes and the user are considered
  4265. // a single scheduling unit. If we create a TokenFactor and return it as
  4266. // chain, then the TokenFactor is both a predecessor (operand) of the
  4267. // user as well as a successor (the TF operands are flagged to the user).
  4268. // c1, f1 = CopyToReg
  4269. // c2, f2 = CopyToReg
  4270. // c3 = TokenFactor c1, c2
  4271. // ...
  4272. // = op c3, ..., f2
  4273. Chain = Chains[NumRegs-1];
  4274. else
  4275. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
  4276. }
  4277. /// AddInlineAsmOperands - Add this value to the specified inlineasm node
  4278. /// operand list. This adds the code marker and includes the number of
  4279. /// values added into it.
  4280. void RegsForValue::AddInlineAsmOperands(unsigned Code,
  4281. bool HasMatching,unsigned MatchingIdx,
  4282. SelectionDAG &DAG,
  4283. std::vector<SDValue> &Ops) const {
  4284. assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
  4285. unsigned Flag = Code | (Regs.size() << 3);
  4286. if (HasMatching)
  4287. Flag |= 0x80000000 | (MatchingIdx << 16);
  4288. SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
  4289. Ops.push_back(Res);
  4290. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  4291. unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  4292. EVT RegisterVT = RegVTs[Value];
  4293. for (unsigned i = 0; i != NumRegs; ++i) {
  4294. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  4295. Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
  4296. }
  4297. }
  4298. }
  4299. /// isAllocatableRegister - If the specified register is safe to allocate,
  4300. /// i.e. it isn't a stack pointer or some other special register, return the
  4301. /// register class for the register. Otherwise, return null.
  4302. static const TargetRegisterClass *
  4303. isAllocatableRegister(unsigned Reg, MachineFunction &MF,
  4304. const TargetLowering &TLI,
  4305. const TargetRegisterInfo *TRI) {
  4306. EVT FoundVT = MVT::Other;
  4307. const TargetRegisterClass *FoundRC = 0;
  4308. for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
  4309. E = TRI->regclass_end(); RCI != E; ++RCI) {
  4310. EVT ThisVT = MVT::Other;
  4311. const TargetRegisterClass *RC = *RCI;
  4312. // If none of the value types for this register class are valid, we
  4313. // can't use it. For example, 64-bit reg classes on 32-bit targets.
  4314. for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
  4315. I != E; ++I) {
  4316. if (TLI.isTypeLegal(*I)) {
  4317. // If we have already found this register in a different register class,
  4318. // choose the one with the largest VT specified. For example, on
  4319. // PowerPC, we favor f64 register classes over f32.
  4320. if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
  4321. ThisVT = *I;
  4322. break;
  4323. }
  4324. }
  4325. }
  4326. if (ThisVT == MVT::Other) continue;
  4327. // NOTE: This isn't ideal. In particular, this might allocate the
  4328. // frame pointer in functions that need it (due to them not being taken
  4329. // out of allocation, because a variable sized allocation hasn't been seen
  4330. // yet). This is a slight code pessimization, but should still work.
  4331. for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
  4332. E = RC->allocation_order_end(MF); I != E; ++I)
  4333. if (*I == Reg) {
  4334. // We found a matching register class. Keep looking at others in case
  4335. // we find one with larger registers that this physreg is also in.
  4336. FoundRC = RC;
  4337. FoundVT = ThisVT;
  4338. break;
  4339. }
  4340. }
  4341. return FoundRC;
  4342. }
  4343. namespace llvm {
  4344. /// AsmOperandInfo - This contains information for each constraint that we are
  4345. /// lowering.
  4346. class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
  4347. public TargetLowering::AsmOperandInfo {
  4348. public:
  4349. /// CallOperand - If this is the result output operand or a clobber
  4350. /// this is null, otherwise it is the incoming operand to the CallInst.
  4351. /// This gets modified as the asm is processed.
  4352. SDValue CallOperand;
  4353. /// AssignedRegs - If this is a register or register class operand, this
  4354. /// contains the set of register corresponding to the operand.
  4355. RegsForValue AssignedRegs;
  4356. explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
  4357. : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
  4358. }
  4359. /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
  4360. /// busy in OutputRegs/InputRegs.
  4361. void MarkAllocatedRegs(bool isOutReg, bool isInReg,
  4362. std::set<unsigned> &OutputRegs,
  4363. std::set<unsigned> &InputRegs,
  4364. const TargetRegisterInfo &TRI) const {
  4365. if (isOutReg) {
  4366. for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
  4367. MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
  4368. }
  4369. if (isInReg) {
  4370. for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
  4371. MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
  4372. }
  4373. }
  4374. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  4375. /// corresponds to. If there is no Value* for this operand, it returns
  4376. /// MVT::Other.
  4377. EVT getCallOperandValEVT(LLVMContext &Context,
  4378. const TargetLowering &TLI,
  4379. const TargetData *TD) const {
  4380. if (CallOperandVal == 0) return MVT::Other;
  4381. if (isa<BasicBlock>(CallOperandVal))
  4382. return TLI.getPointerTy();
  4383. const llvm::Type *OpTy = CallOperandVal->getType();
  4384. // If this is an indirect operand, the operand is a pointer to the
  4385. // accessed type.
  4386. if (isIndirect) {
  4387. const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  4388. if (!PtrTy)
  4389. llvm_report_error("Indirect operand for inline asm not a pointer!");
  4390. OpTy = PtrTy->getElementType();
  4391. }
  4392. // If OpTy is not a single value, it may be a struct/union that we
  4393. // can tile with integers.
  4394. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  4395. unsigned BitSize = TD->getTypeSizeInBits(OpTy);
  4396. switch (BitSize) {
  4397. default: break;
  4398. case 1:
  4399. case 8:
  4400. case 16:
  4401. case 32:
  4402. case 64:
  4403. case 128:
  4404. OpTy = IntegerType::get(Context, BitSize);
  4405. break;
  4406. }
  4407. }
  4408. return TLI.getValueType(OpTy, true);
  4409. }
  4410. private:
  4411. /// MarkRegAndAliases - Mark the specified register and all aliases in the
  4412. /// specified set.
  4413. static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
  4414. const TargetRegisterInfo &TRI) {
  4415. assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
  4416. Regs.insert(Reg);
  4417. if (const unsigned *Aliases = TRI.getAliasSet(Reg))
  4418. for (; *Aliases; ++Aliases)
  4419. Regs.insert(*Aliases);
  4420. }
  4421. };
  4422. } // end llvm namespace.
  4423. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  4424. /// specified operand. We prefer to assign virtual registers, to allow the
  4425. /// register allocator to handle the assignment process. However, if the asm
  4426. /// uses features that we can't model on machineinstrs, we have SDISel do the
  4427. /// allocation. This produces generally horrible, but correct, code.
  4428. ///
  4429. /// OpInfo describes the operand.
  4430. /// Input and OutputRegs are the set of already allocated physical registers.
  4431. ///
  4432. void SelectionDAGBuilder::
  4433. GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
  4434. std::set<unsigned> &OutputRegs,
  4435. std::set<unsigned> &InputRegs) {
  4436. LLVMContext &Context = FuncInfo.Fn->getContext();
  4437. // Compute whether this value requires an input register, an output register,
  4438. // or both.
  4439. bool isOutReg = false;
  4440. bool isInReg = false;
  4441. switch (OpInfo.Type) {
  4442. case InlineAsm::isOutput:
  4443. isOutReg = true;
  4444. // If there is an input constraint that matches this, we need to reserve
  4445. // the input register so no other inputs allocate to it.
  4446. isInReg = OpInfo.hasMatchingInput();
  4447. break;
  4448. case InlineAsm::isInput:
  4449. isInReg = true;
  4450. isOutReg = false;
  4451. break;
  4452. case InlineAsm::isClobber:
  4453. isOutReg = true;
  4454. isInReg = true;
  4455. break;
  4456. }
  4457. MachineFunction &MF = DAG.getMachineFunction();
  4458. SmallVector<unsigned, 4> Regs;
  4459. // If this is a constraint for a single physreg, or a constraint for a
  4460. // register class, find it.
  4461. std::pair<unsigned, const TargetRegisterClass*> PhysReg =
  4462. TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
  4463. OpInfo.ConstraintVT);
  4464. unsigned NumRegs = 1;
  4465. if (OpInfo.ConstraintVT != MVT::Other) {
  4466. // If this is a FP input in an integer register (or visa versa) insert a bit
  4467. // cast of the input value. More generally, handle any case where the input
  4468. // value disagrees with the register class we plan to stick this in.
  4469. if (OpInfo.Type == InlineAsm::isInput &&
  4470. PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
  4471. // Try to convert to the first EVT that the reg class contains. If the
  4472. // types are identical size, use a bitcast to convert (e.g. two differing
  4473. // vector types).
  4474. EVT RegVT = *PhysReg.second->vt_begin();
  4475. if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
  4476. OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
  4477. RegVT, OpInfo.CallOperand);
  4478. OpInfo.ConstraintVT = RegVT;
  4479. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  4480. // If the input is a FP value and we want it in FP registers, do a
  4481. // bitcast to the corresponding integer type. This turns an f64 value
  4482. // into i64, which can be passed with two i32 values on a 32-bit
  4483. // machine.
  4484. RegVT = EVT::getIntegerVT(Context,
  4485. OpInfo.ConstraintVT.getSizeInBits());
  4486. OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
  4487. RegVT, OpInfo.CallOperand);
  4488. OpInfo.ConstraintVT = RegVT;
  4489. }
  4490. }
  4491. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  4492. }
  4493. EVT RegVT;
  4494. EVT ValueVT = OpInfo.ConstraintVT;
  4495. // If this is a constraint for a specific physical register, like {r17},
  4496. // assign it now.
  4497. if (unsigned AssignedReg = PhysReg.first) {
  4498. const TargetRegisterClass *RC = PhysReg.second;
  4499. if (OpInfo.ConstraintVT == MVT::Other)
  4500. ValueVT = *RC->vt_begin();
  4501. // Get the actual register value type. This is important, because the user
  4502. // may have asked for (e.g.) the AX register in i32 type. We need to
  4503. // remember that AX is actually i16 to get the right extension.
  4504. RegVT = *RC->vt_begin();
  4505. // This is a explicit reference to a physical register.
  4506. Regs.push_back(AssignedReg);
  4507. // If this is an expanded reference, add the rest of the regs to Regs.
  4508. if (NumRegs != 1) {
  4509. TargetRegisterClass::iterator I = RC->begin();
  4510. for (; *I != AssignedReg; ++I)
  4511. assert(I != RC->end() && "Didn't find reg!");
  4512. // Already added the first reg.
  4513. --NumRegs; ++I;
  4514. for (; NumRegs; --NumRegs, ++I) {
  4515. assert(I != RC->end() && "Ran out of registers to allocate!");
  4516. Regs.push_back(*I);
  4517. }
  4518. }
  4519. OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
  4520. const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
  4521. OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
  4522. return;
  4523. }
  4524. // Otherwise, if this was a reference to an LLVM register class, create vregs
  4525. // for this reference.
  4526. if (const TargetRegisterClass *RC = PhysReg.second) {
  4527. RegVT = *RC->vt_begin();
  4528. if (OpInfo.ConstraintVT == MVT::Other)
  4529. ValueVT = RegVT;
  4530. // Create the appropriate number of virtual registers.
  4531. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4532. for (; NumRegs; --NumRegs)
  4533. Regs.push_back(RegInfo.createVirtualRegister(RC));
  4534. OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
  4535. return;
  4536. }
  4537. // This is a reference to a register class that doesn't directly correspond
  4538. // to an LLVM register class. Allocate NumRegs consecutive, available,
  4539. // registers from the class.
  4540. std::vector<unsigned> RegClassRegs
  4541. = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
  4542. OpInfo.ConstraintVT);
  4543. const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
  4544. unsigned NumAllocated = 0;
  4545. for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
  4546. unsigned Reg = RegClassRegs[i];
  4547. // See if this register is available.
  4548. if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
  4549. (isInReg && InputRegs.count(Reg))) { // Already used.
  4550. // Make sure we find consecutive registers.
  4551. NumAllocated = 0;
  4552. continue;
  4553. }
  4554. // Check to see if this register is allocatable (i.e. don't give out the
  4555. // stack pointer).
  4556. const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
  4557. if (!RC) { // Couldn't allocate this register.
  4558. // Reset NumAllocated to make sure we return consecutive registers.
  4559. NumAllocated = 0;
  4560. continue;
  4561. }
  4562. // Okay, this register is good, we can use it.
  4563. ++NumAllocated;
  4564. // If we allocated enough consecutive registers, succeed.
  4565. if (NumAllocated == NumRegs) {
  4566. unsigned RegStart = (i-NumAllocated)+1;
  4567. unsigned RegEnd = i+1;
  4568. // Mark all of the allocated registers used.
  4569. for (unsigned i = RegStart; i != RegEnd; ++i)
  4570. Regs.push_back(RegClassRegs[i]);
  4571. OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
  4572. OpInfo.ConstraintVT);
  4573. OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
  4574. return;
  4575. }
  4576. }
  4577. // Otherwise, we couldn't allocate enough registers for this.
  4578. }
  4579. /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
  4580. /// processed uses a memory 'm' constraint.
  4581. static bool
  4582. hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
  4583. const TargetLowering &TLI) {
  4584. for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
  4585. InlineAsm::ConstraintInfo &CI = CInfos[i];
  4586. for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
  4587. TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
  4588. if (CType == TargetLowering::C_Memory)
  4589. return true;
  4590. }
  4591. // Indirect operand accesses access memory.
  4592. if (CI.isIndirect)
  4593. return true;
  4594. }
  4595. return false;
  4596. }
  4597. /// visitInlineAsm - Handle a call to an InlineAsm object.
  4598. ///
  4599. void SelectionDAGBuilder::visitInlineAsm(CallSite CS) {
  4600. InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  4601. /// ConstraintOperands - Information about all of the constraints.
  4602. std::vector<SDISelAsmOperandInfo> ConstraintOperands;
  4603. std::set<unsigned> OutputRegs, InputRegs;
  4604. // Do a prepass over the constraints, canonicalizing them, and building up the
  4605. // ConstraintOperands list.
  4606. std::vector<InlineAsm::ConstraintInfo>
  4607. ConstraintInfos = IA->ParseConstraints();
  4608. bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
  4609. SDValue Chain, Flag;
  4610. // We won't need to flush pending loads if this asm doesn't touch
  4611. // memory and is nonvolatile.
  4612. if (hasMemory || IA->hasSideEffects())
  4613. Chain = getRoot();
  4614. else
  4615. Chain = DAG.getRoot();
  4616. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  4617. unsigned ResNo = 0; // ResNo - The result number of the next output.
  4618. for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
  4619. ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
  4620. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  4621. EVT OpVT = MVT::Other;
  4622. // Compute the value type for each operand.
  4623. switch (OpInfo.Type) {
  4624. case InlineAsm::isOutput:
  4625. // Indirect outputs just consume an argument.
  4626. if (OpInfo.isIndirect) {
  4627. OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
  4628. break;
  4629. }
  4630. // The return value of the call is this value. As such, there is no
  4631. // corresponding argument.
  4632. assert(!CS.getType()->isVoidTy() &&
  4633. "Bad inline asm!");
  4634. if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
  4635. OpVT = TLI.getValueType(STy->getElementType(ResNo));
  4636. } else {
  4637. assert(ResNo == 0 && "Asm only has one result!");
  4638. OpVT = TLI.getValueType(CS.getType());
  4639. }
  4640. ++ResNo;
  4641. break;
  4642. case InlineAsm::isInput:
  4643. OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
  4644. break;
  4645. case InlineAsm::isClobber:
  4646. // Nothing to do.
  4647. break;
  4648. }
  4649. // If this is an input or an indirect output, process the call argument.
  4650. // BasicBlocks are labels, currently appearing only in asm's.
  4651. if (OpInfo.CallOperandVal) {
  4652. // Strip bitcasts, if any. This mostly comes up for functions.
  4653. OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
  4654. if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  4655. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  4656. } else {
  4657. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  4658. }
  4659. OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
  4660. }
  4661. OpInfo.ConstraintVT = OpVT;
  4662. }
  4663. // Second pass over the constraints: compute which constraint option to use
  4664. // and assign registers to constraints that want a specific physreg.
  4665. for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
  4666. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  4667. // If this is an output operand with a matching input operand, look up the
  4668. // matching input. If their types mismatch, e.g. one is an integer, the
  4669. // other is floating point, or their sizes are different, flag it as an
  4670. // error.
  4671. if (OpInfo.hasMatchingInput()) {
  4672. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  4673. if (OpInfo.ConstraintVT != Input.ConstraintVT) {
  4674. if ((OpInfo.ConstraintVT.isInteger() !=
  4675. Input.ConstraintVT.isInteger()) ||
  4676. (OpInfo.ConstraintVT.getSizeInBits() !=
  4677. Input.ConstraintVT.getSizeInBits())) {
  4678. llvm_report_error("Unsupported asm: input constraint"
  4679. " with a matching output constraint of incompatible"
  4680. " type!");
  4681. }
  4682. Input.ConstraintVT = OpInfo.ConstraintVT;
  4683. }
  4684. }
  4685. // Compute the constraint code and ConstraintType to use.
  4686. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
  4687. // If this is a memory input, and if the operand is not indirect, do what we
  4688. // need to to provide an address for the memory input.
  4689. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  4690. !OpInfo.isIndirect) {
  4691. assert(OpInfo.Type == InlineAsm::isInput &&
  4692. "Can only indirectify direct input operands!");
  4693. // Memory operands really want the address of the value. If we don't have
  4694. // an indirect input, put it in the constpool if we can, otherwise spill
  4695. // it to a stack slot.
  4696. // If the operand is a float, integer, or vector constant, spill to a
  4697. // constant pool entry to get its address.
  4698. Value *OpVal = OpInfo.CallOperandVal;
  4699. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  4700. isa<ConstantVector>(OpVal)) {
  4701. OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
  4702. TLI.getPointerTy());
  4703. } else {
  4704. // Otherwise, create a stack slot and emit a store to it before the
  4705. // asm.
  4706. const Type *Ty = OpVal->getType();
  4707. uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
  4708. unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
  4709. MachineFunction &MF = DAG.getMachineFunction();
  4710. int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
  4711. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
  4712. Chain = DAG.getStore(Chain, getCurDebugLoc(),
  4713. OpInfo.CallOperand, StackSlot, NULL, 0,
  4714. false, false, 0);
  4715. OpInfo.CallOperand = StackSlot;
  4716. }
  4717. // There is no longer a Value* corresponding to this operand.
  4718. OpInfo.CallOperandVal = 0;
  4719. // It is now an indirect operand.
  4720. OpInfo.isIndirect = true;
  4721. }
  4722. // If this constraint is for a specific register, allocate it before
  4723. // anything else.
  4724. if (OpInfo.ConstraintType == TargetLowering::C_Register)
  4725. GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
  4726. }
  4727. ConstraintInfos.clear();
  4728. // Second pass - Loop over all of the operands, assigning virtual or physregs
  4729. // to register class operands.
  4730. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  4731. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  4732. // C_Register operands have already been allocated, Other/Memory don't need
  4733. // to be.
  4734. if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
  4735. GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
  4736. }
  4737. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  4738. std::vector<SDValue> AsmNodeOperands;
  4739. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  4740. AsmNodeOperands.push_back(
  4741. DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
  4742. TLI.getPointerTy()));
  4743. // Loop over all of the inputs, copying the operand values into the
  4744. // appropriate registers and processing the output regs.
  4745. RegsForValue RetValRegs;
  4746. // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
  4747. std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
  4748. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  4749. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  4750. switch (OpInfo.Type) {
  4751. case InlineAsm::isOutput: {
  4752. if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
  4753. OpInfo.ConstraintType != TargetLowering::C_Register) {
  4754. // Memory output, or 'other' output (e.g. 'X' constraint).
  4755. assert(OpInfo.isIndirect && "Memory output must be indirect operand");
  4756. // Add information to the INLINEASM node to know about this output.
  4757. unsigned ResOpType = 4/*MEM*/ | (1<<3);
  4758. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  4759. TLI.getPointerTy()));
  4760. AsmNodeOperands.push_back(OpInfo.CallOperand);
  4761. break;
  4762. }
  4763. // Otherwise, this is a register or register class output.
  4764. // Copy the output from the appropriate register. Find a register that
  4765. // we can use.
  4766. if (OpInfo.AssignedRegs.Regs.empty()) {
  4767. llvm_report_error("Couldn't allocate output reg for"
  4768. " constraint '" + OpInfo.ConstraintCode + "'!");
  4769. }
  4770. // If this is an indirect operand, store through the pointer after the
  4771. // asm.
  4772. if (OpInfo.isIndirect) {
  4773. IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
  4774. OpInfo.CallOperandVal));
  4775. } else {
  4776. // This is the result value of the call.
  4777. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  4778. // Concatenate this output onto the outputs list.
  4779. RetValRegs.append(OpInfo.AssignedRegs);
  4780. }
  4781. // Add information to the INLINEASM node to know that this register is
  4782. // set.
  4783. OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
  4784. 6 /* EARLYCLOBBER REGDEF */ :
  4785. 2 /* REGDEF */ ,
  4786. false,
  4787. 0,
  4788. DAG,
  4789. AsmNodeOperands);
  4790. break;
  4791. }
  4792. case InlineAsm::isInput: {
  4793. SDValue InOperandVal = OpInfo.CallOperand;
  4794. if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
  4795. // If this is required to match an output register we have already set,
  4796. // just use its register.
  4797. unsigned OperandNo = OpInfo.getMatchedOperand();
  4798. // Scan until we find the definition we already emitted of this operand.
  4799. // When we find it, create a RegsForValue operand.
  4800. unsigned CurOp = 2; // The first operand.
  4801. for (; OperandNo; --OperandNo) {
  4802. // Advance to the next operand.
  4803. unsigned OpFlag =
  4804. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  4805. assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
  4806. (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
  4807. (OpFlag & 7) == 4 /*MEM*/) &&
  4808. "Skipped past definitions?");
  4809. CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
  4810. }
  4811. unsigned OpFlag =
  4812. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  4813. if ((OpFlag & 7) == 2 /*REGDEF*/
  4814. || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
  4815. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  4816. if (OpInfo.isIndirect) {
  4817. llvm_report_error("Don't know how to handle tied indirect "
  4818. "register inputs yet!");
  4819. }
  4820. RegsForValue MatchedRegs;
  4821. MatchedRegs.TLI = &TLI;
  4822. MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
  4823. EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
  4824. MatchedRegs.RegVTs.push_back(RegVT);
  4825. MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
  4826. for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
  4827. i != e; ++i)
  4828. MatchedRegs.Regs.push_back
  4829. (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
  4830. // Use the produced MatchedRegs object to
  4831. MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
  4832. Chain, &Flag);
  4833. MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
  4834. true, OpInfo.getMatchedOperand(),
  4835. DAG, AsmNodeOperands);
  4836. break;
  4837. } else {
  4838. assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
  4839. assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
  4840. "Unexpected number of operands");
  4841. // Add information to the INLINEASM node to know about this input.
  4842. // See InlineAsm.h isUseOperandTiedToDef.
  4843. OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
  4844. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
  4845. TLI.getPointerTy()));
  4846. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  4847. break;
  4848. }
  4849. }
  4850. if (OpInfo.ConstraintType == TargetLowering::C_Other) {
  4851. assert(!OpInfo.isIndirect &&
  4852. "Don't know how to handle indirect other inputs yet!");
  4853. std::vector<SDValue> Ops;
  4854. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
  4855. hasMemory, Ops, DAG);
  4856. if (Ops.empty()) {
  4857. llvm_report_error("Invalid operand for inline asm"
  4858. " constraint '" + OpInfo.ConstraintCode + "'!");
  4859. }
  4860. // Add information to the INLINEASM node to know about this input.
  4861. unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
  4862. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  4863. TLI.getPointerTy()));
  4864. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  4865. break;
  4866. } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  4867. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  4868. assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
  4869. "Memory operands expect pointer values");
  4870. // Add information to the INLINEASM node to know about this input.
  4871. unsigned ResOpType = 4/*MEM*/ | (1<<3);
  4872. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  4873. TLI.getPointerTy()));
  4874. AsmNodeOperands.push_back(InOperandVal);
  4875. break;
  4876. }
  4877. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  4878. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  4879. "Unknown constraint type!");
  4880. assert(!OpInfo.isIndirect &&
  4881. "Don't know how to handle indirect register inputs yet!");
  4882. // Copy the input into the appropriate registers.
  4883. if (OpInfo.AssignedRegs.Regs.empty() ||
  4884. !OpInfo.AssignedRegs.areValueTypesLegal()) {
  4885. llvm_report_error("Couldn't allocate input reg for"
  4886. " constraint '"+ OpInfo.ConstraintCode +"'!");
  4887. }
  4888. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
  4889. Chain, &Flag);
  4890. OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
  4891. DAG, AsmNodeOperands);
  4892. break;
  4893. }
  4894. case InlineAsm::isClobber: {
  4895. // Add the clobbered value to the operand list, so that the register
  4896. // allocator is aware that the physreg got clobbered.
  4897. if (!OpInfo.AssignedRegs.Regs.empty())
  4898. OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
  4899. false, 0, DAG,
  4900. AsmNodeOperands);
  4901. break;
  4902. }
  4903. }
  4904. }
  4905. // Finish up input operands.
  4906. AsmNodeOperands[0] = Chain;
  4907. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  4908. Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
  4909. DAG.getVTList(MVT::Other, MVT::Flag),
  4910. &AsmNodeOperands[0], AsmNodeOperands.size());
  4911. Flag = Chain.getValue(1);
  4912. // If this asm returns a register value, copy the result from that register
  4913. // and set it as the value of the call.
  4914. if (!RetValRegs.Regs.empty()) {
  4915. SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
  4916. Chain, &Flag);
  4917. // FIXME: Why don't we do this for inline asms with MRVs?
  4918. if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
  4919. EVT ResultType = TLI.getValueType(CS.getType());
  4920. // If any of the results of the inline asm is a vector, it may have the
  4921. // wrong width/num elts. This can happen for register classes that can
  4922. // contain multiple different value types. The preg or vreg allocated may
  4923. // not have the same VT as was expected. Convert it to the right type
  4924. // with bit_convert.
  4925. if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
  4926. Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
  4927. ResultType, Val);
  4928. } else if (ResultType != Val.getValueType() &&
  4929. ResultType.isInteger() && Val.getValueType().isInteger()) {
  4930. // If a result value was tied to an input value, the computed result may
  4931. // have a wider width than the expected result. Extract the relevant
  4932. // portion.
  4933. Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
  4934. }
  4935. assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
  4936. }
  4937. setValue(CS.getInstruction(), Val);
  4938. // Don't need to use this as a chain in this case.
  4939. if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
  4940. return;
  4941. }
  4942. std::vector<std::pair<SDValue, Value*> > StoresToEmit;
  4943. // Process indirect outputs, first output all of the flagged copies out of
  4944. // physregs.
  4945. for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
  4946. RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
  4947. Value *Ptr = IndirectStoresToEmit[i].second;
  4948. SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
  4949. Chain, &Flag);
  4950. StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
  4951. }
  4952. // Emit the non-flagged stores from the physregs.
  4953. SmallVector<SDValue, 8> OutChains;
  4954. for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
  4955. SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
  4956. StoresToEmit[i].first,
  4957. getValue(StoresToEmit[i].second),
  4958. StoresToEmit[i].second, 0,
  4959. false, false, 0);
  4960. OutChains.push_back(Val);
  4961. }
  4962. if (!OutChains.empty())
  4963. Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
  4964. &OutChains[0], OutChains.size());
  4965. DAG.setRoot(Chain);
  4966. }
  4967. void SelectionDAGBuilder::visitVAStart(CallInst &I) {
  4968. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
  4969. MVT::Other, getRoot(),
  4970. getValue(I.getOperand(1)),
  4971. DAG.getSrcValue(I.getOperand(1))));
  4972. }
  4973. void SelectionDAGBuilder::visitVAArg(VAArgInst &I) {
  4974. SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
  4975. getRoot(), getValue(I.getOperand(0)),
  4976. DAG.getSrcValue(I.getOperand(0)));
  4977. setValue(&I, V);
  4978. DAG.setRoot(V.getValue(1));
  4979. }
  4980. void SelectionDAGBuilder::visitVAEnd(CallInst &I) {
  4981. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
  4982. MVT::Other, getRoot(),
  4983. getValue(I.getOperand(1)),
  4984. DAG.getSrcValue(I.getOperand(1))));
  4985. }
  4986. void SelectionDAGBuilder::visitVACopy(CallInst &I) {
  4987. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
  4988. MVT::Other, getRoot(),
  4989. getValue(I.getOperand(1)),
  4990. getValue(I.getOperand(2)),
  4991. DAG.getSrcValue(I.getOperand(1)),
  4992. DAG.getSrcValue(I.getOperand(2))));
  4993. }
  4994. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  4995. /// implementation, which just calls LowerCall.
  4996. /// FIXME: When all targets are
  4997. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  4998. std::pair<SDValue, SDValue>
  4999. TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
  5000. bool RetSExt, bool RetZExt, bool isVarArg,
  5001. bool isInreg, unsigned NumFixedArgs,
  5002. CallingConv::ID CallConv, bool isTailCall,
  5003. bool isReturnValueUsed,
  5004. SDValue Callee,
  5005. ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
  5006. // Handle all of the outgoing arguments.
  5007. SmallVector<ISD::OutputArg, 32> Outs;
  5008. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  5009. SmallVector<EVT, 4> ValueVTs;
  5010. ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
  5011. for (unsigned Value = 0, NumValues = ValueVTs.size();
  5012. Value != NumValues; ++Value) {
  5013. EVT VT = ValueVTs[Value];
  5014. const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
  5015. SDValue Op = SDValue(Args[i].Node.getNode(),
  5016. Args[i].Node.getResNo() + Value);
  5017. ISD::ArgFlagsTy Flags;
  5018. unsigned OriginalAlignment =
  5019. getTargetData()->getABITypeAlignment(ArgTy);
  5020. if (Args[i].isZExt)
  5021. Flags.setZExt();
  5022. if (Args[i].isSExt)
  5023. Flags.setSExt();
  5024. if (Args[i].isInReg)
  5025. Flags.setInReg();
  5026. if (Args[i].isSRet)
  5027. Flags.setSRet();
  5028. if (Args[i].isByVal) {
  5029. Flags.setByVal();
  5030. const PointerType *Ty = cast<PointerType>(Args[i].Ty);
  5031. const Type *ElementTy = Ty->getElementType();
  5032. unsigned FrameAlign = getByValTypeAlignment(ElementTy);
  5033. unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
  5034. // For ByVal, alignment should come from FE. BE will guess if this
  5035. // info is not there but there are cases it cannot get right.
  5036. if (Args[i].Alignment)
  5037. FrameAlign = Args[i].Alignment;
  5038. Flags.setByValAlign(FrameAlign);
  5039. Flags.setByValSize(FrameSize);
  5040. }
  5041. if (Args[i].isNest)
  5042. Flags.setNest();
  5043. Flags.setOrigAlign(OriginalAlignment);
  5044. EVT PartVT = getRegisterType(RetTy->getContext(), VT);
  5045. unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
  5046. SmallVector<SDValue, 4> Parts(NumParts);
  5047. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  5048. if (Args[i].isSExt)
  5049. ExtendKind = ISD::SIGN_EXTEND;
  5050. else if (Args[i].isZExt)
  5051. ExtendKind = ISD::ZERO_EXTEND;
  5052. getCopyToParts(DAG, dl, Op, &Parts[0], NumParts,
  5053. PartVT, ExtendKind);
  5054. for (unsigned j = 0; j != NumParts; ++j) {
  5055. // if it isn't first piece, alignment must be 1
  5056. ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
  5057. if (NumParts > 1 && j == 0)
  5058. MyFlags.Flags.setSplit();
  5059. else if (j != 0)
  5060. MyFlags.Flags.setOrigAlign(1);
  5061. Outs.push_back(MyFlags);
  5062. }
  5063. }
  5064. }
  5065. // Handle the incoming return values from the call.
  5066. SmallVector<ISD::InputArg, 32> Ins;
  5067. SmallVector<EVT, 4> RetTys;
  5068. ComputeValueVTs(*this, RetTy, RetTys);
  5069. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  5070. EVT VT = RetTys[I];
  5071. EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
  5072. unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
  5073. for (unsigned i = 0; i != NumRegs; ++i) {
  5074. ISD::InputArg MyFlags;
  5075. MyFlags.VT = RegisterVT;
  5076. MyFlags.Used = isReturnValueUsed;
  5077. if (RetSExt)
  5078. MyFlags.Flags.setSExt();
  5079. if (RetZExt)
  5080. MyFlags.Flags.setZExt();
  5081. if (isInreg)
  5082. MyFlags.Flags.setInReg();
  5083. Ins.push_back(MyFlags);
  5084. }
  5085. }
  5086. SmallVector<SDValue, 4> InVals;
  5087. Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
  5088. Outs, Ins, dl, DAG, InVals);
  5089. // Verify that the target's LowerCall behaved as expected.
  5090. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  5091. "LowerCall didn't return a valid chain!");
  5092. assert((!isTailCall || InVals.empty()) &&
  5093. "LowerCall emitted a return value for a tail call!");
  5094. assert((isTailCall || InVals.size() == Ins.size()) &&
  5095. "LowerCall didn't emit the correct number of values!");
  5096. // For a tail call, the return value is merely live-out and there aren't
  5097. // any nodes in the DAG representing it. Return a special value to
  5098. // indicate that a tail call has been emitted and no more Instructions
  5099. // should be processed in the current block.
  5100. if (isTailCall) {
  5101. DAG.setRoot(Chain);
  5102. return std::make_pair(SDValue(), SDValue());
  5103. }
  5104. DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  5105. assert(InVals[i].getNode() &&
  5106. "LowerCall emitted a null value!");
  5107. assert(Ins[i].VT == InVals[i].getValueType() &&
  5108. "LowerCall emitted a value with the wrong type!");
  5109. });
  5110. // Collect the legal value parts into potentially illegal values
  5111. // that correspond to the original function's return values.
  5112. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  5113. if (RetSExt)
  5114. AssertOp = ISD::AssertSext;
  5115. else if (RetZExt)
  5116. AssertOp = ISD::AssertZext;
  5117. SmallVector<SDValue, 4> ReturnValues;
  5118. unsigned CurReg = 0;
  5119. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  5120. EVT VT = RetTys[I];
  5121. EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
  5122. unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
  5123. ReturnValues.push_back(getCopyFromParts(DAG, dl, &InVals[CurReg],
  5124. NumRegs, RegisterVT, VT,
  5125. AssertOp));
  5126. CurReg += NumRegs;
  5127. }
  5128. // For a function returning void, there is no return value. We can't create
  5129. // such a node, so we just return a null return value in that case. In
  5130. // that case, nothing will actualy look at the value.
  5131. if (ReturnValues.empty())
  5132. return std::make_pair(SDValue(), Chain);
  5133. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  5134. DAG.getVTList(&RetTys[0], RetTys.size()),
  5135. &ReturnValues[0], ReturnValues.size());
  5136. return std::make_pair(Res, Chain);
  5137. }
  5138. void TargetLowering::LowerOperationWrapper(SDNode *N,
  5139. SmallVectorImpl<SDValue> &Results,
  5140. SelectionDAG &DAG) {
  5141. SDValue Res = LowerOperation(SDValue(N, 0), DAG);
  5142. if (Res.getNode())
  5143. Results.push_back(Res);
  5144. }
  5145. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
  5146. llvm_unreachable("LowerOperation not implemented for this target!");
  5147. return SDValue();
  5148. }
  5149. void SelectionDAGBuilder::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
  5150. SDValue Op = getValue(V);
  5151. assert((Op.getOpcode() != ISD::CopyFromReg ||
  5152. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  5153. "Copy from a reg to the same reg!");
  5154. assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
  5155. RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
  5156. SDValue Chain = DAG.getEntryNode();
  5157. RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
  5158. PendingExports.push_back(Chain);
  5159. }
  5160. #include "llvm/CodeGen/SelectionDAGISel.h"
  5161. void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) {
  5162. // If this is the entry block, emit arguments.
  5163. Function &F = *LLVMBB->getParent();
  5164. SelectionDAG &DAG = SDB->DAG;
  5165. SDValue OldRoot = DAG.getRoot();
  5166. DebugLoc dl = SDB->getCurDebugLoc();
  5167. const TargetData *TD = TLI.getTargetData();
  5168. SmallVector<ISD::InputArg, 16> Ins;
  5169. // Check whether the function can return without sret-demotion.
  5170. SmallVector<EVT, 4> OutVTs;
  5171. SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
  5172. getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
  5173. OutVTs, OutsFlags, TLI);
  5174. FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
  5175. FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(),
  5176. OutVTs, OutsFlags, DAG);
  5177. if (!FLI.CanLowerReturn) {
  5178. // Put in an sret pointer parameter before all the other parameters.
  5179. SmallVector<EVT, 1> ValueVTs;
  5180. ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
  5181. // NOTE: Assuming that a pointer will never break down to more than one VT
  5182. // or one register.
  5183. ISD::ArgFlagsTy Flags;
  5184. Flags.setSRet();
  5185. EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]);
  5186. ISD::InputArg RetArg(Flags, RegisterVT, true);
  5187. Ins.push_back(RetArg);
  5188. }
  5189. // Set up the incoming argument description vector.
  5190. unsigned Idx = 1;
  5191. for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
  5192. I != E; ++I, ++Idx) {
  5193. SmallVector<EVT, 4> ValueVTs;
  5194. ComputeValueVTs(TLI, I->getType(), ValueVTs);
  5195. bool isArgValueUsed = !I->use_empty();
  5196. for (unsigned Value = 0, NumValues = ValueVTs.size();
  5197. Value != NumValues; ++Value) {
  5198. EVT VT = ValueVTs[Value];
  5199. const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  5200. ISD::ArgFlagsTy Flags;
  5201. unsigned OriginalAlignment =
  5202. TD->getABITypeAlignment(ArgTy);
  5203. if (F.paramHasAttr(Idx, Attribute::ZExt))
  5204. Flags.setZExt();
  5205. if (F.paramHasAttr(Idx, Attribute::SExt))
  5206. Flags.setSExt();
  5207. if (F.paramHasAttr(Idx, Attribute::InReg))
  5208. Flags.setInReg();
  5209. if (F.paramHasAttr(Idx, Attribute::StructRet))
  5210. Flags.setSRet();
  5211. if (F.paramHasAttr(Idx, Attribute::ByVal)) {
  5212. Flags.setByVal();
  5213. const PointerType *Ty = cast<PointerType>(I->getType());
  5214. const Type *ElementTy = Ty->getElementType();
  5215. unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
  5216. unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
  5217. // For ByVal, alignment should be passed from FE. BE will guess if
  5218. // this info is not there but there are cases it cannot get right.
  5219. if (F.getParamAlignment(Idx))
  5220. FrameAlign = F.getParamAlignment(Idx);
  5221. Flags.setByValAlign(FrameAlign);
  5222. Flags.setByValSize(FrameSize);
  5223. }
  5224. if (F.paramHasAttr(Idx, Attribute::Nest))
  5225. Flags.setNest();
  5226. Flags.setOrigAlign(OriginalAlignment);
  5227. EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
  5228. unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
  5229. for (unsigned i = 0; i != NumRegs; ++i) {
  5230. ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
  5231. if (NumRegs > 1 && i == 0)
  5232. MyFlags.Flags.setSplit();
  5233. // if it isn't first piece, alignment must be 1
  5234. else if (i > 0)
  5235. MyFlags.Flags.setOrigAlign(1);
  5236. Ins.push_back(MyFlags);
  5237. }
  5238. }
  5239. }
  5240. // Call the target to set up the argument values.
  5241. SmallVector<SDValue, 8> InVals;
  5242. SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
  5243. F.isVarArg(), Ins,
  5244. dl, DAG, InVals);
  5245. // Verify that the target's LowerFormalArguments behaved as expected.
  5246. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  5247. "LowerFormalArguments didn't return a valid chain!");
  5248. assert(InVals.size() == Ins.size() &&
  5249. "LowerFormalArguments didn't emit the correct number of values!");
  5250. DEBUG({
  5251. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  5252. assert(InVals[i].getNode() &&
  5253. "LowerFormalArguments emitted a null value!");
  5254. assert(Ins[i].VT == InVals[i].getValueType() &&
  5255. "LowerFormalArguments emitted a value with the wrong type!");
  5256. }
  5257. });
  5258. // Update the DAG with the new chain value resulting from argument lowering.
  5259. DAG.setRoot(NewRoot);
  5260. // Set up the argument values.
  5261. unsigned i = 0;
  5262. Idx = 1;
  5263. if (!FLI.CanLowerReturn) {
  5264. // Create a virtual register for the sret pointer, and put in a copy
  5265. // from the sret argument into it.
  5266. SmallVector<EVT, 1> ValueVTs;
  5267. ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
  5268. EVT VT = ValueVTs[0];
  5269. EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
  5270. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  5271. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
  5272. RegVT, VT, AssertOp);
  5273. MachineFunction& MF = SDB->DAG.getMachineFunction();
  5274. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  5275. unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
  5276. FLI.DemoteRegister = SRetReg;
  5277. NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
  5278. SRetReg, ArgValue);
  5279. DAG.setRoot(NewRoot);
  5280. // i indexes lowered arguments. Bump it past the hidden sret argument.
  5281. // Idx indexes LLVM arguments. Don't touch it.
  5282. ++i;
  5283. }
  5284. for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
  5285. ++I, ++Idx) {
  5286. SmallVector<SDValue, 4> ArgValues;
  5287. SmallVector<EVT, 4> ValueVTs;
  5288. ComputeValueVTs(TLI, I->getType(), ValueVTs);
  5289. unsigned NumValues = ValueVTs.size();
  5290. for (unsigned Value = 0; Value != NumValues; ++Value) {
  5291. EVT VT = ValueVTs[Value];
  5292. EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
  5293. unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
  5294. if (!I->use_empty()) {
  5295. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  5296. if (F.paramHasAttr(Idx, Attribute::SExt))
  5297. AssertOp = ISD::AssertSext;
  5298. else if (F.paramHasAttr(Idx, Attribute::ZExt))
  5299. AssertOp = ISD::AssertZext;
  5300. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
  5301. NumParts, PartVT, VT,
  5302. AssertOp));
  5303. }
  5304. i += NumParts;
  5305. }
  5306. if (!I->use_empty()) {
  5307. SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
  5308. SDB->getCurDebugLoc());
  5309. SDB->setValue(I, Res);
  5310. // If this argument is live outside of the entry block, insert a copy from
  5311. // whereever we got it to the vreg that other BB's will reference it as.
  5312. SDB->CopyToExportRegsIfNeeded(I);
  5313. }
  5314. }
  5315. assert(i == InVals.size() && "Argument register count mismatch!");
  5316. // Finally, if the target has anything special to do, allow it to do so.
  5317. // FIXME: this should insert code into the DAG!
  5318. EmitFunctionEntryCode(F, SDB->DAG.getMachineFunction());
  5319. }
  5320. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  5321. /// ensure constants are generated when needed. Remember the virtual registers
  5322. /// that need to be added to the Machine PHI nodes as input. We cannot just
  5323. /// directly add them, because expansion might result in multiple MBB's for one
  5324. /// BB. As such, the start of the BB might correspond to a different MBB than
  5325. /// the end.
  5326. ///
  5327. void
  5328. SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
  5329. TerminatorInst *TI = LLVMBB->getTerminator();
  5330. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  5331. // Check successor nodes' PHI nodes that expect a constant to be available
  5332. // from this block.
  5333. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  5334. BasicBlock *SuccBB = TI->getSuccessor(succ);
  5335. if (!isa<PHINode>(SuccBB->begin())) continue;
  5336. MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
  5337. // If this terminator has multiple identical successors (common for
  5338. // switches), only handle each succ once.
  5339. if (!SuccsHandled.insert(SuccMBB)) continue;
  5340. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  5341. PHINode *PN;
  5342. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  5343. // nodes and Machine PHI nodes, but the incoming operands have not been
  5344. // emitted yet.
  5345. for (BasicBlock::iterator I = SuccBB->begin();
  5346. (PN = dyn_cast<PHINode>(I)); ++I) {
  5347. // Ignore dead phi's.
  5348. if (PN->use_empty()) continue;
  5349. unsigned Reg;
  5350. Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
  5351. if (Constant *C = dyn_cast<Constant>(PHIOp)) {
  5352. unsigned &RegOut = SDB->ConstantsOut[C];
  5353. if (RegOut == 0) {
  5354. RegOut = FuncInfo->CreateRegForValue(C);
  5355. SDB->CopyValueToVirtualRegister(C, RegOut);
  5356. }
  5357. Reg = RegOut;
  5358. } else {
  5359. Reg = FuncInfo->ValueMap[PHIOp];
  5360. if (Reg == 0) {
  5361. assert(isa<AllocaInst>(PHIOp) &&
  5362. FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  5363. "Didn't codegen value into a register!??");
  5364. Reg = FuncInfo->CreateRegForValue(PHIOp);
  5365. SDB->CopyValueToVirtualRegister(PHIOp, Reg);
  5366. }
  5367. }
  5368. // Remember that this register needs to added to the machine PHI node as
  5369. // the input for this MBB.
  5370. SmallVector<EVT, 4> ValueVTs;
  5371. ComputeValueVTs(TLI, PN->getType(), ValueVTs);
  5372. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  5373. EVT VT = ValueVTs[vti];
  5374. unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
  5375. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  5376. SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
  5377. Reg += NumRegisters;
  5378. }
  5379. }
  5380. }
  5381. SDB->ConstantsOut.clear();
  5382. }
  5383. /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
  5384. /// supports legal types, and it emits MachineInstrs directly instead of
  5385. /// creating SelectionDAG nodes.
  5386. ///
  5387. bool
  5388. SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
  5389. FastISel *F) {
  5390. TerminatorInst *TI = LLVMBB->getTerminator();
  5391. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  5392. unsigned OrigNumPHINodesToUpdate = SDB->PHINodesToUpdate.size();
  5393. // Check successor nodes' PHI nodes that expect a constant to be available
  5394. // from this block.
  5395. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  5396. BasicBlock *SuccBB = TI->getSuccessor(succ);
  5397. if (!isa<PHINode>(SuccBB->begin())) continue;
  5398. MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
  5399. // If this terminator has multiple identical successors (common for
  5400. // switches), only handle each succ once.
  5401. if (!SuccsHandled.insert(SuccMBB)) continue;
  5402. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  5403. PHINode *PN;
  5404. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  5405. // nodes and Machine PHI nodes, but the incoming operands have not been
  5406. // emitted yet.
  5407. for (BasicBlock::iterator I = SuccBB->begin();
  5408. (PN = dyn_cast<PHINode>(I)); ++I) {
  5409. // Ignore dead phi's.
  5410. if (PN->use_empty()) continue;
  5411. // Only handle legal types. Two interesting things to note here. First,
  5412. // by bailing out early, we may leave behind some dead instructions,
  5413. // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
  5414. // own moves. Second, this check is necessary becuase FastISel doesn't
  5415. // use CreateRegForValue to create registers, so it always creates
  5416. // exactly one register for each non-void instruction.
  5417. EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
  5418. if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
  5419. // Promote MVT::i1.
  5420. if (VT == MVT::i1)
  5421. VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
  5422. else {
  5423. SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
  5424. return false;
  5425. }
  5426. }
  5427. Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
  5428. unsigned Reg = F->getRegForValue(PHIOp);
  5429. if (Reg == 0) {
  5430. SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
  5431. return false;
  5432. }
  5433. SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
  5434. }
  5435. }
  5436. return true;
  5437. }