SelectionDAGBuilder.cpp 301 KB

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