PPCISelLowering.cpp 723 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440
  1. //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the PPCISelLowering class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "PPCISelLowering.h"
  13. #include "MCTargetDesc/PPCPredicates.h"
  14. #include "PPC.h"
  15. #include "PPCCCState.h"
  16. #include "PPCCallingConv.h"
  17. #include "PPCFrameLowering.h"
  18. #include "PPCInstrInfo.h"
  19. #include "PPCMachineFunctionInfo.h"
  20. #include "PPCPerfectShuffle.h"
  21. #include "PPCRegisterInfo.h"
  22. #include "PPCSubtarget.h"
  23. #include "PPCTargetMachine.h"
  24. #include "llvm/ADT/APFloat.h"
  25. #include "llvm/ADT/APInt.h"
  26. #include "llvm/ADT/ArrayRef.h"
  27. #include "llvm/ADT/DenseMap.h"
  28. #include "llvm/ADT/STLExtras.h"
  29. #include "llvm/ADT/SmallPtrSet.h"
  30. #include "llvm/ADT/SmallSet.h"
  31. #include "llvm/ADT/SmallVector.h"
  32. #include "llvm/ADT/Statistic.h"
  33. #include "llvm/ADT/StringRef.h"
  34. #include "llvm/ADT/StringSwitch.h"
  35. #include "llvm/CodeGen/CallingConvLower.h"
  36. #include "llvm/CodeGen/ISDOpcodes.h"
  37. #include "llvm/CodeGen/MachineBasicBlock.h"
  38. #include "llvm/CodeGen/MachineFrameInfo.h"
  39. #include "llvm/CodeGen/MachineFunction.h"
  40. #include "llvm/CodeGen/MachineInstr.h"
  41. #include "llvm/CodeGen/MachineInstrBuilder.h"
  42. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  43. #include "llvm/CodeGen/MachineLoopInfo.h"
  44. #include "llvm/CodeGen/MachineMemOperand.h"
  45. #include "llvm/CodeGen/MachineModuleInfo.h"
  46. #include "llvm/CodeGen/MachineOperand.h"
  47. #include "llvm/CodeGen/MachineRegisterInfo.h"
  48. #include "llvm/CodeGen/RuntimeLibcalls.h"
  49. #include "llvm/CodeGen/SelectionDAG.h"
  50. #include "llvm/CodeGen/SelectionDAGNodes.h"
  51. #include "llvm/CodeGen/TargetInstrInfo.h"
  52. #include "llvm/CodeGen/TargetLowering.h"
  53. #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
  54. #include "llvm/CodeGen/TargetRegisterInfo.h"
  55. #include "llvm/CodeGen/ValueTypes.h"
  56. #include "llvm/IR/CallingConv.h"
  57. #include "llvm/IR/Constant.h"
  58. #include "llvm/IR/Constants.h"
  59. #include "llvm/IR/DataLayout.h"
  60. #include "llvm/IR/DebugLoc.h"
  61. #include "llvm/IR/DerivedTypes.h"
  62. #include "llvm/IR/Function.h"
  63. #include "llvm/IR/GlobalValue.h"
  64. #include "llvm/IR/IRBuilder.h"
  65. #include "llvm/IR/Instructions.h"
  66. #include "llvm/IR/Intrinsics.h"
  67. #include "llvm/IR/IntrinsicsPowerPC.h"
  68. #include "llvm/IR/Module.h"
  69. #include "llvm/IR/Type.h"
  70. #include "llvm/IR/Use.h"
  71. #include "llvm/IR/Value.h"
  72. #include "llvm/MC/MCContext.h"
  73. #include "llvm/MC/MCExpr.h"
  74. #include "llvm/MC/MCRegisterInfo.h"
  75. #include "llvm/MC/MCSectionXCOFF.h"
  76. #include "llvm/MC/MCSymbolXCOFF.h"
  77. #include "llvm/Support/AtomicOrdering.h"
  78. #include "llvm/Support/BranchProbability.h"
  79. #include "llvm/Support/Casting.h"
  80. #include "llvm/Support/CodeGen.h"
  81. #include "llvm/Support/CommandLine.h"
  82. #include "llvm/Support/Compiler.h"
  83. #include "llvm/Support/Debug.h"
  84. #include "llvm/Support/ErrorHandling.h"
  85. #include "llvm/Support/Format.h"
  86. #include "llvm/Support/KnownBits.h"
  87. #include "llvm/Support/MachineValueType.h"
  88. #include "llvm/Support/MathExtras.h"
  89. #include "llvm/Support/raw_ostream.h"
  90. #include "llvm/Target/TargetMachine.h"
  91. #include "llvm/Target/TargetOptions.h"
  92. #include <algorithm>
  93. #include <cassert>
  94. #include <cstdint>
  95. #include <iterator>
  96. #include <list>
  97. #include <optional>
  98. #include <utility>
  99. #include <vector>
  100. using namespace llvm;
  101. #define DEBUG_TYPE "ppc-lowering"
  102. static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
  103. cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
  104. static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
  105. cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
  106. static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
  107. cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
  108. static cl::opt<bool> DisableSCO("disable-ppc-sco",
  109. cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
  110. static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
  111. cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
  112. static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
  113. cl::desc("use absolute jump tables on ppc"), cl::Hidden);
  114. static cl::opt<bool> EnableQuadwordAtomics(
  115. "ppc-quadword-atomics",
  116. cl::desc("enable quadword lock-free atomic operations"), cl::init(false),
  117. cl::Hidden);
  118. static cl::opt<bool>
  119. DisablePerfectShuffle("ppc-disable-perfect-shuffle",
  120. cl::desc("disable vector permute decomposition"),
  121. cl::init(true), cl::Hidden);
  122. cl::opt<bool> DisableAutoPairedVecSt(
  123. "disable-auto-paired-vec-st",
  124. cl::desc("disable automatically generated 32byte paired vector stores"),
  125. cl::init(true), cl::Hidden);
  126. STATISTIC(NumTailCalls, "Number of tail calls");
  127. STATISTIC(NumSiblingCalls, "Number of sibling calls");
  128. STATISTIC(ShufflesHandledWithVPERM,
  129. "Number of shuffles lowered to a VPERM or XXPERM");
  130. STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
  131. static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
  132. static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
  133. static const char AIXSSPCanaryWordName[] = "__ssp_canary_word";
  134. // FIXME: Remove this once the bug has been fixed!
  135. extern cl::opt<bool> ANDIGlueBug;
  136. PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
  137. const PPCSubtarget &STI)
  138. : TargetLowering(TM), Subtarget(STI) {
  139. // Initialize map that relates the PPC addressing modes to the computed flags
  140. // of a load/store instruction. The map is used to determine the optimal
  141. // addressing mode when selecting load and stores.
  142. initializeAddrModeMap();
  143. // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
  144. // arguments are at least 4/8 bytes aligned.
  145. bool isPPC64 = Subtarget.isPPC64();
  146. setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
  147. // Set up the register classes.
  148. addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
  149. if (!useSoftFloat()) {
  150. if (hasSPE()) {
  151. addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
  152. // EFPU2 APU only supports f32
  153. if (!Subtarget.hasEFPU2())
  154. addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
  155. } else {
  156. addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
  157. addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
  158. }
  159. }
  160. // Match BITREVERSE to customized fast code sequence in the td file.
  161. setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
  162. setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
  163. // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
  164. setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
  165. // Custom lower inline assembly to check for special registers.
  166. setOperationAction(ISD::INLINEASM, MVT::Other, Custom);
  167. setOperationAction(ISD::INLINEASM_BR, MVT::Other, Custom);
  168. // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
  169. for (MVT VT : MVT::integer_valuetypes()) {
  170. setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
  171. setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
  172. }
  173. if (Subtarget.isISA3_0()) {
  174. setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
  175. setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
  176. setTruncStoreAction(MVT::f64, MVT::f16, Legal);
  177. setTruncStoreAction(MVT::f32, MVT::f16, Legal);
  178. } else {
  179. // No extending loads from f16 or HW conversions back and forth.
  180. setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
  181. setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
  182. setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
  183. setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
  184. setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
  185. setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
  186. setTruncStoreAction(MVT::f64, MVT::f16, Expand);
  187. setTruncStoreAction(MVT::f32, MVT::f16, Expand);
  188. }
  189. setTruncStoreAction(MVT::f64, MVT::f32, Expand);
  190. // PowerPC has pre-inc load and store's.
  191. setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
  192. setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
  193. setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
  194. setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
  195. setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
  196. setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
  197. setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
  198. setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
  199. setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
  200. setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
  201. if (!Subtarget.hasSPE()) {
  202. setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
  203. setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
  204. setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
  205. setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
  206. }
  207. // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
  208. const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
  209. for (MVT VT : ScalarIntVTs) {
  210. setOperationAction(ISD::ADDC, VT, Legal);
  211. setOperationAction(ISD::ADDE, VT, Legal);
  212. setOperationAction(ISD::SUBC, VT, Legal);
  213. setOperationAction(ISD::SUBE, VT, Legal);
  214. }
  215. if (Subtarget.useCRBits()) {
  216. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
  217. if (isPPC64 || Subtarget.hasFPCVT()) {
  218. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote);
  219. AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1,
  220. isPPC64 ? MVT::i64 : MVT::i32);
  221. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote);
  222. AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1,
  223. isPPC64 ? MVT::i64 : MVT::i32);
  224. setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
  225. AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
  226. isPPC64 ? MVT::i64 : MVT::i32);
  227. setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
  228. AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
  229. isPPC64 ? MVT::i64 : MVT::i32);
  230. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote);
  231. AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1,
  232. isPPC64 ? MVT::i64 : MVT::i32);
  233. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote);
  234. AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1,
  235. isPPC64 ? MVT::i64 : MVT::i32);
  236. setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
  237. AddPromotedToType(ISD::FP_TO_SINT, MVT::i1,
  238. isPPC64 ? MVT::i64 : MVT::i32);
  239. setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
  240. AddPromotedToType(ISD::FP_TO_UINT, MVT::i1,
  241. isPPC64 ? MVT::i64 : MVT::i32);
  242. } else {
  243. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom);
  244. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom);
  245. setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
  246. setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
  247. }
  248. // PowerPC does not support direct load/store of condition registers.
  249. setOperationAction(ISD::LOAD, MVT::i1, Custom);
  250. setOperationAction(ISD::STORE, MVT::i1, Custom);
  251. // FIXME: Remove this once the ANDI glue bug is fixed:
  252. if (ANDIGlueBug)
  253. setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
  254. for (MVT VT : MVT::integer_valuetypes()) {
  255. setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
  256. setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
  257. setTruncStoreAction(VT, MVT::i1, Expand);
  258. }
  259. addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
  260. }
  261. // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
  262. // PPC (the libcall is not available).
  263. setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
  264. setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
  265. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom);
  266. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom);
  267. // We do not currently implement these libm ops for PowerPC.
  268. setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
  269. setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
  270. setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
  271. setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
  272. setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
  273. setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
  274. // PowerPC has no SREM/UREM instructions unless we are on P9
  275. // On P9 we may use a hardware instruction to compute the remainder.
  276. // When the result of both the remainder and the division is required it is
  277. // more efficient to compute the remainder from the result of the division
  278. // rather than use the remainder instruction. The instructions are legalized
  279. // directly because the DivRemPairsPass performs the transformation at the IR
  280. // level.
  281. if (Subtarget.isISA3_0()) {
  282. setOperationAction(ISD::SREM, MVT::i32, Legal);
  283. setOperationAction(ISD::UREM, MVT::i32, Legal);
  284. setOperationAction(ISD::SREM, MVT::i64, Legal);
  285. setOperationAction(ISD::UREM, MVT::i64, Legal);
  286. } else {
  287. setOperationAction(ISD::SREM, MVT::i32, Expand);
  288. setOperationAction(ISD::UREM, MVT::i32, Expand);
  289. setOperationAction(ISD::SREM, MVT::i64, Expand);
  290. setOperationAction(ISD::UREM, MVT::i64, Expand);
  291. }
  292. // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
  293. setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
  294. setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
  295. setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
  296. setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
  297. setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
  298. setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
  299. setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
  300. setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
  301. // Handle constrained floating-point operations of scalar.
  302. // TODO: Handle SPE specific operation.
  303. setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
  304. setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
  305. setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
  306. setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
  307. setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
  308. setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
  309. setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
  310. setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
  311. setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
  312. if (!Subtarget.hasSPE()) {
  313. setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
  314. setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
  315. }
  316. if (Subtarget.hasVSX()) {
  317. setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal);
  318. setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal);
  319. }
  320. if (Subtarget.hasFSQRT()) {
  321. setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
  322. setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
  323. }
  324. if (Subtarget.hasFPRND()) {
  325. setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
  326. setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal);
  327. setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
  328. setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
  329. setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
  330. setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal);
  331. setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
  332. setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
  333. }
  334. // We don't support sin/cos/sqrt/fmod/pow
  335. setOperationAction(ISD::FSIN , MVT::f64, Expand);
  336. setOperationAction(ISD::FCOS , MVT::f64, Expand);
  337. setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
  338. setOperationAction(ISD::FREM , MVT::f64, Expand);
  339. setOperationAction(ISD::FPOW , MVT::f64, Expand);
  340. setOperationAction(ISD::FSIN , MVT::f32, Expand);
  341. setOperationAction(ISD::FCOS , MVT::f32, Expand);
  342. setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
  343. setOperationAction(ISD::FREM , MVT::f32, Expand);
  344. setOperationAction(ISD::FPOW , MVT::f32, Expand);
  345. // MASS transformation for LLVM intrinsics with replicating fast-math flag
  346. // to be consistent to PPCGenScalarMASSEntries pass
  347. if (TM.getOptLevel() == CodeGenOpt::Aggressive) {
  348. setOperationAction(ISD::FSIN , MVT::f64, Custom);
  349. setOperationAction(ISD::FCOS , MVT::f64, Custom);
  350. setOperationAction(ISD::FPOW , MVT::f64, Custom);
  351. setOperationAction(ISD::FLOG, MVT::f64, Custom);
  352. setOperationAction(ISD::FLOG10, MVT::f64, Custom);
  353. setOperationAction(ISD::FEXP, MVT::f64, Custom);
  354. setOperationAction(ISD::FSIN , MVT::f32, Custom);
  355. setOperationAction(ISD::FCOS , MVT::f32, Custom);
  356. setOperationAction(ISD::FPOW , MVT::f32, Custom);
  357. setOperationAction(ISD::FLOG, MVT::f32, Custom);
  358. setOperationAction(ISD::FLOG10, MVT::f32, Custom);
  359. setOperationAction(ISD::FEXP, MVT::f32, Custom);
  360. }
  361. if (Subtarget.hasSPE()) {
  362. setOperationAction(ISD::FMA , MVT::f64, Expand);
  363. setOperationAction(ISD::FMA , MVT::f32, Expand);
  364. } else {
  365. setOperationAction(ISD::FMA , MVT::f64, Legal);
  366. setOperationAction(ISD::FMA , MVT::f32, Legal);
  367. }
  368. if (Subtarget.hasSPE())
  369. setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
  370. setOperationAction(ISD::GET_ROUNDING, MVT::i32, Custom);
  371. // If we're enabling GP optimizations, use hardware square root
  372. if (!Subtarget.hasFSQRT() &&
  373. !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
  374. Subtarget.hasFRE()))
  375. setOperationAction(ISD::FSQRT, MVT::f64, Expand);
  376. if (!Subtarget.hasFSQRT() &&
  377. !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
  378. Subtarget.hasFRES()))
  379. setOperationAction(ISD::FSQRT, MVT::f32, Expand);
  380. if (Subtarget.hasFCPSGN()) {
  381. setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
  382. setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
  383. } else {
  384. setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
  385. setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
  386. }
  387. if (Subtarget.hasFPRND()) {
  388. setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
  389. setOperationAction(ISD::FCEIL, MVT::f64, Legal);
  390. setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
  391. setOperationAction(ISD::FROUND, MVT::f64, Legal);
  392. setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
  393. setOperationAction(ISD::FCEIL, MVT::f32, Legal);
  394. setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
  395. setOperationAction(ISD::FROUND, MVT::f32, Legal);
  396. }
  397. // Prior to P10, PowerPC does not have BSWAP, but we can use vector BSWAP
  398. // instruction xxbrd to speed up scalar BSWAP64.
  399. if (Subtarget.isISA3_1()) {
  400. setOperationAction(ISD::BSWAP, MVT::i32, Legal);
  401. setOperationAction(ISD::BSWAP, MVT::i64, Legal);
  402. } else {
  403. setOperationAction(ISD::BSWAP, MVT::i32, Expand);
  404. setOperationAction(
  405. ISD::BSWAP, MVT::i64,
  406. (Subtarget.hasP9Vector() && Subtarget.isPPC64()) ? Custom : Expand);
  407. }
  408. // CTPOP or CTTZ were introduced in P8/P9 respectively
  409. if (Subtarget.isISA3_0()) {
  410. setOperationAction(ISD::CTTZ , MVT::i32 , Legal);
  411. setOperationAction(ISD::CTTZ , MVT::i64 , Legal);
  412. } else {
  413. setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
  414. setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
  415. }
  416. if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
  417. setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
  418. setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
  419. } else {
  420. setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
  421. setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
  422. }
  423. // PowerPC does not have ROTR
  424. setOperationAction(ISD::ROTR, MVT::i32 , Expand);
  425. setOperationAction(ISD::ROTR, MVT::i64 , Expand);
  426. if (!Subtarget.useCRBits()) {
  427. // PowerPC does not have Select
  428. setOperationAction(ISD::SELECT, MVT::i32, Expand);
  429. setOperationAction(ISD::SELECT, MVT::i64, Expand);
  430. setOperationAction(ISD::SELECT, MVT::f32, Expand);
  431. setOperationAction(ISD::SELECT, MVT::f64, Expand);
  432. }
  433. // PowerPC wants to turn select_cc of FP into fsel when possible.
  434. setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
  435. setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
  436. // PowerPC wants to optimize integer setcc a bit
  437. if (!Subtarget.useCRBits())
  438. setOperationAction(ISD::SETCC, MVT::i32, Custom);
  439. if (Subtarget.hasFPU()) {
  440. setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
  441. setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
  442. setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
  443. setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
  444. setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
  445. setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
  446. }
  447. // PowerPC does not have BRCOND which requires SetCC
  448. if (!Subtarget.useCRBits())
  449. setOperationAction(ISD::BRCOND, MVT::Other, Expand);
  450. setOperationAction(ISD::BR_JT, MVT::Other, Expand);
  451. if (Subtarget.hasSPE()) {
  452. // SPE has built-in conversions
  453. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
  454. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
  455. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
  456. setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
  457. setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
  458. setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
  459. // SPE supports signaling compare of f32/f64.
  460. setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
  461. setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
  462. } else {
  463. // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
  464. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
  465. setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
  466. // PowerPC does not have [U|S]INT_TO_FP
  467. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
  468. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
  469. setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
  470. setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
  471. }
  472. if (Subtarget.hasDirectMove() && isPPC64) {
  473. setOperationAction(ISD::BITCAST, MVT::f32, Legal);
  474. setOperationAction(ISD::BITCAST, MVT::i32, Legal);
  475. setOperationAction(ISD::BITCAST, MVT::i64, Legal);
  476. setOperationAction(ISD::BITCAST, MVT::f64, Legal);
  477. if (TM.Options.UnsafeFPMath) {
  478. setOperationAction(ISD::LRINT, MVT::f64, Legal);
  479. setOperationAction(ISD::LRINT, MVT::f32, Legal);
  480. setOperationAction(ISD::LLRINT, MVT::f64, Legal);
  481. setOperationAction(ISD::LLRINT, MVT::f32, Legal);
  482. setOperationAction(ISD::LROUND, MVT::f64, Legal);
  483. setOperationAction(ISD::LROUND, MVT::f32, Legal);
  484. setOperationAction(ISD::LLROUND, MVT::f64, Legal);
  485. setOperationAction(ISD::LLROUND, MVT::f32, Legal);
  486. }
  487. } else {
  488. setOperationAction(ISD::BITCAST, MVT::f32, Expand);
  489. setOperationAction(ISD::BITCAST, MVT::i32, Expand);
  490. setOperationAction(ISD::BITCAST, MVT::i64, Expand);
  491. setOperationAction(ISD::BITCAST, MVT::f64, Expand);
  492. }
  493. // We cannot sextinreg(i1). Expand to shifts.
  494. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
  495. // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
  496. // SjLj exception handling but a light-weight setjmp/longjmp replacement to
  497. // support continuation, user-level threading, and etc.. As a result, no
  498. // other SjLj exception interfaces are implemented and please don't build
  499. // your own exception handling based on them.
  500. // LLVM/Clang supports zero-cost DWARF exception handling.
  501. setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
  502. setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
  503. // We want to legalize GlobalAddress and ConstantPool nodes into the
  504. // appropriate instructions to materialize the address.
  505. setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
  506. setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
  507. setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
  508. setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
  509. setOperationAction(ISD::JumpTable, MVT::i32, Custom);
  510. setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
  511. setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
  512. setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
  513. setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
  514. setOperationAction(ISD::JumpTable, MVT::i64, Custom);
  515. // TRAP is legal.
  516. setOperationAction(ISD::TRAP, MVT::Other, Legal);
  517. // TRAMPOLINE is custom lowered.
  518. setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
  519. setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
  520. // VASTART needs to be custom lowered to use the VarArgsFrameIndex
  521. setOperationAction(ISD::VASTART , MVT::Other, Custom);
  522. if (Subtarget.is64BitELFABI()) {
  523. // VAARG always uses double-word chunks, so promote anything smaller.
  524. setOperationAction(ISD::VAARG, MVT::i1, Promote);
  525. AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
  526. setOperationAction(ISD::VAARG, MVT::i8, Promote);
  527. AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
  528. setOperationAction(ISD::VAARG, MVT::i16, Promote);
  529. AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
  530. setOperationAction(ISD::VAARG, MVT::i32, Promote);
  531. AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
  532. setOperationAction(ISD::VAARG, MVT::Other, Expand);
  533. } else if (Subtarget.is32BitELFABI()) {
  534. // VAARG is custom lowered with the 32-bit SVR4 ABI.
  535. setOperationAction(ISD::VAARG, MVT::Other, Custom);
  536. setOperationAction(ISD::VAARG, MVT::i64, Custom);
  537. } else
  538. setOperationAction(ISD::VAARG, MVT::Other, Expand);
  539. // VACOPY is custom lowered with the 32-bit SVR4 ABI.
  540. if (Subtarget.is32BitELFABI())
  541. setOperationAction(ISD::VACOPY , MVT::Other, Custom);
  542. else
  543. setOperationAction(ISD::VACOPY , MVT::Other, Expand);
  544. // Use the default implementation.
  545. setOperationAction(ISD::VAEND , MVT::Other, Expand);
  546. setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
  547. setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
  548. setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
  549. setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
  550. setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
  551. setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
  552. setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
  553. setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
  554. // We want to custom lower some of our intrinsics.
  555. setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
  556. setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f64, Custom);
  557. setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::ppcf128, Custom);
  558. setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
  559. setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f64, Custom);
  560. // To handle counter-based loop conditions.
  561. setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
  562. setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
  563. setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
  564. setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
  565. setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
  566. // Comparisons that require checking two conditions.
  567. if (Subtarget.hasSPE()) {
  568. setCondCodeAction(ISD::SETO, MVT::f32, Expand);
  569. setCondCodeAction(ISD::SETO, MVT::f64, Expand);
  570. setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
  571. setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
  572. }
  573. setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
  574. setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
  575. setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
  576. setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
  577. setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
  578. setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
  579. setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
  580. setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
  581. setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
  582. setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
  583. setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
  584. setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
  585. setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
  586. setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
  587. if (Subtarget.has64BitSupport()) {
  588. // They also have instructions for converting between i64 and fp.
  589. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
  590. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
  591. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
  592. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
  593. setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
  594. setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
  595. setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
  596. setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
  597. // This is just the low 32 bits of a (signed) fp->i64 conversion.
  598. // We cannot do this with Promote because i64 is not a legal type.
  599. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
  600. setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
  601. if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
  602. setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
  603. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
  604. }
  605. } else {
  606. // PowerPC does not have FP_TO_UINT on 32-bit implementations.
  607. if (Subtarget.hasSPE()) {
  608. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
  609. setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
  610. } else {
  611. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
  612. setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
  613. }
  614. }
  615. // With the instructions enabled under FPCVT, we can do everything.
  616. if (Subtarget.hasFPCVT()) {
  617. if (Subtarget.has64BitSupport()) {
  618. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
  619. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
  620. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
  621. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
  622. setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
  623. setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
  624. setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
  625. setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
  626. }
  627. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
  628. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
  629. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
  630. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
  631. setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
  632. setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
  633. setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
  634. setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
  635. }
  636. if (Subtarget.use64BitRegs()) {
  637. // 64-bit PowerPC implementations can support i64 types directly
  638. addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
  639. // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
  640. setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
  641. // 64-bit PowerPC wants to expand i128 shifts itself.
  642. setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
  643. setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
  644. setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
  645. } else {
  646. // 32-bit PowerPC wants to expand i64 shifts itself.
  647. setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
  648. setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
  649. setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
  650. }
  651. // PowerPC has better expansions for funnel shifts than the generic
  652. // TargetLowering::expandFunnelShift.
  653. if (Subtarget.has64BitSupport()) {
  654. setOperationAction(ISD::FSHL, MVT::i64, Custom);
  655. setOperationAction(ISD::FSHR, MVT::i64, Custom);
  656. }
  657. setOperationAction(ISD::FSHL, MVT::i32, Custom);
  658. setOperationAction(ISD::FSHR, MVT::i32, Custom);
  659. if (Subtarget.hasVSX()) {
  660. setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
  661. setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
  662. setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
  663. setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
  664. }
  665. if (Subtarget.hasAltivec()) {
  666. for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
  667. setOperationAction(ISD::SADDSAT, VT, Legal);
  668. setOperationAction(ISD::SSUBSAT, VT, Legal);
  669. setOperationAction(ISD::UADDSAT, VT, Legal);
  670. setOperationAction(ISD::USUBSAT, VT, Legal);
  671. }
  672. // First set operation action for all vector types to expand. Then we
  673. // will selectively turn on ones that can be effectively codegen'd.
  674. for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
  675. // add/sub are legal for all supported vector VT's.
  676. setOperationAction(ISD::ADD, VT, Legal);
  677. setOperationAction(ISD::SUB, VT, Legal);
  678. // For v2i64, these are only valid with P8Vector. This is corrected after
  679. // the loop.
  680. if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
  681. setOperationAction(ISD::SMAX, VT, Legal);
  682. setOperationAction(ISD::SMIN, VT, Legal);
  683. setOperationAction(ISD::UMAX, VT, Legal);
  684. setOperationAction(ISD::UMIN, VT, Legal);
  685. }
  686. else {
  687. setOperationAction(ISD::SMAX, VT, Expand);
  688. setOperationAction(ISD::SMIN, VT, Expand);
  689. setOperationAction(ISD::UMAX, VT, Expand);
  690. setOperationAction(ISD::UMIN, VT, Expand);
  691. }
  692. if (Subtarget.hasVSX()) {
  693. setOperationAction(ISD::FMAXNUM, VT, Legal);
  694. setOperationAction(ISD::FMINNUM, VT, Legal);
  695. }
  696. // Vector instructions introduced in P8
  697. if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
  698. setOperationAction(ISD::CTPOP, VT, Legal);
  699. setOperationAction(ISD::CTLZ, VT, Legal);
  700. }
  701. else {
  702. setOperationAction(ISD::CTPOP, VT, Expand);
  703. setOperationAction(ISD::CTLZ, VT, Expand);
  704. }
  705. // Vector instructions introduced in P9
  706. if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
  707. setOperationAction(ISD::CTTZ, VT, Legal);
  708. else
  709. setOperationAction(ISD::CTTZ, VT, Expand);
  710. // We promote all shuffles to v16i8.
  711. setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
  712. AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
  713. // We promote all non-typed operations to v4i32.
  714. setOperationAction(ISD::AND , VT, Promote);
  715. AddPromotedToType (ISD::AND , VT, MVT::v4i32);
  716. setOperationAction(ISD::OR , VT, Promote);
  717. AddPromotedToType (ISD::OR , VT, MVT::v4i32);
  718. setOperationAction(ISD::XOR , VT, Promote);
  719. AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
  720. setOperationAction(ISD::LOAD , VT, Promote);
  721. AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
  722. setOperationAction(ISD::SELECT, VT, Promote);
  723. AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
  724. setOperationAction(ISD::VSELECT, VT, Legal);
  725. setOperationAction(ISD::SELECT_CC, VT, Promote);
  726. AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
  727. setOperationAction(ISD::STORE, VT, Promote);
  728. AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
  729. // No other operations are legal.
  730. setOperationAction(ISD::MUL , VT, Expand);
  731. setOperationAction(ISD::SDIV, VT, Expand);
  732. setOperationAction(ISD::SREM, VT, Expand);
  733. setOperationAction(ISD::UDIV, VT, Expand);
  734. setOperationAction(ISD::UREM, VT, Expand);
  735. setOperationAction(ISD::FDIV, VT, Expand);
  736. setOperationAction(ISD::FREM, VT, Expand);
  737. setOperationAction(ISD::FNEG, VT, Expand);
  738. setOperationAction(ISD::FSQRT, VT, Expand);
  739. setOperationAction(ISD::FLOG, VT, Expand);
  740. setOperationAction(ISD::FLOG10, VT, Expand);
  741. setOperationAction(ISD::FLOG2, VT, Expand);
  742. setOperationAction(ISD::FEXP, VT, Expand);
  743. setOperationAction(ISD::FEXP2, VT, Expand);
  744. setOperationAction(ISD::FSIN, VT, Expand);
  745. setOperationAction(ISD::FCOS, VT, Expand);
  746. setOperationAction(ISD::FABS, VT, Expand);
  747. setOperationAction(ISD::FFLOOR, VT, Expand);
  748. setOperationAction(ISD::FCEIL, VT, Expand);
  749. setOperationAction(ISD::FTRUNC, VT, Expand);
  750. setOperationAction(ISD::FRINT, VT, Expand);
  751. setOperationAction(ISD::FNEARBYINT, VT, Expand);
  752. setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
  753. setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
  754. setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
  755. setOperationAction(ISD::MULHU, VT, Expand);
  756. setOperationAction(ISD::MULHS, VT, Expand);
  757. setOperationAction(ISD::UMUL_LOHI, VT, Expand);
  758. setOperationAction(ISD::SMUL_LOHI, VT, Expand);
  759. setOperationAction(ISD::UDIVREM, VT, Expand);
  760. setOperationAction(ISD::SDIVREM, VT, Expand);
  761. setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
  762. setOperationAction(ISD::FPOW, VT, Expand);
  763. setOperationAction(ISD::BSWAP, VT, Expand);
  764. setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
  765. setOperationAction(ISD::ROTL, VT, Expand);
  766. setOperationAction(ISD::ROTR, VT, Expand);
  767. for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
  768. setTruncStoreAction(VT, InnerVT, Expand);
  769. setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
  770. setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
  771. setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
  772. }
  773. }
  774. setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
  775. if (!Subtarget.hasP8Vector()) {
  776. setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
  777. setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
  778. setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
  779. setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
  780. }
  781. // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
  782. // with merges, splats, etc.
  783. setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
  784. // Vector truncates to sub-word integer that fit in an Altivec/VSX register
  785. // are cheap, so handle them before they get expanded to scalar.
  786. setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
  787. setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
  788. setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
  789. setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
  790. setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
  791. setOperationAction(ISD::AND , MVT::v4i32, Legal);
  792. setOperationAction(ISD::OR , MVT::v4i32, Legal);
  793. setOperationAction(ISD::XOR , MVT::v4i32, Legal);
  794. setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
  795. setOperationAction(ISD::SELECT, MVT::v4i32,
  796. Subtarget.useCRBits() ? Legal : Expand);
  797. setOperationAction(ISD::STORE , MVT::v4i32, Legal);
  798. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
  799. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
  800. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
  801. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
  802. setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
  803. setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
  804. setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
  805. setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
  806. setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
  807. setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
  808. setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
  809. setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
  810. // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
  811. setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
  812. // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
  813. if (Subtarget.hasAltivec())
  814. for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
  815. setOperationAction(ISD::ROTL, VT, Legal);
  816. // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
  817. if (Subtarget.hasP8Altivec())
  818. setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
  819. addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
  820. addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
  821. addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
  822. addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
  823. setOperationAction(ISD::MUL, MVT::v4f32, Legal);
  824. setOperationAction(ISD::FMA, MVT::v4f32, Legal);
  825. if (Subtarget.hasVSX()) {
  826. setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
  827. setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
  828. setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
  829. }
  830. if (Subtarget.hasP8Altivec())
  831. setOperationAction(ISD::MUL, MVT::v4i32, Legal);
  832. else
  833. setOperationAction(ISD::MUL, MVT::v4i32, Custom);
  834. if (Subtarget.isISA3_1()) {
  835. setOperationAction(ISD::MUL, MVT::v2i64, Legal);
  836. setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
  837. setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
  838. setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
  839. setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
  840. setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
  841. setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
  842. setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
  843. setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
  844. setOperationAction(ISD::UREM, MVT::v2i64, Legal);
  845. setOperationAction(ISD::SREM, MVT::v2i64, Legal);
  846. setOperationAction(ISD::UREM, MVT::v4i32, Legal);
  847. setOperationAction(ISD::SREM, MVT::v4i32, Legal);
  848. setOperationAction(ISD::UREM, MVT::v1i128, Legal);
  849. setOperationAction(ISD::SREM, MVT::v1i128, Legal);
  850. setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
  851. setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
  852. setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
  853. }
  854. setOperationAction(ISD::MUL, MVT::v8i16, Legal);
  855. setOperationAction(ISD::MUL, MVT::v16i8, Custom);
  856. setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
  857. setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
  858. setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
  859. setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
  860. setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
  861. setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
  862. // Altivec does not contain unordered floating-point compare instructions
  863. setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
  864. setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
  865. setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
  866. setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
  867. if (Subtarget.hasVSX()) {
  868. setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
  869. setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
  870. if (Subtarget.hasP8Vector()) {
  871. setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
  872. setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
  873. }
  874. if (Subtarget.hasDirectMove() && isPPC64) {
  875. setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
  876. setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
  877. setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
  878. setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
  879. setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
  880. setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
  881. setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
  882. setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
  883. }
  884. setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
  885. // The nearbyint variants are not allowed to raise the inexact exception
  886. // so we can only code-gen them with unsafe math.
  887. if (TM.Options.UnsafeFPMath) {
  888. setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
  889. setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
  890. }
  891. setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
  892. setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
  893. setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
  894. setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
  895. setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
  896. setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
  897. setOperationAction(ISD::FROUND, MVT::f64, Legal);
  898. setOperationAction(ISD::FRINT, MVT::f64, Legal);
  899. setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
  900. setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
  901. setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
  902. setOperationAction(ISD::FROUND, MVT::f32, Legal);
  903. setOperationAction(ISD::FRINT, MVT::f32, Legal);
  904. setOperationAction(ISD::MUL, MVT::v2f64, Legal);
  905. setOperationAction(ISD::FMA, MVT::v2f64, Legal);
  906. setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
  907. setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
  908. // Share the Altivec comparison restrictions.
  909. setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
  910. setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
  911. setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
  912. setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
  913. setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
  914. setOperationAction(ISD::STORE, MVT::v2f64, Legal);
  915. setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
  916. if (Subtarget.hasP8Vector())
  917. addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
  918. addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
  919. addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
  920. addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
  921. addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
  922. if (Subtarget.hasP8Altivec()) {
  923. setOperationAction(ISD::SHL, MVT::v2i64, Legal);
  924. setOperationAction(ISD::SRA, MVT::v2i64, Legal);
  925. setOperationAction(ISD::SRL, MVT::v2i64, Legal);
  926. // 128 bit shifts can be accomplished via 3 instructions for SHL and
  927. // SRL, but not for SRA because of the instructions available:
  928. // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
  929. // doing
  930. setOperationAction(ISD::SHL, MVT::v1i128, Expand);
  931. setOperationAction(ISD::SRL, MVT::v1i128, Expand);
  932. setOperationAction(ISD::SRA, MVT::v1i128, Expand);
  933. setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
  934. }
  935. else {
  936. setOperationAction(ISD::SHL, MVT::v2i64, Expand);
  937. setOperationAction(ISD::SRA, MVT::v2i64, Expand);
  938. setOperationAction(ISD::SRL, MVT::v2i64, Expand);
  939. setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
  940. // VSX v2i64 only supports non-arithmetic operations.
  941. setOperationAction(ISD::ADD, MVT::v2i64, Expand);
  942. setOperationAction(ISD::SUB, MVT::v2i64, Expand);
  943. }
  944. if (Subtarget.isISA3_1())
  945. setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
  946. else
  947. setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
  948. setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
  949. AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
  950. setOperationAction(ISD::STORE, MVT::v2i64, Promote);
  951. AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
  952. setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
  953. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
  954. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
  955. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
  956. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
  957. setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
  958. setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
  959. setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
  960. setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
  961. // Custom handling for partial vectors of integers converted to
  962. // floating point. We already have optimal handling for v2i32 through
  963. // the DAG combine, so those aren't necessary.
  964. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
  965. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
  966. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
  967. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
  968. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
  969. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
  970. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
  971. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
  972. setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
  973. setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
  974. setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
  975. setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
  976. setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
  977. setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
  978. setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
  979. setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
  980. setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
  981. setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
  982. setOperationAction(ISD::FABS, MVT::v4f32, Legal);
  983. setOperationAction(ISD::FABS, MVT::v2f64, Legal);
  984. setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
  985. setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
  986. setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
  987. setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
  988. // Handle constrained floating-point operations of vector.
  989. // The predictor is `hasVSX` because altivec instruction has
  990. // no exception but VSX vector instruction has.
  991. setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
  992. setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
  993. setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
  994. setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
  995. setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
  996. setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
  997. setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
  998. setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
  999. setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
  1000. setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
  1001. setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal);
  1002. setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
  1003. setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
  1004. setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
  1005. setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
  1006. setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
  1007. setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
  1008. setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
  1009. setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
  1010. setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
  1011. setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
  1012. setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
  1013. setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
  1014. setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal);
  1015. setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
  1016. setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
  1017. addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
  1018. addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
  1019. for (MVT FPT : MVT::fp_valuetypes())
  1020. setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
  1021. // Expand the SELECT to SELECT_CC
  1022. setOperationAction(ISD::SELECT, MVT::f128, Expand);
  1023. setTruncStoreAction(MVT::f128, MVT::f64, Expand);
  1024. setTruncStoreAction(MVT::f128, MVT::f32, Expand);
  1025. // No implementation for these ops for PowerPC.
  1026. setOperationAction(ISD::FSIN, MVT::f128, Expand);
  1027. setOperationAction(ISD::FCOS, MVT::f128, Expand);
  1028. setOperationAction(ISD::FPOW, MVT::f128, Expand);
  1029. setOperationAction(ISD::FPOWI, MVT::f128, Expand);
  1030. setOperationAction(ISD::FREM, MVT::f128, Expand);
  1031. }
  1032. if (Subtarget.hasP8Altivec()) {
  1033. addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
  1034. addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
  1035. }
  1036. if (Subtarget.hasP9Vector()) {
  1037. setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
  1038. setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
  1039. // 128 bit shifts can be accomplished via 3 instructions for SHL and
  1040. // SRL, but not for SRA because of the instructions available:
  1041. // VS{RL} and VS{RL}O.
  1042. setOperationAction(ISD::SHL, MVT::v1i128, Legal);
  1043. setOperationAction(ISD::SRL, MVT::v1i128, Legal);
  1044. setOperationAction(ISD::SRA, MVT::v1i128, Expand);
  1045. setOperationAction(ISD::FADD, MVT::f128, Legal);
  1046. setOperationAction(ISD::FSUB, MVT::f128, Legal);
  1047. setOperationAction(ISD::FDIV, MVT::f128, Legal);
  1048. setOperationAction(ISD::FMUL, MVT::f128, Legal);
  1049. setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
  1050. setOperationAction(ISD::FMA, MVT::f128, Legal);
  1051. setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
  1052. setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
  1053. setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
  1054. setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
  1055. setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
  1056. setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
  1057. setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
  1058. setOperationAction(ISD::FRINT, MVT::f128, Legal);
  1059. setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
  1060. setOperationAction(ISD::FCEIL, MVT::f128, Legal);
  1061. setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
  1062. setOperationAction(ISD::FROUND, MVT::f128, Legal);
  1063. setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
  1064. setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
  1065. setOperationAction(ISD::BITCAST, MVT::i128, Custom);
  1066. // Handle constrained floating-point operations of fp128
  1067. setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
  1068. setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
  1069. setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
  1070. setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
  1071. setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
  1072. setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
  1073. setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
  1074. setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
  1075. setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
  1076. setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
  1077. setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
  1078. setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
  1079. setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
  1080. setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
  1081. setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
  1082. setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
  1083. setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
  1084. setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
  1085. setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
  1086. setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
  1087. } else if (Subtarget.hasVSX()) {
  1088. setOperationAction(ISD::LOAD, MVT::f128, Promote);
  1089. setOperationAction(ISD::STORE, MVT::f128, Promote);
  1090. AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
  1091. AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
  1092. // Set FADD/FSUB as libcall to avoid the legalizer to expand the
  1093. // fp_to_uint and int_to_fp.
  1094. setOperationAction(ISD::FADD, MVT::f128, LibCall);
  1095. setOperationAction(ISD::FSUB, MVT::f128, LibCall);
  1096. setOperationAction(ISD::FMUL, MVT::f128, Expand);
  1097. setOperationAction(ISD::FDIV, MVT::f128, Expand);
  1098. setOperationAction(ISD::FNEG, MVT::f128, Expand);
  1099. setOperationAction(ISD::FABS, MVT::f128, Expand);
  1100. setOperationAction(ISD::FSQRT, MVT::f128, Expand);
  1101. setOperationAction(ISD::FMA, MVT::f128, Expand);
  1102. setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
  1103. // Expand the fp_extend if the target type is fp128.
  1104. setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand);
  1105. setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand);
  1106. // Expand the fp_round if the source type is fp128.
  1107. for (MVT VT : {MVT::f32, MVT::f64}) {
  1108. setOperationAction(ISD::FP_ROUND, VT, Custom);
  1109. setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom);
  1110. }
  1111. setOperationAction(ISD::SETCC, MVT::f128, Custom);
  1112. setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
  1113. setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
  1114. setOperationAction(ISD::BR_CC, MVT::f128, Expand);
  1115. // Lower following f128 select_cc pattern:
  1116. // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
  1117. setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
  1118. // We need to handle f128 SELECT_CC with integer result type.
  1119. setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
  1120. setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand);
  1121. }
  1122. if (Subtarget.hasP9Altivec()) {
  1123. if (Subtarget.isISA3_1()) {
  1124. setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
  1125. setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Legal);
  1126. setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Legal);
  1127. setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
  1128. } else {
  1129. setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
  1130. setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
  1131. }
  1132. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal);
  1133. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
  1134. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
  1135. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal);
  1136. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
  1137. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
  1138. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
  1139. }
  1140. if (Subtarget.hasP10Vector()) {
  1141. setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
  1142. }
  1143. }
  1144. if (Subtarget.pairedVectorMemops()) {
  1145. addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
  1146. setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
  1147. setOperationAction(ISD::STORE, MVT::v256i1, Custom);
  1148. }
  1149. if (Subtarget.hasMMA()) {
  1150. if (Subtarget.isISAFuture())
  1151. addRegisterClass(MVT::v512i1, &PPC::WACCRCRegClass);
  1152. else
  1153. addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
  1154. setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
  1155. setOperationAction(ISD::STORE, MVT::v512i1, Custom);
  1156. setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
  1157. }
  1158. if (Subtarget.has64BitSupport())
  1159. setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
  1160. if (Subtarget.isISA3_1())
  1161. setOperationAction(ISD::SRA, MVT::v1i128, Legal);
  1162. setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
  1163. if (!isPPC64) {
  1164. setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
  1165. setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
  1166. }
  1167. if (shouldInlineQuadwordAtomics()) {
  1168. setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
  1169. setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
  1170. setOperationAction(ISD::INTRINSIC_VOID, MVT::i128, Custom);
  1171. }
  1172. setBooleanContents(ZeroOrOneBooleanContent);
  1173. if (Subtarget.hasAltivec()) {
  1174. // Altivec instructions set fields to all zeros or all ones.
  1175. setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
  1176. }
  1177. setLibcallName(RTLIB::MULO_I128, nullptr);
  1178. if (!isPPC64) {
  1179. // These libcalls are not available in 32-bit.
  1180. setLibcallName(RTLIB::SHL_I128, nullptr);
  1181. setLibcallName(RTLIB::SRL_I128, nullptr);
  1182. setLibcallName(RTLIB::SRA_I128, nullptr);
  1183. setLibcallName(RTLIB::MUL_I128, nullptr);
  1184. setLibcallName(RTLIB::MULO_I64, nullptr);
  1185. }
  1186. if (!isPPC64)
  1187. setMaxAtomicSizeInBitsSupported(32);
  1188. else if (shouldInlineQuadwordAtomics())
  1189. setMaxAtomicSizeInBitsSupported(128);
  1190. else
  1191. setMaxAtomicSizeInBitsSupported(64);
  1192. setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
  1193. // We have target-specific dag combine patterns for the following nodes:
  1194. setTargetDAGCombine({ISD::ADD, ISD::SHL, ISD::SRA, ISD::SRL, ISD::MUL,
  1195. ISD::FMA, ISD::SINT_TO_FP, ISD::BUILD_VECTOR});
  1196. if (Subtarget.hasFPCVT())
  1197. setTargetDAGCombine(ISD::UINT_TO_FP);
  1198. setTargetDAGCombine({ISD::LOAD, ISD::STORE, ISD::BR_CC});
  1199. if (Subtarget.useCRBits())
  1200. setTargetDAGCombine(ISD::BRCOND);
  1201. setTargetDAGCombine({ISD::BSWAP, ISD::INTRINSIC_WO_CHAIN,
  1202. ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID});
  1203. setTargetDAGCombine({ISD::SIGN_EXTEND, ISD::ZERO_EXTEND, ISD::ANY_EXTEND});
  1204. setTargetDAGCombine({ISD::TRUNCATE, ISD::VECTOR_SHUFFLE});
  1205. if (Subtarget.useCRBits()) {
  1206. setTargetDAGCombine({ISD::TRUNCATE, ISD::SETCC, ISD::SELECT_CC});
  1207. }
  1208. if (Subtarget.hasP9Altivec()) {
  1209. setTargetDAGCombine({ISD::ABS, ISD::VSELECT});
  1210. }
  1211. setLibcallName(RTLIB::LOG_F128, "logf128");
  1212. setLibcallName(RTLIB::LOG2_F128, "log2f128");
  1213. setLibcallName(RTLIB::LOG10_F128, "log10f128");
  1214. setLibcallName(RTLIB::EXP_F128, "expf128");
  1215. setLibcallName(RTLIB::EXP2_F128, "exp2f128");
  1216. setLibcallName(RTLIB::SIN_F128, "sinf128");
  1217. setLibcallName(RTLIB::COS_F128, "cosf128");
  1218. setLibcallName(RTLIB::POW_F128, "powf128");
  1219. setLibcallName(RTLIB::FMIN_F128, "fminf128");
  1220. setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
  1221. setLibcallName(RTLIB::REM_F128, "fmodf128");
  1222. setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
  1223. setLibcallName(RTLIB::CEIL_F128, "ceilf128");
  1224. setLibcallName(RTLIB::FLOOR_F128, "floorf128");
  1225. setLibcallName(RTLIB::TRUNC_F128, "truncf128");
  1226. setLibcallName(RTLIB::ROUND_F128, "roundf128");
  1227. setLibcallName(RTLIB::LROUND_F128, "lroundf128");
  1228. setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
  1229. setLibcallName(RTLIB::RINT_F128, "rintf128");
  1230. setLibcallName(RTLIB::LRINT_F128, "lrintf128");
  1231. setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
  1232. setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
  1233. setLibcallName(RTLIB::FMA_F128, "fmaf128");
  1234. // With 32 condition bits, we don't need to sink (and duplicate) compares
  1235. // aggressively in CodeGenPrep.
  1236. if (Subtarget.useCRBits()) {
  1237. setHasMultipleConditionRegisters();
  1238. setJumpIsExpensive();
  1239. }
  1240. setMinFunctionAlignment(Align(4));
  1241. switch (Subtarget.getCPUDirective()) {
  1242. default: break;
  1243. case PPC::DIR_970:
  1244. case PPC::DIR_A2:
  1245. case PPC::DIR_E500:
  1246. case PPC::DIR_E500mc:
  1247. case PPC::DIR_E5500:
  1248. case PPC::DIR_PWR4:
  1249. case PPC::DIR_PWR5:
  1250. case PPC::DIR_PWR5X:
  1251. case PPC::DIR_PWR6:
  1252. case PPC::DIR_PWR6X:
  1253. case PPC::DIR_PWR7:
  1254. case PPC::DIR_PWR8:
  1255. case PPC::DIR_PWR9:
  1256. case PPC::DIR_PWR10:
  1257. case PPC::DIR_PWR_FUTURE:
  1258. setPrefLoopAlignment(Align(16));
  1259. setPrefFunctionAlignment(Align(16));
  1260. break;
  1261. }
  1262. if (Subtarget.enableMachineScheduler())
  1263. setSchedulingPreference(Sched::Source);
  1264. else
  1265. setSchedulingPreference(Sched::Hybrid);
  1266. computeRegisterProperties(STI.getRegisterInfo());
  1267. // The Freescale cores do better with aggressive inlining of memcpy and
  1268. // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
  1269. if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
  1270. Subtarget.getCPUDirective() == PPC::DIR_E5500) {
  1271. MaxStoresPerMemset = 32;
  1272. MaxStoresPerMemsetOptSize = 16;
  1273. MaxStoresPerMemcpy = 32;
  1274. MaxStoresPerMemcpyOptSize = 8;
  1275. MaxStoresPerMemmove = 32;
  1276. MaxStoresPerMemmoveOptSize = 8;
  1277. } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
  1278. // The A2 also benefits from (very) aggressive inlining of memcpy and
  1279. // friends. The overhead of a the function call, even when warm, can be
  1280. // over one hundred cycles.
  1281. MaxStoresPerMemset = 128;
  1282. MaxStoresPerMemcpy = 128;
  1283. MaxStoresPerMemmove = 128;
  1284. MaxLoadsPerMemcmp = 128;
  1285. } else {
  1286. MaxLoadsPerMemcmp = 8;
  1287. MaxLoadsPerMemcmpOptSize = 4;
  1288. }
  1289. IsStrictFPEnabled = true;
  1290. // Let the subtarget (CPU) decide if a predictable select is more expensive
  1291. // than the corresponding branch. This information is used in CGP to decide
  1292. // when to convert selects into branches.
  1293. PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
  1294. }
  1295. // *********************************** NOTE ************************************
  1296. // For selecting load and store instructions, the addressing modes are defined
  1297. // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
  1298. // patterns to match the load the store instructions.
  1299. //
  1300. // The TD definitions for the addressing modes correspond to their respective
  1301. // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
  1302. // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
  1303. // address mode flags of a particular node. Afterwards, the computed address
  1304. // flags are passed into getAddrModeForFlags() in order to retrieve the optimal
  1305. // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
  1306. // accordingly, based on the preferred addressing mode.
  1307. //
  1308. // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
  1309. // MemOpFlags contains all the possible flags that can be used to compute the
  1310. // optimal addressing mode for load and store instructions.
  1311. // AddrMode contains all the possible load and store addressing modes available
  1312. // on Power (such as DForm, DSForm, DQForm, XForm, etc.)
  1313. //
  1314. // When adding new load and store instructions, it is possible that new address
  1315. // flags may need to be added into MemOpFlags, and a new addressing mode will
  1316. // need to be added to AddrMode. An entry of the new addressing mode (consisting
  1317. // of the minimal and main distinguishing address flags for the new load/store
  1318. // instructions) will need to be added into initializeAddrModeMap() below.
  1319. // Finally, when adding new addressing modes, the getAddrModeForFlags() will
  1320. // need to be updated to account for selecting the optimal addressing mode.
  1321. // *****************************************************************************
  1322. /// Initialize the map that relates the different addressing modes of the load
  1323. /// and store instructions to a set of flags. This ensures the load/store
  1324. /// instruction is correctly matched during instruction selection.
  1325. void PPCTargetLowering::initializeAddrModeMap() {
  1326. AddrModesMap[PPC::AM_DForm] = {
  1327. // LWZ, STW
  1328. PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt,
  1329. PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt,
  1330. PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
  1331. PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
  1332. // LBZ, LHZ, STB, STH
  1333. PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
  1334. PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
  1335. PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
  1336. PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
  1337. // LHA
  1338. PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
  1339. PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
  1340. PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
  1341. PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
  1342. // LFS, LFD, STFS, STFD
  1343. PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
  1344. PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
  1345. PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
  1346. PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
  1347. };
  1348. AddrModesMap[PPC::AM_DSForm] = {
  1349. // LWA
  1350. PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt,
  1351. PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
  1352. PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
  1353. // LD, STD
  1354. PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt,
  1355. PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt,
  1356. PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt,
  1357. // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
  1358. PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
  1359. PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
  1360. PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
  1361. };
  1362. AddrModesMap[PPC::AM_DQForm] = {
  1363. // LXV, STXV
  1364. PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
  1365. PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
  1366. PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
  1367. };
  1368. AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 |
  1369. PPC::MOF_SubtargetP10};
  1370. // TODO: Add mapping for quadword load/store.
  1371. }
  1372. /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
  1373. /// the desired ByVal argument alignment.
  1374. static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
  1375. if (MaxAlign == MaxMaxAlign)
  1376. return;
  1377. if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
  1378. if (MaxMaxAlign >= 32 &&
  1379. VTy->getPrimitiveSizeInBits().getFixedValue() >= 256)
  1380. MaxAlign = Align(32);
  1381. else if (VTy->getPrimitiveSizeInBits().getFixedValue() >= 128 &&
  1382. MaxAlign < 16)
  1383. MaxAlign = Align(16);
  1384. } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  1385. Align EltAlign;
  1386. getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
  1387. if (EltAlign > MaxAlign)
  1388. MaxAlign = EltAlign;
  1389. } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
  1390. for (auto *EltTy : STy->elements()) {
  1391. Align EltAlign;
  1392. getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
  1393. if (EltAlign > MaxAlign)
  1394. MaxAlign = EltAlign;
  1395. if (MaxAlign == MaxMaxAlign)
  1396. break;
  1397. }
  1398. }
  1399. }
  1400. /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
  1401. /// function arguments in the caller parameter area.
  1402. uint64_t PPCTargetLowering::getByValTypeAlignment(Type *Ty,
  1403. const DataLayout &DL) const {
  1404. // 16byte and wider vectors are passed on 16byte boundary.
  1405. // The rest is 8 on PPC64 and 4 on PPC32 boundary.
  1406. Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
  1407. if (Subtarget.hasAltivec())
  1408. getMaxByValAlign(Ty, Alignment, Align(16));
  1409. return Alignment.value();
  1410. }
  1411. bool PPCTargetLowering::useSoftFloat() const {
  1412. return Subtarget.useSoftFloat();
  1413. }
  1414. bool PPCTargetLowering::hasSPE() const {
  1415. return Subtarget.hasSPE();
  1416. }
  1417. bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
  1418. return VT.isScalarInteger();
  1419. }
  1420. const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
  1421. switch ((PPCISD::NodeType)Opcode) {
  1422. case PPCISD::FIRST_NUMBER: break;
  1423. case PPCISD::FSEL: return "PPCISD::FSEL";
  1424. case PPCISD::XSMAXC: return "PPCISD::XSMAXC";
  1425. case PPCISD::XSMINC: return "PPCISD::XSMINC";
  1426. case PPCISD::FCFID: return "PPCISD::FCFID";
  1427. case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
  1428. case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
  1429. case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
  1430. case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
  1431. case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
  1432. case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
  1433. case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
  1434. case PPCISD::FP_TO_UINT_IN_VSR:
  1435. return "PPCISD::FP_TO_UINT_IN_VSR,";
  1436. case PPCISD::FP_TO_SINT_IN_VSR:
  1437. return "PPCISD::FP_TO_SINT_IN_VSR";
  1438. case PPCISD::FRE: return "PPCISD::FRE";
  1439. case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
  1440. case PPCISD::FTSQRT:
  1441. return "PPCISD::FTSQRT";
  1442. case PPCISD::FSQRT:
  1443. return "PPCISD::FSQRT";
  1444. case PPCISD::STFIWX: return "PPCISD::STFIWX";
  1445. case PPCISD::VPERM: return "PPCISD::VPERM";
  1446. case PPCISD::XXSPLT: return "PPCISD::XXSPLT";
  1447. case PPCISD::XXSPLTI_SP_TO_DP:
  1448. return "PPCISD::XXSPLTI_SP_TO_DP";
  1449. case PPCISD::XXSPLTI32DX:
  1450. return "PPCISD::XXSPLTI32DX";
  1451. case PPCISD::VECINSERT: return "PPCISD::VECINSERT";
  1452. case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI";
  1453. case PPCISD::XXPERM:
  1454. return "PPCISD::XXPERM";
  1455. case PPCISD::VECSHL: return "PPCISD::VECSHL";
  1456. case PPCISD::CMPB: return "PPCISD::CMPB";
  1457. case PPCISD::Hi: return "PPCISD::Hi";
  1458. case PPCISD::Lo: return "PPCISD::Lo";
  1459. case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
  1460. case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
  1461. case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
  1462. case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
  1463. case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
  1464. case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA";
  1465. case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
  1466. case PPCISD::SRL: return "PPCISD::SRL";
  1467. case PPCISD::SRA: return "PPCISD::SRA";
  1468. case PPCISD::SHL: return "PPCISD::SHL";
  1469. case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
  1470. case PPCISD::CALL: return "PPCISD::CALL";
  1471. case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
  1472. case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC";
  1473. case PPCISD::CALL_RM:
  1474. return "PPCISD::CALL_RM";
  1475. case PPCISD::CALL_NOP_RM:
  1476. return "PPCISD::CALL_NOP_RM";
  1477. case PPCISD::CALL_NOTOC_RM:
  1478. return "PPCISD::CALL_NOTOC_RM";
  1479. case PPCISD::MTCTR: return "PPCISD::MTCTR";
  1480. case PPCISD::BCTRL: return "PPCISD::BCTRL";
  1481. case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
  1482. case PPCISD::BCTRL_RM:
  1483. return "PPCISD::BCTRL_RM";
  1484. case PPCISD::BCTRL_LOAD_TOC_RM:
  1485. return "PPCISD::BCTRL_LOAD_TOC_RM";
  1486. case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
  1487. case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
  1488. case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
  1489. case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
  1490. case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
  1491. case PPCISD::MFVSR: return "PPCISD::MFVSR";
  1492. case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
  1493. case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
  1494. case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP";
  1495. case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP";
  1496. case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
  1497. return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
  1498. case PPCISD::ANDI_rec_1_EQ_BIT:
  1499. return "PPCISD::ANDI_rec_1_EQ_BIT";
  1500. case PPCISD::ANDI_rec_1_GT_BIT:
  1501. return "PPCISD::ANDI_rec_1_GT_BIT";
  1502. case PPCISD::VCMP: return "PPCISD::VCMP";
  1503. case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec";
  1504. case PPCISD::LBRX: return "PPCISD::LBRX";
  1505. case PPCISD::STBRX: return "PPCISD::STBRX";
  1506. case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
  1507. case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
  1508. case PPCISD::LXSIZX: return "PPCISD::LXSIZX";
  1509. case PPCISD::STXSIX: return "PPCISD::STXSIX";
  1510. case PPCISD::VEXTS: return "PPCISD::VEXTS";
  1511. case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
  1512. case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
  1513. case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE";
  1514. case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE";
  1515. case PPCISD::ST_VSR_SCAL_INT:
  1516. return "PPCISD::ST_VSR_SCAL_INT";
  1517. case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
  1518. case PPCISD::BDNZ: return "PPCISD::BDNZ";
  1519. case PPCISD::BDZ: return "PPCISD::BDZ";
  1520. case PPCISD::MFFS: return "PPCISD::MFFS";
  1521. case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
  1522. case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
  1523. case PPCISD::CR6SET: return "PPCISD::CR6SET";
  1524. case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
  1525. case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
  1526. case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
  1527. case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
  1528. case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
  1529. case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
  1530. case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
  1531. case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
  1532. case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
  1533. case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
  1534. case PPCISD::TLSGD_AIX: return "PPCISD::TLSGD_AIX";
  1535. case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
  1536. case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
  1537. case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
  1538. case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
  1539. case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
  1540. case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
  1541. case PPCISD::PADDI_DTPREL:
  1542. return "PPCISD::PADDI_DTPREL";
  1543. case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
  1544. case PPCISD::SC: return "PPCISD::SC";
  1545. case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
  1546. case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
  1547. case PPCISD::RFEBB: return "PPCISD::RFEBB";
  1548. case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
  1549. case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN";
  1550. case PPCISD::VABSD: return "PPCISD::VABSD";
  1551. case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128";
  1552. case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64";
  1553. case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE";
  1554. case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI";
  1555. case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH";
  1556. case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF";
  1557. case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR";
  1558. case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
  1559. return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
  1560. case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
  1561. return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
  1562. case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD";
  1563. case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD";
  1564. case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
  1565. case PPCISD::XXMFACC: return "PPCISD::XXMFACC";
  1566. case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT";
  1567. case PPCISD::ZEXT_LD_SPLAT: return "PPCISD::ZEXT_LD_SPLAT";
  1568. case PPCISD::SEXT_LD_SPLAT: return "PPCISD::SEXT_LD_SPLAT";
  1569. case PPCISD::FNMSUB: return "PPCISD::FNMSUB";
  1570. case PPCISD::STRICT_FADDRTZ:
  1571. return "PPCISD::STRICT_FADDRTZ";
  1572. case PPCISD::STRICT_FCTIDZ:
  1573. return "PPCISD::STRICT_FCTIDZ";
  1574. case PPCISD::STRICT_FCTIWZ:
  1575. return "PPCISD::STRICT_FCTIWZ";
  1576. case PPCISD::STRICT_FCTIDUZ:
  1577. return "PPCISD::STRICT_FCTIDUZ";
  1578. case PPCISD::STRICT_FCTIWUZ:
  1579. return "PPCISD::STRICT_FCTIWUZ";
  1580. case PPCISD::STRICT_FCFID:
  1581. return "PPCISD::STRICT_FCFID";
  1582. case PPCISD::STRICT_FCFIDU:
  1583. return "PPCISD::STRICT_FCFIDU";
  1584. case PPCISD::STRICT_FCFIDS:
  1585. return "PPCISD::STRICT_FCFIDS";
  1586. case PPCISD::STRICT_FCFIDUS:
  1587. return "PPCISD::STRICT_FCFIDUS";
  1588. case PPCISD::LXVRZX: return "PPCISD::LXVRZX";
  1589. case PPCISD::STORE_COND:
  1590. return "PPCISD::STORE_COND";
  1591. }
  1592. return nullptr;
  1593. }
  1594. EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
  1595. EVT VT) const {
  1596. if (!VT.isVector())
  1597. return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
  1598. return VT.changeVectorElementTypeToInteger();
  1599. }
  1600. bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
  1601. assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
  1602. return true;
  1603. }
  1604. //===----------------------------------------------------------------------===//
  1605. // Node matching predicates, for use by the tblgen matching code.
  1606. //===----------------------------------------------------------------------===//
  1607. /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
  1608. static bool isFloatingPointZero(SDValue Op) {
  1609. if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
  1610. return CFP->getValueAPF().isZero();
  1611. else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
  1612. // Maybe this has already been legalized into the constant pool?
  1613. if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
  1614. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
  1615. return CFP->getValueAPF().isZero();
  1616. }
  1617. return false;
  1618. }
  1619. /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
  1620. /// true if Op is undef or if it matches the specified value.
  1621. static bool isConstantOrUndef(int Op, int Val) {
  1622. return Op < 0 || Op == Val;
  1623. }
  1624. /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
  1625. /// VPKUHUM instruction.
  1626. /// The ShuffleKind distinguishes between big-endian operations with
  1627. /// two different inputs (0), either-endian operations with two identical
  1628. /// inputs (1), and little-endian operations with two different inputs (2).
  1629. /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
  1630. bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
  1631. SelectionDAG &DAG) {
  1632. bool IsLE = DAG.getDataLayout().isLittleEndian();
  1633. if (ShuffleKind == 0) {
  1634. if (IsLE)
  1635. return false;
  1636. for (unsigned i = 0; i != 16; ++i)
  1637. if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
  1638. return false;
  1639. } else if (ShuffleKind == 2) {
  1640. if (!IsLE)
  1641. return false;
  1642. for (unsigned i = 0; i != 16; ++i)
  1643. if (!isConstantOrUndef(N->getMaskElt(i), i*2))
  1644. return false;
  1645. } else if (ShuffleKind == 1) {
  1646. unsigned j = IsLE ? 0 : 1;
  1647. for (unsigned i = 0; i != 8; ++i)
  1648. if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
  1649. !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
  1650. return false;
  1651. }
  1652. return true;
  1653. }
  1654. /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
  1655. /// VPKUWUM instruction.
  1656. /// The ShuffleKind distinguishes between big-endian operations with
  1657. /// two different inputs (0), either-endian operations with two identical
  1658. /// inputs (1), and little-endian operations with two different inputs (2).
  1659. /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
  1660. bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
  1661. SelectionDAG &DAG) {
  1662. bool IsLE = DAG.getDataLayout().isLittleEndian();
  1663. if (ShuffleKind == 0) {
  1664. if (IsLE)
  1665. return false;
  1666. for (unsigned i = 0; i != 16; i += 2)
  1667. if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
  1668. !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
  1669. return false;
  1670. } else if (ShuffleKind == 2) {
  1671. if (!IsLE)
  1672. return false;
  1673. for (unsigned i = 0; i != 16; i += 2)
  1674. if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
  1675. !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
  1676. return false;
  1677. } else if (ShuffleKind == 1) {
  1678. unsigned j = IsLE ? 0 : 2;
  1679. for (unsigned i = 0; i != 8; i += 2)
  1680. if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
  1681. !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
  1682. !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
  1683. !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
  1684. return false;
  1685. }
  1686. return true;
  1687. }
  1688. /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
  1689. /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
  1690. /// current subtarget.
  1691. ///
  1692. /// The ShuffleKind distinguishes between big-endian operations with
  1693. /// two different inputs (0), either-endian operations with two identical
  1694. /// inputs (1), and little-endian operations with two different inputs (2).
  1695. /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
  1696. bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
  1697. SelectionDAG &DAG) {
  1698. const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
  1699. if (!Subtarget.hasP8Vector())
  1700. return false;
  1701. bool IsLE = DAG.getDataLayout().isLittleEndian();
  1702. if (ShuffleKind == 0) {
  1703. if (IsLE)
  1704. return false;
  1705. for (unsigned i = 0; i != 16; i += 4)
  1706. if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
  1707. !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
  1708. !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
  1709. !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
  1710. return false;
  1711. } else if (ShuffleKind == 2) {
  1712. if (!IsLE)
  1713. return false;
  1714. for (unsigned i = 0; i != 16; i += 4)
  1715. if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
  1716. !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
  1717. !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
  1718. !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
  1719. return false;
  1720. } else if (ShuffleKind == 1) {
  1721. unsigned j = IsLE ? 0 : 4;
  1722. for (unsigned i = 0; i != 8; i += 4)
  1723. if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
  1724. !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
  1725. !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
  1726. !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
  1727. !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
  1728. !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
  1729. !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
  1730. !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
  1731. return false;
  1732. }
  1733. return true;
  1734. }
  1735. /// isVMerge - Common function, used to match vmrg* shuffles.
  1736. ///
  1737. static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
  1738. unsigned LHSStart, unsigned RHSStart) {
  1739. if (N->getValueType(0) != MVT::v16i8)
  1740. return false;
  1741. assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
  1742. "Unsupported merge size!");
  1743. for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
  1744. for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
  1745. if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
  1746. LHSStart+j+i*UnitSize) ||
  1747. !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
  1748. RHSStart+j+i*UnitSize))
  1749. return false;
  1750. }
  1751. return true;
  1752. }
  1753. /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
  1754. /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
  1755. /// The ShuffleKind distinguishes between big-endian merges with two
  1756. /// different inputs (0), either-endian merges with two identical inputs (1),
  1757. /// and little-endian merges with two different inputs (2). For the latter,
  1758. /// the input operands are swapped (see PPCInstrAltivec.td).
  1759. bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
  1760. unsigned ShuffleKind, SelectionDAG &DAG) {
  1761. if (DAG.getDataLayout().isLittleEndian()) {
  1762. if (ShuffleKind == 1) // unary
  1763. return isVMerge(N, UnitSize, 0, 0);
  1764. else if (ShuffleKind == 2) // swapped
  1765. return isVMerge(N, UnitSize, 0, 16);
  1766. else
  1767. return false;
  1768. } else {
  1769. if (ShuffleKind == 1) // unary
  1770. return isVMerge(N, UnitSize, 8, 8);
  1771. else if (ShuffleKind == 0) // normal
  1772. return isVMerge(N, UnitSize, 8, 24);
  1773. else
  1774. return false;
  1775. }
  1776. }
  1777. /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
  1778. /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
  1779. /// The ShuffleKind distinguishes between big-endian merges with two
  1780. /// different inputs (0), either-endian merges with two identical inputs (1),
  1781. /// and little-endian merges with two different inputs (2). For the latter,
  1782. /// the input operands are swapped (see PPCInstrAltivec.td).
  1783. bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
  1784. unsigned ShuffleKind, SelectionDAG &DAG) {
  1785. if (DAG.getDataLayout().isLittleEndian()) {
  1786. if (ShuffleKind == 1) // unary
  1787. return isVMerge(N, UnitSize, 8, 8);
  1788. else if (ShuffleKind == 2) // swapped
  1789. return isVMerge(N, UnitSize, 8, 24);
  1790. else
  1791. return false;
  1792. } else {
  1793. if (ShuffleKind == 1) // unary
  1794. return isVMerge(N, UnitSize, 0, 0);
  1795. else if (ShuffleKind == 0) // normal
  1796. return isVMerge(N, UnitSize, 0, 16);
  1797. else
  1798. return false;
  1799. }
  1800. }
  1801. /**
  1802. * Common function used to match vmrgew and vmrgow shuffles
  1803. *
  1804. * The indexOffset determines whether to look for even or odd words in
  1805. * the shuffle mask. This is based on the of the endianness of the target
  1806. * machine.
  1807. * - Little Endian:
  1808. * - Use offset of 0 to check for odd elements
  1809. * - Use offset of 4 to check for even elements
  1810. * - Big Endian:
  1811. * - Use offset of 0 to check for even elements
  1812. * - Use offset of 4 to check for odd elements
  1813. * A detailed description of the vector element ordering for little endian and
  1814. * big endian can be found at
  1815. * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
  1816. * Targeting your applications - what little endian and big endian IBM XL C/C++
  1817. * compiler differences mean to you
  1818. *
  1819. * The mask to the shuffle vector instruction specifies the indices of the
  1820. * elements from the two input vectors to place in the result. The elements are
  1821. * numbered in array-access order, starting with the first vector. These vectors
  1822. * are always of type v16i8, thus each vector will contain 16 elements of size
  1823. * 8. More info on the shuffle vector can be found in the
  1824. * http://llvm.org/docs/LangRef.html#shufflevector-instruction
  1825. * Language Reference.
  1826. *
  1827. * The RHSStartValue indicates whether the same input vectors are used (unary)
  1828. * or two different input vectors are used, based on the following:
  1829. * - If the instruction uses the same vector for both inputs, the range of the
  1830. * indices will be 0 to 15. In this case, the RHSStart value passed should
  1831. * be 0.
  1832. * - If the instruction has two different vectors then the range of the
  1833. * indices will be 0 to 31. In this case, the RHSStart value passed should
  1834. * be 16 (indices 0-15 specify elements in the first vector while indices 16
  1835. * to 31 specify elements in the second vector).
  1836. *
  1837. * \param[in] N The shuffle vector SD Node to analyze
  1838. * \param[in] IndexOffset Specifies whether to look for even or odd elements
  1839. * \param[in] RHSStartValue Specifies the starting index for the righthand input
  1840. * vector to the shuffle_vector instruction
  1841. * \return true iff this shuffle vector represents an even or odd word merge
  1842. */
  1843. static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
  1844. unsigned RHSStartValue) {
  1845. if (N->getValueType(0) != MVT::v16i8)
  1846. return false;
  1847. for (unsigned i = 0; i < 2; ++i)
  1848. for (unsigned j = 0; j < 4; ++j)
  1849. if (!isConstantOrUndef(N->getMaskElt(i*4+j),
  1850. i*RHSStartValue+j+IndexOffset) ||
  1851. !isConstantOrUndef(N->getMaskElt(i*4+j+8),
  1852. i*RHSStartValue+j+IndexOffset+8))
  1853. return false;
  1854. return true;
  1855. }
  1856. /**
  1857. * Determine if the specified shuffle mask is suitable for the vmrgew or
  1858. * vmrgow instructions.
  1859. *
  1860. * \param[in] N The shuffle vector SD Node to analyze
  1861. * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
  1862. * \param[in] ShuffleKind Identify the type of merge:
  1863. * - 0 = big-endian merge with two different inputs;
  1864. * - 1 = either-endian merge with two identical inputs;
  1865. * - 2 = little-endian merge with two different inputs (inputs are swapped for
  1866. * little-endian merges).
  1867. * \param[in] DAG The current SelectionDAG
  1868. * \return true iff this shuffle mask
  1869. */
  1870. bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
  1871. unsigned ShuffleKind, SelectionDAG &DAG) {
  1872. if (DAG.getDataLayout().isLittleEndian()) {
  1873. unsigned indexOffset = CheckEven ? 4 : 0;
  1874. if (ShuffleKind == 1) // Unary
  1875. return isVMerge(N, indexOffset, 0);
  1876. else if (ShuffleKind == 2) // swapped
  1877. return isVMerge(N, indexOffset, 16);
  1878. else
  1879. return false;
  1880. }
  1881. else {
  1882. unsigned indexOffset = CheckEven ? 0 : 4;
  1883. if (ShuffleKind == 1) // Unary
  1884. return isVMerge(N, indexOffset, 0);
  1885. else if (ShuffleKind == 0) // Normal
  1886. return isVMerge(N, indexOffset, 16);
  1887. else
  1888. return false;
  1889. }
  1890. return false;
  1891. }
  1892. /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
  1893. /// amount, otherwise return -1.
  1894. /// The ShuffleKind distinguishes between big-endian operations with two
  1895. /// different inputs (0), either-endian operations with two identical inputs
  1896. /// (1), and little-endian operations with two different inputs (2). For the
  1897. /// latter, the input operands are swapped (see PPCInstrAltivec.td).
  1898. int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
  1899. SelectionDAG &DAG) {
  1900. if (N->getValueType(0) != MVT::v16i8)
  1901. return -1;
  1902. ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
  1903. // Find the first non-undef value in the shuffle mask.
  1904. unsigned i;
  1905. for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
  1906. /*search*/;
  1907. if (i == 16) return -1; // all undef.
  1908. // Otherwise, check to see if the rest of the elements are consecutively
  1909. // numbered from this value.
  1910. unsigned ShiftAmt = SVOp->getMaskElt(i);
  1911. if (ShiftAmt < i) return -1;
  1912. ShiftAmt -= i;
  1913. bool isLE = DAG.getDataLayout().isLittleEndian();
  1914. if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
  1915. // Check the rest of the elements to see if they are consecutive.
  1916. for (++i; i != 16; ++i)
  1917. if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
  1918. return -1;
  1919. } else if (ShuffleKind == 1) {
  1920. // Check the rest of the elements to see if they are consecutive.
  1921. for (++i; i != 16; ++i)
  1922. if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
  1923. return -1;
  1924. } else
  1925. return -1;
  1926. if (isLE)
  1927. ShiftAmt = 16 - ShiftAmt;
  1928. return ShiftAmt;
  1929. }
  1930. /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
  1931. /// specifies a splat of a single element that is suitable for input to
  1932. /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
  1933. bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
  1934. EVT VT = N->getValueType(0);
  1935. if (VT == MVT::v2i64 || VT == MVT::v2f64)
  1936. return EltSize == 8 && N->getMaskElt(0) == N->getMaskElt(1);
  1937. assert(VT == MVT::v16i8 && isPowerOf2_32(EltSize) &&
  1938. EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
  1939. // The consecutive indices need to specify an element, not part of two
  1940. // different elements. So abandon ship early if this isn't the case.
  1941. if (N->getMaskElt(0) % EltSize != 0)
  1942. return false;
  1943. // This is a splat operation if each element of the permute is the same, and
  1944. // if the value doesn't reference the second vector.
  1945. unsigned ElementBase = N->getMaskElt(0);
  1946. // FIXME: Handle UNDEF elements too!
  1947. if (ElementBase >= 16)
  1948. return false;
  1949. // Check that the indices are consecutive, in the case of a multi-byte element
  1950. // splatted with a v16i8 mask.
  1951. for (unsigned i = 1; i != EltSize; ++i)
  1952. if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
  1953. return false;
  1954. for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
  1955. if (N->getMaskElt(i) < 0) continue;
  1956. for (unsigned j = 0; j != EltSize; ++j)
  1957. if (N->getMaskElt(i+j) != N->getMaskElt(j))
  1958. return false;
  1959. }
  1960. return true;
  1961. }
  1962. /// Check that the mask is shuffling N byte elements. Within each N byte
  1963. /// element of the mask, the indices could be either in increasing or
  1964. /// decreasing order as long as they are consecutive.
  1965. /// \param[in] N the shuffle vector SD Node to analyze
  1966. /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
  1967. /// Word/DoubleWord/QuadWord).
  1968. /// \param[in] StepLen the delta indices number among the N byte element, if
  1969. /// the mask is in increasing/decreasing order then it is 1/-1.
  1970. /// \return true iff the mask is shuffling N byte elements.
  1971. static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
  1972. int StepLen) {
  1973. assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
  1974. "Unexpected element width.");
  1975. assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
  1976. unsigned NumOfElem = 16 / Width;
  1977. unsigned MaskVal[16]; // Width is never greater than 16
  1978. for (unsigned i = 0; i < NumOfElem; ++i) {
  1979. MaskVal[0] = N->getMaskElt(i * Width);
  1980. if ((StepLen == 1) && (MaskVal[0] % Width)) {
  1981. return false;
  1982. } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
  1983. return false;
  1984. }
  1985. for (unsigned int j = 1; j < Width; ++j) {
  1986. MaskVal[j] = N->getMaskElt(i * Width + j);
  1987. if (MaskVal[j] != MaskVal[j-1] + StepLen) {
  1988. return false;
  1989. }
  1990. }
  1991. }
  1992. return true;
  1993. }
  1994. bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
  1995. unsigned &InsertAtByte, bool &Swap, bool IsLE) {
  1996. if (!isNByteElemShuffleMask(N, 4, 1))
  1997. return false;
  1998. // Now we look at mask elements 0,4,8,12
  1999. unsigned M0 = N->getMaskElt(0) / 4;
  2000. unsigned M1 = N->getMaskElt(4) / 4;
  2001. unsigned M2 = N->getMaskElt(8) / 4;
  2002. unsigned M3 = N->getMaskElt(12) / 4;
  2003. unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
  2004. unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
  2005. // Below, let H and L be arbitrary elements of the shuffle mask
  2006. // where H is in the range [4,7] and L is in the range [0,3].
  2007. // H, 1, 2, 3 or L, 5, 6, 7
  2008. if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
  2009. (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
  2010. ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
  2011. InsertAtByte = IsLE ? 12 : 0;
  2012. Swap = M0 < 4;
  2013. return true;
  2014. }
  2015. // 0, H, 2, 3 or 4, L, 6, 7
  2016. if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
  2017. (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
  2018. ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
  2019. InsertAtByte = IsLE ? 8 : 4;
  2020. Swap = M1 < 4;
  2021. return true;
  2022. }
  2023. // 0, 1, H, 3 or 4, 5, L, 7
  2024. if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
  2025. (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
  2026. ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
  2027. InsertAtByte = IsLE ? 4 : 8;
  2028. Swap = M2 < 4;
  2029. return true;
  2030. }
  2031. // 0, 1, 2, H or 4, 5, 6, L
  2032. if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
  2033. (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
  2034. ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
  2035. InsertAtByte = IsLE ? 0 : 12;
  2036. Swap = M3 < 4;
  2037. return true;
  2038. }
  2039. // If both vector operands for the shuffle are the same vector, the mask will
  2040. // contain only elements from the first one and the second one will be undef.
  2041. if (N->getOperand(1).isUndef()) {
  2042. ShiftElts = 0;
  2043. Swap = true;
  2044. unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
  2045. if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
  2046. InsertAtByte = IsLE ? 12 : 0;
  2047. return true;
  2048. }
  2049. if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
  2050. InsertAtByte = IsLE ? 8 : 4;
  2051. return true;
  2052. }
  2053. if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
  2054. InsertAtByte = IsLE ? 4 : 8;
  2055. return true;
  2056. }
  2057. if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
  2058. InsertAtByte = IsLE ? 0 : 12;
  2059. return true;
  2060. }
  2061. }
  2062. return false;
  2063. }
  2064. bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
  2065. bool &Swap, bool IsLE) {
  2066. assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
  2067. // Ensure each byte index of the word is consecutive.
  2068. if (!isNByteElemShuffleMask(N, 4, 1))
  2069. return false;
  2070. // Now we look at mask elements 0,4,8,12, which are the beginning of words.
  2071. unsigned M0 = N->getMaskElt(0) / 4;
  2072. unsigned M1 = N->getMaskElt(4) / 4;
  2073. unsigned M2 = N->getMaskElt(8) / 4;
  2074. unsigned M3 = N->getMaskElt(12) / 4;
  2075. // If both vector operands for the shuffle are the same vector, the mask will
  2076. // contain only elements from the first one and the second one will be undef.
  2077. if (N->getOperand(1).isUndef()) {
  2078. assert(M0 < 4 && "Indexing into an undef vector?");
  2079. if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
  2080. return false;
  2081. ShiftElts = IsLE ? (4 - M0) % 4 : M0;
  2082. Swap = false;
  2083. return true;
  2084. }
  2085. // Ensure each word index of the ShuffleVector Mask is consecutive.
  2086. if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
  2087. return false;
  2088. if (IsLE) {
  2089. if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
  2090. // Input vectors don't need to be swapped if the leading element
  2091. // of the result is one of the 3 left elements of the second vector
  2092. // (or if there is no shift to be done at all).
  2093. Swap = false;
  2094. ShiftElts = (8 - M0) % 8;
  2095. } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
  2096. // Input vectors need to be swapped if the leading element
  2097. // of the result is one of the 3 left elements of the first vector
  2098. // (or if we're shifting by 4 - thereby simply swapping the vectors).
  2099. Swap = true;
  2100. ShiftElts = (4 - M0) % 4;
  2101. }
  2102. return true;
  2103. } else { // BE
  2104. if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
  2105. // Input vectors don't need to be swapped if the leading element
  2106. // of the result is one of the 4 elements of the first vector.
  2107. Swap = false;
  2108. ShiftElts = M0;
  2109. } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
  2110. // Input vectors need to be swapped if the leading element
  2111. // of the result is one of the 4 elements of the right vector.
  2112. Swap = true;
  2113. ShiftElts = M0 - 4;
  2114. }
  2115. return true;
  2116. }
  2117. }
  2118. bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
  2119. assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
  2120. if (!isNByteElemShuffleMask(N, Width, -1))
  2121. return false;
  2122. for (int i = 0; i < 16; i += Width)
  2123. if (N->getMaskElt(i) != i + Width - 1)
  2124. return false;
  2125. return true;
  2126. }
  2127. bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
  2128. return isXXBRShuffleMaskHelper(N, 2);
  2129. }
  2130. bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
  2131. return isXXBRShuffleMaskHelper(N, 4);
  2132. }
  2133. bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
  2134. return isXXBRShuffleMaskHelper(N, 8);
  2135. }
  2136. bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
  2137. return isXXBRShuffleMaskHelper(N, 16);
  2138. }
  2139. /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
  2140. /// if the inputs to the instruction should be swapped and set \p DM to the
  2141. /// value for the immediate.
  2142. /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
  2143. /// AND element 0 of the result comes from the first input (LE) or second input
  2144. /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
  2145. /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
  2146. /// mask.
  2147. bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
  2148. bool &Swap, bool IsLE) {
  2149. assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
  2150. // Ensure each byte index of the double word is consecutive.
  2151. if (!isNByteElemShuffleMask(N, 8, 1))
  2152. return false;
  2153. unsigned M0 = N->getMaskElt(0) / 8;
  2154. unsigned M1 = N->getMaskElt(8) / 8;
  2155. assert(((M0 | M1) < 4) && "A mask element out of bounds?");
  2156. // If both vector operands for the shuffle are the same vector, the mask will
  2157. // contain only elements from the first one and the second one will be undef.
  2158. if (N->getOperand(1).isUndef()) {
  2159. if ((M0 | M1) < 2) {
  2160. DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
  2161. Swap = false;
  2162. return true;
  2163. } else
  2164. return false;
  2165. }
  2166. if (IsLE) {
  2167. if (M0 > 1 && M1 < 2) {
  2168. Swap = false;
  2169. } else if (M0 < 2 && M1 > 1) {
  2170. M0 = (M0 + 2) % 4;
  2171. M1 = (M1 + 2) % 4;
  2172. Swap = true;
  2173. } else
  2174. return false;
  2175. // Note: if control flow comes here that means Swap is already set above
  2176. DM = (((~M1) & 1) << 1) + ((~M0) & 1);
  2177. return true;
  2178. } else { // BE
  2179. if (M0 < 2 && M1 > 1) {
  2180. Swap = false;
  2181. } else if (M0 > 1 && M1 < 2) {
  2182. M0 = (M0 + 2) % 4;
  2183. M1 = (M1 + 2) % 4;
  2184. Swap = true;
  2185. } else
  2186. return false;
  2187. // Note: if control flow comes here that means Swap is already set above
  2188. DM = (M0 << 1) + (M1 & 1);
  2189. return true;
  2190. }
  2191. }
  2192. /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
  2193. /// appropriate for PPC mnemonics (which have a big endian bias - namely
  2194. /// elements are counted from the left of the vector register).
  2195. unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
  2196. SelectionDAG &DAG) {
  2197. ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
  2198. assert(isSplatShuffleMask(SVOp, EltSize));
  2199. EVT VT = SVOp->getValueType(0);
  2200. if (VT == MVT::v2i64 || VT == MVT::v2f64)
  2201. return DAG.getDataLayout().isLittleEndian() ? 1 - SVOp->getMaskElt(0)
  2202. : SVOp->getMaskElt(0);
  2203. if (DAG.getDataLayout().isLittleEndian())
  2204. return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
  2205. else
  2206. return SVOp->getMaskElt(0) / EltSize;
  2207. }
  2208. /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
  2209. /// by using a vspltis[bhw] instruction of the specified element size, return
  2210. /// the constant being splatted. The ByteSize field indicates the number of
  2211. /// bytes of each element [124] -> [bhw].
  2212. SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
  2213. SDValue OpVal;
  2214. // If ByteSize of the splat is bigger than the element size of the
  2215. // build_vector, then we have a case where we are checking for a splat where
  2216. // multiple elements of the buildvector are folded together into a single
  2217. // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
  2218. unsigned EltSize = 16/N->getNumOperands();
  2219. if (EltSize < ByteSize) {
  2220. unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
  2221. SDValue UniquedVals[4];
  2222. assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
  2223. // See if all of the elements in the buildvector agree across.
  2224. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  2225. if (N->getOperand(i).isUndef()) continue;
  2226. // If the element isn't a constant, bail fully out.
  2227. if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
  2228. if (!UniquedVals[i&(Multiple-1)].getNode())
  2229. UniquedVals[i&(Multiple-1)] = N->getOperand(i);
  2230. else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
  2231. return SDValue(); // no match.
  2232. }
  2233. // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
  2234. // either constant or undef values that are identical for each chunk. See
  2235. // if these chunks can form into a larger vspltis*.
  2236. // Check to see if all of the leading entries are either 0 or -1. If
  2237. // neither, then this won't fit into the immediate field.
  2238. bool LeadingZero = true;
  2239. bool LeadingOnes = true;
  2240. for (unsigned i = 0; i != Multiple-1; ++i) {
  2241. if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
  2242. LeadingZero &= isNullConstant(UniquedVals[i]);
  2243. LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
  2244. }
  2245. // Finally, check the least significant entry.
  2246. if (LeadingZero) {
  2247. if (!UniquedVals[Multiple-1].getNode())
  2248. return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
  2249. int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
  2250. if (Val < 16) // 0,0,0,4 -> vspltisw(4)
  2251. return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
  2252. }
  2253. if (LeadingOnes) {
  2254. if (!UniquedVals[Multiple-1].getNode())
  2255. return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
  2256. int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
  2257. if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
  2258. return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
  2259. }
  2260. return SDValue();
  2261. }
  2262. // Check to see if this buildvec has a single non-undef value in its elements.
  2263. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  2264. if (N->getOperand(i).isUndef()) continue;
  2265. if (!OpVal.getNode())
  2266. OpVal = N->getOperand(i);
  2267. else if (OpVal != N->getOperand(i))
  2268. return SDValue();
  2269. }
  2270. if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
  2271. unsigned ValSizeInBytes = EltSize;
  2272. uint64_t Value = 0;
  2273. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
  2274. Value = CN->getZExtValue();
  2275. } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
  2276. assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
  2277. Value = FloatToBits(CN->getValueAPF().convertToFloat());
  2278. }
  2279. // If the splat value is larger than the element value, then we can never do
  2280. // this splat. The only case that we could fit the replicated bits into our
  2281. // immediate field for would be zero, and we prefer to use vxor for it.
  2282. if (ValSizeInBytes < ByteSize) return SDValue();
  2283. // If the element value is larger than the splat value, check if it consists
  2284. // of a repeated bit pattern of size ByteSize.
  2285. if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
  2286. return SDValue();
  2287. // Properly sign extend the value.
  2288. int MaskVal = SignExtend32(Value, ByteSize * 8);
  2289. // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
  2290. if (MaskVal == 0) return SDValue();
  2291. // Finally, if this value fits in a 5 bit sext field, return it
  2292. if (SignExtend32<5>(MaskVal) == MaskVal)
  2293. return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
  2294. return SDValue();
  2295. }
  2296. //===----------------------------------------------------------------------===//
  2297. // Addressing Mode Selection
  2298. //===----------------------------------------------------------------------===//
  2299. /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
  2300. /// or 64-bit immediate, and if the value can be accurately represented as a
  2301. /// sign extension from a 16-bit value. If so, this returns true and the
  2302. /// immediate.
  2303. bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
  2304. if (!isa<ConstantSDNode>(N))
  2305. return false;
  2306. Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
  2307. if (N->getValueType(0) == MVT::i32)
  2308. return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
  2309. else
  2310. return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
  2311. }
  2312. bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
  2313. return isIntS16Immediate(Op.getNode(), Imm);
  2314. }
  2315. /// Used when computing address flags for selecting loads and stores.
  2316. /// If we have an OR, check if the LHS and RHS are provably disjoint.
  2317. /// An OR of two provably disjoint values is equivalent to an ADD.
  2318. /// Most PPC load/store instructions compute the effective address as a sum,
  2319. /// so doing this conversion is useful.
  2320. static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
  2321. if (N.getOpcode() != ISD::OR)
  2322. return false;
  2323. KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
  2324. if (!LHSKnown.Zero.getBoolValue())
  2325. return false;
  2326. KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
  2327. return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
  2328. }
  2329. /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
  2330. /// be represented as an indexed [r+r] operation.
  2331. bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
  2332. SDValue &Index,
  2333. SelectionDAG &DAG) const {
  2334. for (SDNode *U : N->uses()) {
  2335. if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) {
  2336. if (Memop->getMemoryVT() == MVT::f64) {
  2337. Base = N.getOperand(0);
  2338. Index = N.getOperand(1);
  2339. return true;
  2340. }
  2341. }
  2342. }
  2343. return false;
  2344. }
  2345. /// isIntS34Immediate - This method tests if value of node given can be
  2346. /// accurately represented as a sign extension from a 34-bit value. If so,
  2347. /// this returns true and the immediate.
  2348. bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
  2349. if (!isa<ConstantSDNode>(N))
  2350. return false;
  2351. Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
  2352. return isInt<34>(Imm);
  2353. }
  2354. bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
  2355. return isIntS34Immediate(Op.getNode(), Imm);
  2356. }
  2357. /// SelectAddressRegReg - Given the specified addressed, check to see if it
  2358. /// can be represented as an indexed [r+r] operation. Returns false if it
  2359. /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
  2360. /// non-zero and N can be represented by a base register plus a signed 16-bit
  2361. /// displacement, make a more precise judgement by checking (displacement % \p
  2362. /// EncodingAlignment).
  2363. bool PPCTargetLowering::SelectAddressRegReg(
  2364. SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
  2365. MaybeAlign EncodingAlignment) const {
  2366. // If we have a PC Relative target flag don't select as [reg+reg]. It will be
  2367. // a [pc+imm].
  2368. if (SelectAddressPCRel(N, Base))
  2369. return false;
  2370. int16_t Imm = 0;
  2371. if (N.getOpcode() == ISD::ADD) {
  2372. // Is there any SPE load/store (f64), which can't handle 16bit offset?
  2373. // SPE load/store can only handle 8-bit offsets.
  2374. if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
  2375. return true;
  2376. if (isIntS16Immediate(N.getOperand(1), Imm) &&
  2377. (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
  2378. return false; // r+i
  2379. if (N.getOperand(1).getOpcode() == PPCISD::Lo)
  2380. return false; // r+i
  2381. Base = N.getOperand(0);
  2382. Index = N.getOperand(1);
  2383. return true;
  2384. } else if (N.getOpcode() == ISD::OR) {
  2385. if (isIntS16Immediate(N.getOperand(1), Imm) &&
  2386. (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
  2387. return false; // r+i can fold it if we can.
  2388. // If this is an or of disjoint bitfields, we can codegen this as an add
  2389. // (for better address arithmetic) if the LHS and RHS of the OR are provably
  2390. // disjoint.
  2391. KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
  2392. if (LHSKnown.Zero.getBoolValue()) {
  2393. KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
  2394. // If all of the bits are known zero on the LHS or RHS, the add won't
  2395. // carry.
  2396. if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
  2397. Base = N.getOperand(0);
  2398. Index = N.getOperand(1);
  2399. return true;
  2400. }
  2401. }
  2402. }
  2403. return false;
  2404. }
  2405. // If we happen to be doing an i64 load or store into a stack slot that has
  2406. // less than a 4-byte alignment, then the frame-index elimination may need to
  2407. // use an indexed load or store instruction (because the offset may not be a
  2408. // multiple of 4). The extra register needed to hold the offset comes from the
  2409. // register scavenger, and it is possible that the scavenger will need to use
  2410. // an emergency spill slot. As a result, we need to make sure that a spill slot
  2411. // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
  2412. // stack slot.
  2413. static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
  2414. // FIXME: This does not handle the LWA case.
  2415. if (VT != MVT::i64)
  2416. return;
  2417. // NOTE: We'll exclude negative FIs here, which come from argument
  2418. // lowering, because there are no known test cases triggering this problem
  2419. // using packed structures (or similar). We can remove this exclusion if
  2420. // we find such a test case. The reason why this is so test-case driven is
  2421. // because this entire 'fixup' is only to prevent crashes (from the
  2422. // register scavenger) on not-really-valid inputs. For example, if we have:
  2423. // %a = alloca i1
  2424. // %b = bitcast i1* %a to i64*
  2425. // store i64* a, i64 b
  2426. // then the store should really be marked as 'align 1', but is not. If it
  2427. // were marked as 'align 1' then the indexed form would have been
  2428. // instruction-selected initially, and the problem this 'fixup' is preventing
  2429. // won't happen regardless.
  2430. if (FrameIdx < 0)
  2431. return;
  2432. MachineFunction &MF = DAG.getMachineFunction();
  2433. MachineFrameInfo &MFI = MF.getFrameInfo();
  2434. if (MFI.getObjectAlign(FrameIdx) >= Align(4))
  2435. return;
  2436. PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  2437. FuncInfo->setHasNonRISpills();
  2438. }
  2439. /// Returns true if the address N can be represented by a base register plus
  2440. /// a signed 16-bit displacement [r+imm], and if it is not better
  2441. /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept
  2442. /// displacements that are multiples of that value.
  2443. bool PPCTargetLowering::SelectAddressRegImm(
  2444. SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
  2445. MaybeAlign EncodingAlignment) const {
  2446. // FIXME dl should come from parent load or store, not from address
  2447. SDLoc dl(N);
  2448. // If we have a PC Relative target flag don't select as [reg+imm]. It will be
  2449. // a [pc+imm].
  2450. if (SelectAddressPCRel(N, Base))
  2451. return false;
  2452. // If this can be more profitably realized as r+r, fail.
  2453. if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
  2454. return false;
  2455. if (N.getOpcode() == ISD::ADD) {
  2456. int16_t imm = 0;
  2457. if (isIntS16Immediate(N.getOperand(1), imm) &&
  2458. (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
  2459. Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
  2460. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
  2461. Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
  2462. fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
  2463. } else {
  2464. Base = N.getOperand(0);
  2465. }
  2466. return true; // [r+i]
  2467. } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
  2468. // Match LOAD (ADD (X, Lo(G))).
  2469. assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
  2470. && "Cannot handle constant offsets yet!");
  2471. Disp = N.getOperand(1).getOperand(0); // The global address.
  2472. assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
  2473. Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
  2474. Disp.getOpcode() == ISD::TargetConstantPool ||
  2475. Disp.getOpcode() == ISD::TargetJumpTable);
  2476. Base = N.getOperand(0);
  2477. return true; // [&g+r]
  2478. }
  2479. } else if (N.getOpcode() == ISD::OR) {
  2480. int16_t imm = 0;
  2481. if (isIntS16Immediate(N.getOperand(1), imm) &&
  2482. (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
  2483. // If this is an or of disjoint bitfields, we can codegen this as an add
  2484. // (for better address arithmetic) if the LHS and RHS of the OR are
  2485. // provably disjoint.
  2486. KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
  2487. if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
  2488. // If all of the bits are known zero on the LHS or RHS, the add won't
  2489. // carry.
  2490. if (FrameIndexSDNode *FI =
  2491. dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
  2492. Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
  2493. fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
  2494. } else {
  2495. Base = N.getOperand(0);
  2496. }
  2497. Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
  2498. return true;
  2499. }
  2500. }
  2501. } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
  2502. // Loading from a constant address.
  2503. // If this address fits entirely in a 16-bit sext immediate field, codegen
  2504. // this as "d, 0"
  2505. int16_t Imm;
  2506. if (isIntS16Immediate(CN, Imm) &&
  2507. (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
  2508. Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
  2509. Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
  2510. CN->getValueType(0));
  2511. return true;
  2512. }
  2513. // Handle 32-bit sext immediates with LIS + addr mode.
  2514. if ((CN->getValueType(0) == MVT::i32 ||
  2515. (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
  2516. (!EncodingAlignment ||
  2517. isAligned(*EncodingAlignment, CN->getZExtValue()))) {
  2518. int Addr = (int)CN->getZExtValue();
  2519. // Otherwise, break this down into an LIS + disp.
  2520. Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
  2521. Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
  2522. MVT::i32);
  2523. unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
  2524. Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
  2525. return true;
  2526. }
  2527. }
  2528. Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
  2529. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
  2530. Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
  2531. fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
  2532. } else
  2533. Base = N;
  2534. return true; // [r+0]
  2535. }
  2536. /// Similar to the 16-bit case but for instructions that take a 34-bit
  2537. /// displacement field (prefixed loads/stores).
  2538. bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
  2539. SDValue &Base,
  2540. SelectionDAG &DAG) const {
  2541. // Only on 64-bit targets.
  2542. if (N.getValueType() != MVT::i64)
  2543. return false;
  2544. SDLoc dl(N);
  2545. int64_t Imm = 0;
  2546. if (N.getOpcode() == ISD::ADD) {
  2547. if (!isIntS34Immediate(N.getOperand(1), Imm))
  2548. return false;
  2549. Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
  2550. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
  2551. Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
  2552. else
  2553. Base = N.getOperand(0);
  2554. return true;
  2555. }
  2556. if (N.getOpcode() == ISD::OR) {
  2557. if (!isIntS34Immediate(N.getOperand(1), Imm))
  2558. return false;
  2559. // If this is an or of disjoint bitfields, we can codegen this as an add
  2560. // (for better address arithmetic) if the LHS and RHS of the OR are
  2561. // provably disjoint.
  2562. KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
  2563. if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
  2564. return false;
  2565. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
  2566. Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
  2567. else
  2568. Base = N.getOperand(0);
  2569. Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
  2570. return true;
  2571. }
  2572. if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
  2573. Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
  2574. Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
  2575. return true;
  2576. }
  2577. return false;
  2578. }
  2579. /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
  2580. /// represented as an indexed [r+r] operation.
  2581. bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
  2582. SDValue &Index,
  2583. SelectionDAG &DAG) const {
  2584. // Check to see if we can easily represent this as an [r+r] address. This
  2585. // will fail if it thinks that the address is more profitably represented as
  2586. // reg+imm, e.g. where imm = 0.
  2587. if (SelectAddressRegReg(N, Base, Index, DAG))
  2588. return true;
  2589. // If the address is the result of an add, we will utilize the fact that the
  2590. // address calculation includes an implicit add. However, we can reduce
  2591. // register pressure if we do not materialize a constant just for use as the
  2592. // index register. We only get rid of the add if it is not an add of a
  2593. // value and a 16-bit signed constant and both have a single use.
  2594. int16_t imm = 0;
  2595. if (N.getOpcode() == ISD::ADD &&
  2596. (!isIntS16Immediate(N.getOperand(1), imm) ||
  2597. !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
  2598. Base = N.getOperand(0);
  2599. Index = N.getOperand(1);
  2600. return true;
  2601. }
  2602. // Otherwise, do it the hard way, using R0 as the base register.
  2603. Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
  2604. N.getValueType());
  2605. Index = N;
  2606. return true;
  2607. }
  2608. template <typename Ty> static bool isValidPCRelNode(SDValue N) {
  2609. Ty *PCRelCand = dyn_cast<Ty>(N);
  2610. return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
  2611. }
  2612. /// Returns true if this address is a PC Relative address.
  2613. /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
  2614. /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
  2615. bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
  2616. // This is a materialize PC Relative node. Always select this as PC Relative.
  2617. Base = N;
  2618. if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
  2619. return true;
  2620. if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
  2621. isValidPCRelNode<GlobalAddressSDNode>(N) ||
  2622. isValidPCRelNode<JumpTableSDNode>(N) ||
  2623. isValidPCRelNode<BlockAddressSDNode>(N))
  2624. return true;
  2625. return false;
  2626. }
  2627. /// Returns true if we should use a direct load into vector instruction
  2628. /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
  2629. static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
  2630. // If there are any other uses other than scalar to vector, then we should
  2631. // keep it as a scalar load -> direct move pattern to prevent multiple
  2632. // loads.
  2633. LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
  2634. if (!LD)
  2635. return false;
  2636. EVT MemVT = LD->getMemoryVT();
  2637. if (!MemVT.isSimple())
  2638. return false;
  2639. switch(MemVT.getSimpleVT().SimpleTy) {
  2640. case MVT::i64:
  2641. break;
  2642. case MVT::i32:
  2643. if (!ST.hasP8Vector())
  2644. return false;
  2645. break;
  2646. case MVT::i16:
  2647. case MVT::i8:
  2648. if (!ST.hasP9Vector())
  2649. return false;
  2650. break;
  2651. default:
  2652. return false;
  2653. }
  2654. SDValue LoadedVal(N, 0);
  2655. if (!LoadedVal.hasOneUse())
  2656. return false;
  2657. for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
  2658. UI != UE; ++UI)
  2659. if (UI.getUse().get().getResNo() == 0 &&
  2660. UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
  2661. UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
  2662. return false;
  2663. return true;
  2664. }
  2665. /// getPreIndexedAddressParts - returns true by value, base pointer and
  2666. /// offset pointer and addressing mode by reference if the node's address
  2667. /// can be legally represented as pre-indexed load / store address.
  2668. bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
  2669. SDValue &Offset,
  2670. ISD::MemIndexedMode &AM,
  2671. SelectionDAG &DAG) const {
  2672. if (DisablePPCPreinc) return false;
  2673. bool isLoad = true;
  2674. SDValue Ptr;
  2675. EVT VT;
  2676. Align Alignment;
  2677. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
  2678. Ptr = LD->getBasePtr();
  2679. VT = LD->getMemoryVT();
  2680. Alignment = LD->getAlign();
  2681. } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
  2682. Ptr = ST->getBasePtr();
  2683. VT = ST->getMemoryVT();
  2684. Alignment = ST->getAlign();
  2685. isLoad = false;
  2686. } else
  2687. return false;
  2688. // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
  2689. // instructions because we can fold these into a more efficient instruction
  2690. // instead, (such as LXSD).
  2691. if (isLoad && usePartialVectorLoads(N, Subtarget)) {
  2692. return false;
  2693. }
  2694. // PowerPC doesn't have preinc load/store instructions for vectors
  2695. if (VT.isVector())
  2696. return false;
  2697. if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
  2698. // Common code will reject creating a pre-inc form if the base pointer
  2699. // is a frame index, or if N is a store and the base pointer is either
  2700. // the same as or a predecessor of the value being stored. Check for
  2701. // those situations here, and try with swapped Base/Offset instead.
  2702. bool Swap = false;
  2703. if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
  2704. Swap = true;
  2705. else if (!isLoad) {
  2706. SDValue Val = cast<StoreSDNode>(N)->getValue();
  2707. if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
  2708. Swap = true;
  2709. }
  2710. if (Swap)
  2711. std::swap(Base, Offset);
  2712. AM = ISD::PRE_INC;
  2713. return true;
  2714. }
  2715. // LDU/STU can only handle immediates that are a multiple of 4.
  2716. if (VT != MVT::i64) {
  2717. if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, std::nullopt))
  2718. return false;
  2719. } else {
  2720. // LDU/STU need an address with at least 4-byte alignment.
  2721. if (Alignment < Align(4))
  2722. return false;
  2723. if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
  2724. return false;
  2725. }
  2726. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
  2727. // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
  2728. // sext i32 to i64 when addr mode is r+i.
  2729. if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
  2730. LD->getExtensionType() == ISD::SEXTLOAD &&
  2731. isa<ConstantSDNode>(Offset))
  2732. return false;
  2733. }
  2734. AM = ISD::PRE_INC;
  2735. return true;
  2736. }
  2737. //===----------------------------------------------------------------------===//
  2738. // LowerOperation implementation
  2739. //===----------------------------------------------------------------------===//
  2740. /// Return true if we should reference labels using a PICBase, set the HiOpFlags
  2741. /// and LoOpFlags to the target MO flags.
  2742. static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
  2743. unsigned &HiOpFlags, unsigned &LoOpFlags,
  2744. const GlobalValue *GV = nullptr) {
  2745. HiOpFlags = PPCII::MO_HA;
  2746. LoOpFlags = PPCII::MO_LO;
  2747. // Don't use the pic base if not in PIC relocation model.
  2748. if (IsPIC) {
  2749. HiOpFlags |= PPCII::MO_PIC_FLAG;
  2750. LoOpFlags |= PPCII::MO_PIC_FLAG;
  2751. }
  2752. }
  2753. static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
  2754. SelectionDAG &DAG) {
  2755. SDLoc DL(HiPart);
  2756. EVT PtrVT = HiPart.getValueType();
  2757. SDValue Zero = DAG.getConstant(0, DL, PtrVT);
  2758. SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
  2759. SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
  2760. // With PIC, the first instruction is actually "GR+hi(&G)".
  2761. if (isPIC)
  2762. Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
  2763. DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
  2764. // Generate non-pic code that has direct accesses to the constant pool.
  2765. // The address of the global is just (hi(&g)+lo(&g)).
  2766. return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
  2767. }
  2768. static void setUsesTOCBasePtr(MachineFunction &MF) {
  2769. PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  2770. FuncInfo->setUsesTOCBasePtr();
  2771. }
  2772. static void setUsesTOCBasePtr(SelectionDAG &DAG) {
  2773. setUsesTOCBasePtr(DAG.getMachineFunction());
  2774. }
  2775. SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
  2776. SDValue GA) const {
  2777. const bool Is64Bit = Subtarget.isPPC64();
  2778. EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
  2779. SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
  2780. : Subtarget.isAIXABI()
  2781. ? DAG.getRegister(PPC::R2, VT)
  2782. : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
  2783. SDValue Ops[] = { GA, Reg };
  2784. return DAG.getMemIntrinsicNode(
  2785. PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
  2786. MachinePointerInfo::getGOT(DAG.getMachineFunction()), std::nullopt,
  2787. MachineMemOperand::MOLoad);
  2788. }
  2789. SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
  2790. SelectionDAG &DAG) const {
  2791. EVT PtrVT = Op.getValueType();
  2792. ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
  2793. const Constant *C = CP->getConstVal();
  2794. // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
  2795. // The actual address of the GlobalValue is stored in the TOC.
  2796. if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
  2797. if (Subtarget.isUsingPCRelativeCalls()) {
  2798. SDLoc DL(CP);
  2799. EVT Ty = getPointerTy(DAG.getDataLayout());
  2800. SDValue ConstPool = DAG.getTargetConstantPool(
  2801. C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
  2802. return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
  2803. }
  2804. setUsesTOCBasePtr(DAG);
  2805. SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
  2806. return getTOCEntry(DAG, SDLoc(CP), GA);
  2807. }
  2808. unsigned MOHiFlag, MOLoFlag;
  2809. bool IsPIC = isPositionIndependent();
  2810. getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
  2811. if (IsPIC && Subtarget.isSVR4ABI()) {
  2812. SDValue GA =
  2813. DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
  2814. return getTOCEntry(DAG, SDLoc(CP), GA);
  2815. }
  2816. SDValue CPIHi =
  2817. DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
  2818. SDValue CPILo =
  2819. DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
  2820. return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
  2821. }
  2822. // For 64-bit PowerPC, prefer the more compact relative encodings.
  2823. // This trades 32 bits per jump table entry for one or two instructions
  2824. // on the jump site.
  2825. unsigned PPCTargetLowering::getJumpTableEncoding() const {
  2826. if (isJumpTableRelative())
  2827. return MachineJumpTableInfo::EK_LabelDifference32;
  2828. return TargetLowering::getJumpTableEncoding();
  2829. }
  2830. bool PPCTargetLowering::isJumpTableRelative() const {
  2831. if (UseAbsoluteJumpTables)
  2832. return false;
  2833. if (Subtarget.isPPC64() || Subtarget.isAIXABI())
  2834. return true;
  2835. return TargetLowering::isJumpTableRelative();
  2836. }
  2837. SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
  2838. SelectionDAG &DAG) const {
  2839. if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
  2840. return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
  2841. switch (getTargetMachine().getCodeModel()) {
  2842. case CodeModel::Small:
  2843. case CodeModel::Medium:
  2844. return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
  2845. default:
  2846. return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
  2847. getPointerTy(DAG.getDataLayout()));
  2848. }
  2849. }
  2850. const MCExpr *
  2851. PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
  2852. unsigned JTI,
  2853. MCContext &Ctx) const {
  2854. if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
  2855. return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
  2856. switch (getTargetMachine().getCodeModel()) {
  2857. case CodeModel::Small:
  2858. case CodeModel::Medium:
  2859. return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
  2860. default:
  2861. return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
  2862. }
  2863. }
  2864. SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
  2865. EVT PtrVT = Op.getValueType();
  2866. JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
  2867. // isUsingPCRelativeCalls() returns true when PCRelative is enabled
  2868. if (Subtarget.isUsingPCRelativeCalls()) {
  2869. SDLoc DL(JT);
  2870. EVT Ty = getPointerTy(DAG.getDataLayout());
  2871. SDValue GA =
  2872. DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
  2873. SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
  2874. return MatAddr;
  2875. }
  2876. // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
  2877. // The actual address of the GlobalValue is stored in the TOC.
  2878. if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
  2879. setUsesTOCBasePtr(DAG);
  2880. SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
  2881. return getTOCEntry(DAG, SDLoc(JT), GA);
  2882. }
  2883. unsigned MOHiFlag, MOLoFlag;
  2884. bool IsPIC = isPositionIndependent();
  2885. getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
  2886. if (IsPIC && Subtarget.isSVR4ABI()) {
  2887. SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
  2888. PPCII::MO_PIC_FLAG);
  2889. return getTOCEntry(DAG, SDLoc(GA), GA);
  2890. }
  2891. SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
  2892. SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
  2893. return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
  2894. }
  2895. SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
  2896. SelectionDAG &DAG) const {
  2897. EVT PtrVT = Op.getValueType();
  2898. BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
  2899. const BlockAddress *BA = BASDN->getBlockAddress();
  2900. // isUsingPCRelativeCalls() returns true when PCRelative is enabled
  2901. if (Subtarget.isUsingPCRelativeCalls()) {
  2902. SDLoc DL(BASDN);
  2903. EVT Ty = getPointerTy(DAG.getDataLayout());
  2904. SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
  2905. PPCII::MO_PCREL_FLAG);
  2906. SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
  2907. return MatAddr;
  2908. }
  2909. // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
  2910. // The actual BlockAddress is stored in the TOC.
  2911. if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
  2912. setUsesTOCBasePtr(DAG);
  2913. SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
  2914. return getTOCEntry(DAG, SDLoc(BASDN), GA);
  2915. }
  2916. // 32-bit position-independent ELF stores the BlockAddress in the .got.
  2917. if (Subtarget.is32BitELFABI() && isPositionIndependent())
  2918. return getTOCEntry(
  2919. DAG, SDLoc(BASDN),
  2920. DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
  2921. unsigned MOHiFlag, MOLoFlag;
  2922. bool IsPIC = isPositionIndependent();
  2923. getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
  2924. SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
  2925. SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
  2926. return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
  2927. }
  2928. SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
  2929. SelectionDAG &DAG) const {
  2930. if (Subtarget.isAIXABI())
  2931. return LowerGlobalTLSAddressAIX(Op, DAG);
  2932. return LowerGlobalTLSAddressLinux(Op, DAG);
  2933. }
  2934. SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
  2935. SelectionDAG &DAG) const {
  2936. GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
  2937. if (DAG.getTarget().useEmulatedTLS())
  2938. report_fatal_error("Emulated TLS is not yet supported on AIX");
  2939. SDLoc dl(GA);
  2940. const GlobalValue *GV = GA->getGlobal();
  2941. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  2942. // The general-dynamic model is the only access model supported for now, so
  2943. // all the GlobalTLSAddress nodes are lowered with this model.
  2944. // We need to generate two TOC entries, one for the variable offset, one for
  2945. // the region handle. The global address for the TOC entry of the region
  2946. // handle is created with the MO_TLSGDM_FLAG flag and the global address
  2947. // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG.
  2948. SDValue VariableOffsetTGA =
  2949. DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
  2950. SDValue RegionHandleTGA =
  2951. DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
  2952. SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
  2953. SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
  2954. return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
  2955. RegionHandle);
  2956. }
  2957. SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
  2958. SelectionDAG &DAG) const {
  2959. // FIXME: TLS addresses currently use medium model code sequences,
  2960. // which is the most useful form. Eventually support for small and
  2961. // large models could be added if users need it, at the cost of
  2962. // additional complexity.
  2963. GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
  2964. if (DAG.getTarget().useEmulatedTLS())
  2965. return LowerToTLSEmulatedModel(GA, DAG);
  2966. SDLoc dl(GA);
  2967. const GlobalValue *GV = GA->getGlobal();
  2968. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  2969. bool is64bit = Subtarget.isPPC64();
  2970. const Module *M = DAG.getMachineFunction().getFunction().getParent();
  2971. PICLevel::Level picLevel = M->getPICLevel();
  2972. const TargetMachine &TM = getTargetMachine();
  2973. TLSModel::Model Model = TM.getTLSModel(GV);
  2974. if (Model == TLSModel::LocalExec) {
  2975. if (Subtarget.isUsingPCRelativeCalls()) {
  2976. SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
  2977. SDValue TGA = DAG.getTargetGlobalAddress(
  2978. GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
  2979. SDValue MatAddr =
  2980. DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
  2981. return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
  2982. }
  2983. SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
  2984. PPCII::MO_TPREL_HA);
  2985. SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
  2986. PPCII::MO_TPREL_LO);
  2987. SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
  2988. : DAG.getRegister(PPC::R2, MVT::i32);
  2989. SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
  2990. return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
  2991. }
  2992. if (Model == TLSModel::InitialExec) {
  2993. bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
  2994. SDValue TGA = DAG.getTargetGlobalAddress(
  2995. GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
  2996. SDValue TGATLS = DAG.getTargetGlobalAddress(
  2997. GV, dl, PtrVT, 0,
  2998. IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
  2999. SDValue TPOffset;
  3000. if (IsPCRel) {
  3001. SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
  3002. TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
  3003. MachinePointerInfo());
  3004. } else {
  3005. SDValue GOTPtr;
  3006. if (is64bit) {
  3007. setUsesTOCBasePtr(DAG);
  3008. SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
  3009. GOTPtr =
  3010. DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
  3011. } else {
  3012. if (!TM.isPositionIndependent())
  3013. GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
  3014. else if (picLevel == PICLevel::SmallPIC)
  3015. GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
  3016. else
  3017. GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
  3018. }
  3019. TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
  3020. }
  3021. return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
  3022. }
  3023. if (Model == TLSModel::GeneralDynamic) {
  3024. if (Subtarget.isUsingPCRelativeCalls()) {
  3025. SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
  3026. PPCII::MO_GOT_TLSGD_PCREL_FLAG);
  3027. return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
  3028. }
  3029. SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
  3030. SDValue GOTPtr;
  3031. if (is64bit) {
  3032. setUsesTOCBasePtr(DAG);
  3033. SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
  3034. GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
  3035. GOTReg, TGA);
  3036. } else {
  3037. if (picLevel == PICLevel::SmallPIC)
  3038. GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
  3039. else
  3040. GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
  3041. }
  3042. return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
  3043. GOTPtr, TGA, TGA);
  3044. }
  3045. if (Model == TLSModel::LocalDynamic) {
  3046. if (Subtarget.isUsingPCRelativeCalls()) {
  3047. SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
  3048. PPCII::MO_GOT_TLSLD_PCREL_FLAG);
  3049. SDValue MatPCRel =
  3050. DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
  3051. return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
  3052. }
  3053. SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
  3054. SDValue GOTPtr;
  3055. if (is64bit) {
  3056. setUsesTOCBasePtr(DAG);
  3057. SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
  3058. GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
  3059. GOTReg, TGA);
  3060. } else {
  3061. if (picLevel == PICLevel::SmallPIC)
  3062. GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
  3063. else
  3064. GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
  3065. }
  3066. SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
  3067. PtrVT, GOTPtr, TGA, TGA);
  3068. SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
  3069. PtrVT, TLSAddr, TGA);
  3070. return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
  3071. }
  3072. llvm_unreachable("Unknown TLS model!");
  3073. }
  3074. SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
  3075. SelectionDAG &DAG) const {
  3076. EVT PtrVT = Op.getValueType();
  3077. GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
  3078. SDLoc DL(GSDN);
  3079. const GlobalValue *GV = GSDN->getGlobal();
  3080. // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
  3081. // The actual address of the GlobalValue is stored in the TOC.
  3082. if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
  3083. if (Subtarget.isUsingPCRelativeCalls()) {
  3084. EVT Ty = getPointerTy(DAG.getDataLayout());
  3085. if (isAccessedAsGotIndirect(Op)) {
  3086. SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
  3087. PPCII::MO_PCREL_FLAG |
  3088. PPCII::MO_GOT_FLAG);
  3089. SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
  3090. SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
  3091. MachinePointerInfo());
  3092. return Load;
  3093. } else {
  3094. SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
  3095. PPCII::MO_PCREL_FLAG);
  3096. return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
  3097. }
  3098. }
  3099. setUsesTOCBasePtr(DAG);
  3100. SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
  3101. return getTOCEntry(DAG, DL, GA);
  3102. }
  3103. unsigned MOHiFlag, MOLoFlag;
  3104. bool IsPIC = isPositionIndependent();
  3105. getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
  3106. if (IsPIC && Subtarget.isSVR4ABI()) {
  3107. SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
  3108. GSDN->getOffset(),
  3109. PPCII::MO_PIC_FLAG);
  3110. return getTOCEntry(DAG, DL, GA);
  3111. }
  3112. SDValue GAHi =
  3113. DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
  3114. SDValue GALo =
  3115. DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
  3116. return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
  3117. }
  3118. SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
  3119. bool IsStrict = Op->isStrictFPOpcode();
  3120. ISD::CondCode CC =
  3121. cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
  3122. SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
  3123. SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
  3124. SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
  3125. EVT LHSVT = LHS.getValueType();
  3126. SDLoc dl(Op);
  3127. // Soften the setcc with libcall if it is fp128.
  3128. if (LHSVT == MVT::f128) {
  3129. assert(!Subtarget.hasP9Vector() &&
  3130. "SETCC for f128 is already legal under Power9!");
  3131. softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
  3132. Op->getOpcode() == ISD::STRICT_FSETCCS);
  3133. if (RHS.getNode())
  3134. LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
  3135. DAG.getCondCode(CC));
  3136. if (IsStrict)
  3137. return DAG.getMergeValues({LHS, Chain}, dl);
  3138. return LHS;
  3139. }
  3140. assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!");
  3141. if (Op.getValueType() == MVT::v2i64) {
  3142. // When the operands themselves are v2i64 values, we need to do something
  3143. // special because VSX has no underlying comparison operations for these.
  3144. if (LHS.getValueType() == MVT::v2i64) {
  3145. // Equality can be handled by casting to the legal type for Altivec
  3146. // comparisons, everything else needs to be expanded.
  3147. if (CC != ISD::SETEQ && CC != ISD::SETNE)
  3148. return SDValue();
  3149. SDValue SetCC32 = DAG.getSetCC(
  3150. dl, MVT::v4i32, DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS),
  3151. DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC);
  3152. int ShuffV[] = {1, 0, 3, 2};
  3153. SDValue Shuff =
  3154. DAG.getVectorShuffle(MVT::v4i32, dl, SetCC32, SetCC32, ShuffV);
  3155. return DAG.getBitcast(MVT::v2i64,
  3156. DAG.getNode(CC == ISD::SETEQ ? ISD::AND : ISD::OR,
  3157. dl, MVT::v4i32, Shuff, SetCC32));
  3158. }
  3159. // We handle most of these in the usual way.
  3160. return Op;
  3161. }
  3162. // If we're comparing for equality to zero, expose the fact that this is
  3163. // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
  3164. // fold the new nodes.
  3165. if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
  3166. return V;
  3167. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
  3168. // Leave comparisons against 0 and -1 alone for now, since they're usually
  3169. // optimized. FIXME: revisit this when we can custom lower all setcc
  3170. // optimizations.
  3171. if (C->isAllOnes() || C->isZero())
  3172. return SDValue();
  3173. }
  3174. // If we have an integer seteq/setne, turn it into a compare against zero
  3175. // by xor'ing the rhs with the lhs, which is faster than setting a
  3176. // condition register, reading it back out, and masking the correct bit. The
  3177. // normal approach here uses sub to do this instead of xor. Using xor exposes
  3178. // the result to other bit-twiddling opportunities.
  3179. if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
  3180. EVT VT = Op.getValueType();
  3181. SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS);
  3182. return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
  3183. }
  3184. return SDValue();
  3185. }
  3186. SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
  3187. SDNode *Node = Op.getNode();
  3188. EVT VT = Node->getValueType(0);
  3189. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  3190. SDValue InChain = Node->getOperand(0);
  3191. SDValue VAListPtr = Node->getOperand(1);
  3192. const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
  3193. SDLoc dl(Node);
  3194. assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
  3195. // gpr_index
  3196. SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
  3197. VAListPtr, MachinePointerInfo(SV), MVT::i8);
  3198. InChain = GprIndex.getValue(1);
  3199. if (VT == MVT::i64) {
  3200. // Check if GprIndex is even
  3201. SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
  3202. DAG.getConstant(1, dl, MVT::i32));
  3203. SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
  3204. DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
  3205. SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
  3206. DAG.getConstant(1, dl, MVT::i32));
  3207. // Align GprIndex to be even if it isn't
  3208. GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
  3209. GprIndex);
  3210. }
  3211. // fpr index is 1 byte after gpr
  3212. SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
  3213. DAG.getConstant(1, dl, MVT::i32));
  3214. // fpr
  3215. SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
  3216. FprPtr, MachinePointerInfo(SV), MVT::i8);
  3217. InChain = FprIndex.getValue(1);
  3218. SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
  3219. DAG.getConstant(8, dl, MVT::i32));
  3220. SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
  3221. DAG.getConstant(4, dl, MVT::i32));
  3222. // areas
  3223. SDValue OverflowArea =
  3224. DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
  3225. InChain = OverflowArea.getValue(1);
  3226. SDValue RegSaveArea =
  3227. DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
  3228. InChain = RegSaveArea.getValue(1);
  3229. // select overflow_area if index > 8
  3230. SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
  3231. DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
  3232. // adjustment constant gpr_index * 4/8
  3233. SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
  3234. VT.isInteger() ? GprIndex : FprIndex,
  3235. DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
  3236. MVT::i32));
  3237. // OurReg = RegSaveArea + RegConstant
  3238. SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
  3239. RegConstant);
  3240. // Floating types are 32 bytes into RegSaveArea
  3241. if (VT.isFloatingPoint())
  3242. OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
  3243. DAG.getConstant(32, dl, MVT::i32));
  3244. // increase {f,g}pr_index by 1 (or 2 if VT is i64)
  3245. SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
  3246. VT.isInteger() ? GprIndex : FprIndex,
  3247. DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
  3248. MVT::i32));
  3249. InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
  3250. VT.isInteger() ? VAListPtr : FprPtr,
  3251. MachinePointerInfo(SV), MVT::i8);
  3252. // determine if we should load from reg_save_area or overflow_area
  3253. SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
  3254. // increase overflow_area by 4/8 if gpr/fpr > 8
  3255. SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
  3256. DAG.getConstant(VT.isInteger() ? 4 : 8,
  3257. dl, MVT::i32));
  3258. OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
  3259. OverflowAreaPlusN);
  3260. InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
  3261. MachinePointerInfo(), MVT::i32);
  3262. return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
  3263. }
  3264. SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
  3265. assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
  3266. // We have to copy the entire va_list struct:
  3267. // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
  3268. return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
  3269. DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
  3270. false, true, false, MachinePointerInfo(),
  3271. MachinePointerInfo());
  3272. }
  3273. SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
  3274. SelectionDAG &DAG) const {
  3275. if (Subtarget.isAIXABI())
  3276. report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
  3277. return Op.getOperand(0);
  3278. }
  3279. SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
  3280. MachineFunction &MF = DAG.getMachineFunction();
  3281. PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>();
  3282. assert((Op.getOpcode() == ISD::INLINEASM ||
  3283. Op.getOpcode() == ISD::INLINEASM_BR) &&
  3284. "Expecting Inline ASM node.");
  3285. // If an LR store is already known to be required then there is not point in
  3286. // checking this ASM as well.
  3287. if (MFI.isLRStoreRequired())
  3288. return Op;
  3289. // Inline ASM nodes have an optional last operand that is an incoming Flag of
  3290. // type MVT::Glue. We want to ignore this last operand if that is the case.
  3291. unsigned NumOps = Op.getNumOperands();
  3292. if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue)
  3293. --NumOps;
  3294. // Check all operands that may contain the LR.
  3295. for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
  3296. unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue();
  3297. unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
  3298. ++i; // Skip the ID value.
  3299. switch (InlineAsm::getKind(Flags)) {
  3300. default:
  3301. llvm_unreachable("Bad flags!");
  3302. case InlineAsm::Kind_RegUse:
  3303. case InlineAsm::Kind_Imm:
  3304. case InlineAsm::Kind_Mem:
  3305. i += NumVals;
  3306. break;
  3307. case InlineAsm::Kind_Clobber:
  3308. case InlineAsm::Kind_RegDef:
  3309. case InlineAsm::Kind_RegDefEarlyClobber: {
  3310. for (; NumVals; --NumVals, ++i) {
  3311. Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
  3312. if (Reg != PPC::LR && Reg != PPC::LR8)
  3313. continue;
  3314. MFI.setLRStoreRequired();
  3315. return Op;
  3316. }
  3317. break;
  3318. }
  3319. }
  3320. }
  3321. return Op;
  3322. }
  3323. SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
  3324. SelectionDAG &DAG) const {
  3325. if (Subtarget.isAIXABI())
  3326. report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
  3327. SDValue Chain = Op.getOperand(0);
  3328. SDValue Trmp = Op.getOperand(1); // trampoline
  3329. SDValue FPtr = Op.getOperand(2); // nested function
  3330. SDValue Nest = Op.getOperand(3); // 'nest' parameter value
  3331. SDLoc dl(Op);
  3332. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  3333. bool isPPC64 = (PtrVT == MVT::i64);
  3334. Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
  3335. TargetLowering::ArgListTy Args;
  3336. TargetLowering::ArgListEntry Entry;
  3337. Entry.Ty = IntPtrTy;
  3338. Entry.Node = Trmp; Args.push_back(Entry);
  3339. // TrampSize == (isPPC64 ? 48 : 40);
  3340. Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
  3341. isPPC64 ? MVT::i64 : MVT::i32);
  3342. Args.push_back(Entry);
  3343. Entry.Node = FPtr; Args.push_back(Entry);
  3344. Entry.Node = Nest; Args.push_back(Entry);
  3345. // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
  3346. TargetLowering::CallLoweringInfo CLI(DAG);
  3347. CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
  3348. CallingConv::C, Type::getVoidTy(*DAG.getContext()),
  3349. DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
  3350. std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
  3351. return CallResult.second;
  3352. }
  3353. SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
  3354. MachineFunction &MF = DAG.getMachineFunction();
  3355. PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  3356. EVT PtrVT = getPointerTy(MF.getDataLayout());
  3357. SDLoc dl(Op);
  3358. if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
  3359. // vastart just stores the address of the VarArgsFrameIndex slot into the
  3360. // memory location argument.
  3361. SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
  3362. const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
  3363. return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
  3364. MachinePointerInfo(SV));
  3365. }
  3366. // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
  3367. // We suppose the given va_list is already allocated.
  3368. //
  3369. // typedef struct {
  3370. // char gpr; /* index into the array of 8 GPRs
  3371. // * stored in the register save area
  3372. // * gpr=0 corresponds to r3,
  3373. // * gpr=1 to r4, etc.
  3374. // */
  3375. // char fpr; /* index into the array of 8 FPRs
  3376. // * stored in the register save area
  3377. // * fpr=0 corresponds to f1,
  3378. // * fpr=1 to f2, etc.
  3379. // */
  3380. // char *overflow_arg_area;
  3381. // /* location on stack that holds
  3382. // * the next overflow argument
  3383. // */
  3384. // char *reg_save_area;
  3385. // /* where r3:r10 and f1:f8 (if saved)
  3386. // * are stored
  3387. // */
  3388. // } va_list[1];
  3389. SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
  3390. SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
  3391. SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
  3392. PtrVT);
  3393. SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
  3394. PtrVT);
  3395. uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
  3396. SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
  3397. uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
  3398. SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
  3399. uint64_t FPROffset = 1;
  3400. SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
  3401. const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
  3402. // Store first byte : number of int regs
  3403. SDValue firstStore =
  3404. DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
  3405. MachinePointerInfo(SV), MVT::i8);
  3406. uint64_t nextOffset = FPROffset;
  3407. SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
  3408. ConstFPROffset);
  3409. // Store second byte : number of float regs
  3410. SDValue secondStore =
  3411. DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
  3412. MachinePointerInfo(SV, nextOffset), MVT::i8);
  3413. nextOffset += StackOffset;
  3414. nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
  3415. // Store second word : arguments given on stack
  3416. SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
  3417. MachinePointerInfo(SV, nextOffset));
  3418. nextOffset += FrameOffset;
  3419. nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
  3420. // Store third word : arguments given in registers
  3421. return DAG.getStore(thirdStore, dl, FR, nextPtr,
  3422. MachinePointerInfo(SV, nextOffset));
  3423. }
  3424. /// FPR - The set of FP registers that should be allocated for arguments
  3425. /// on Darwin and AIX.
  3426. static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
  3427. PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
  3428. PPC::F11, PPC::F12, PPC::F13};
  3429. /// CalculateStackSlotSize - Calculates the size reserved for this argument on
  3430. /// the stack.
  3431. static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
  3432. unsigned PtrByteSize) {
  3433. unsigned ArgSize = ArgVT.getStoreSize();
  3434. if (Flags.isByVal())
  3435. ArgSize = Flags.getByValSize();
  3436. // Round up to multiples of the pointer size, except for array members,
  3437. // which are always packed.
  3438. if (!Flags.isInConsecutiveRegs())
  3439. ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
  3440. return ArgSize;
  3441. }
  3442. /// CalculateStackSlotAlignment - Calculates the alignment of this argument
  3443. /// on the stack.
  3444. static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
  3445. ISD::ArgFlagsTy Flags,
  3446. unsigned PtrByteSize) {
  3447. Align Alignment(PtrByteSize);
  3448. // Altivec parameters are padded to a 16 byte boundary.
  3449. if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
  3450. ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
  3451. ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
  3452. ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
  3453. Alignment = Align(16);
  3454. // ByVal parameters are aligned as requested.
  3455. if (Flags.isByVal()) {
  3456. auto BVAlign = Flags.getNonZeroByValAlign();
  3457. if (BVAlign > PtrByteSize) {
  3458. if (BVAlign.value() % PtrByteSize != 0)
  3459. llvm_unreachable(
  3460. "ByVal alignment is not a multiple of the pointer size");
  3461. Alignment = BVAlign;
  3462. }
  3463. }
  3464. // Array members are always packed to their original alignment.
  3465. if (Flags.isInConsecutiveRegs()) {
  3466. // If the array member was split into multiple registers, the first
  3467. // needs to be aligned to the size of the full type. (Except for
  3468. // ppcf128, which is only aligned as its f64 components.)
  3469. if (Flags.isSplit() && OrigVT != MVT::ppcf128)
  3470. Alignment = Align(OrigVT.getStoreSize());
  3471. else
  3472. Alignment = Align(ArgVT.getStoreSize());
  3473. }
  3474. return Alignment;
  3475. }
  3476. /// CalculateStackSlotUsed - Return whether this argument will use its
  3477. /// stack slot (instead of being passed in registers). ArgOffset,
  3478. /// AvailableFPRs, and AvailableVRs must hold the current argument
  3479. /// position, and will be updated to account for this argument.
  3480. static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
  3481. unsigned PtrByteSize, unsigned LinkageSize,
  3482. unsigned ParamAreaSize, unsigned &ArgOffset,
  3483. unsigned &AvailableFPRs,
  3484. unsigned &AvailableVRs) {
  3485. bool UseMemory = false;
  3486. // Respect alignment of argument on the stack.
  3487. Align Alignment =
  3488. CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
  3489. ArgOffset = alignTo(ArgOffset, Alignment);
  3490. // If there's no space left in the argument save area, we must
  3491. // use memory (this check also catches zero-sized arguments).
  3492. if (ArgOffset >= LinkageSize + ParamAreaSize)
  3493. UseMemory = true;
  3494. // Allocate argument on the stack.
  3495. ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
  3496. if (Flags.isInConsecutiveRegsLast())
  3497. ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
  3498. // If we overran the argument save area, we must use memory
  3499. // (this check catches arguments passed partially in memory)
  3500. if (ArgOffset > LinkageSize + ParamAreaSize)
  3501. UseMemory = true;
  3502. // However, if the argument is actually passed in an FPR or a VR,
  3503. // we don't use memory after all.
  3504. if (!Flags.isByVal()) {
  3505. if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
  3506. if (AvailableFPRs > 0) {
  3507. --AvailableFPRs;
  3508. return false;
  3509. }
  3510. if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
  3511. ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
  3512. ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
  3513. ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
  3514. if (AvailableVRs > 0) {
  3515. --AvailableVRs;
  3516. return false;
  3517. }
  3518. }
  3519. return UseMemory;
  3520. }
  3521. /// EnsureStackAlignment - Round stack frame size up from NumBytes to
  3522. /// ensure minimum alignment required for target.
  3523. static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
  3524. unsigned NumBytes) {
  3525. return alignTo(NumBytes, Lowering->getStackAlign());
  3526. }
  3527. SDValue PPCTargetLowering::LowerFormalArguments(
  3528. SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
  3529. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
  3530. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
  3531. if (Subtarget.isAIXABI())
  3532. return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
  3533. InVals);
  3534. if (Subtarget.is64BitELFABI())
  3535. return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
  3536. InVals);
  3537. assert(Subtarget.is32BitELFABI());
  3538. return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
  3539. InVals);
  3540. }
  3541. SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
  3542. SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
  3543. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
  3544. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
  3545. // 32-bit SVR4 ABI Stack Frame Layout:
  3546. // +-----------------------------------+
  3547. // +--> | Back chain |
  3548. // | +-----------------------------------+
  3549. // | | Floating-point register save area |
  3550. // | +-----------------------------------+
  3551. // | | General register save area |
  3552. // | +-----------------------------------+
  3553. // | | CR save word |
  3554. // | +-----------------------------------+
  3555. // | | VRSAVE save word |
  3556. // | +-----------------------------------+
  3557. // | | Alignment padding |
  3558. // | +-----------------------------------+
  3559. // | | Vector register save area |
  3560. // | +-----------------------------------+
  3561. // | | Local variable space |
  3562. // | +-----------------------------------+
  3563. // | | Parameter list area |
  3564. // | +-----------------------------------+
  3565. // | | LR save word |
  3566. // | +-----------------------------------+
  3567. // SP--> +--- | Back chain |
  3568. // +-----------------------------------+
  3569. //
  3570. // Specifications:
  3571. // System V Application Binary Interface PowerPC Processor Supplement
  3572. // AltiVec Technology Programming Interface Manual
  3573. MachineFunction &MF = DAG.getMachineFunction();
  3574. MachineFrameInfo &MFI = MF.getFrameInfo();
  3575. PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  3576. EVT PtrVT = getPointerTy(MF.getDataLayout());
  3577. // Potential tail calls could cause overwriting of argument stack slots.
  3578. bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
  3579. (CallConv == CallingConv::Fast));
  3580. const Align PtrAlign(4);
  3581. // Assign locations to all of the incoming arguments.
  3582. SmallVector<CCValAssign, 16> ArgLocs;
  3583. PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
  3584. *DAG.getContext());
  3585. // Reserve space for the linkage area on the stack.
  3586. unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
  3587. CCInfo.AllocateStack(LinkageSize, PtrAlign);
  3588. if (useSoftFloat())
  3589. CCInfo.PreAnalyzeFormalArguments(Ins);
  3590. CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
  3591. CCInfo.clearWasPPCF128();
  3592. for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
  3593. CCValAssign &VA = ArgLocs[i];
  3594. // Arguments stored in registers.
  3595. if (VA.isRegLoc()) {
  3596. const TargetRegisterClass *RC;
  3597. EVT ValVT = VA.getValVT();
  3598. switch (ValVT.getSimpleVT().SimpleTy) {
  3599. default:
  3600. llvm_unreachable("ValVT not supported by formal arguments Lowering");
  3601. case MVT::i1:
  3602. case MVT::i32:
  3603. RC = &PPC::GPRCRegClass;
  3604. break;
  3605. case MVT::f32:
  3606. if (Subtarget.hasP8Vector())
  3607. RC = &PPC::VSSRCRegClass;
  3608. else if (Subtarget.hasSPE())
  3609. RC = &PPC::GPRCRegClass;
  3610. else
  3611. RC = &PPC::F4RCRegClass;
  3612. break;
  3613. case MVT::f64:
  3614. if (Subtarget.hasVSX())
  3615. RC = &PPC::VSFRCRegClass;
  3616. else if (Subtarget.hasSPE())
  3617. // SPE passes doubles in GPR pairs.
  3618. RC = &PPC::GPRCRegClass;
  3619. else
  3620. RC = &PPC::F8RCRegClass;
  3621. break;
  3622. case MVT::v16i8:
  3623. case MVT::v8i16:
  3624. case MVT::v4i32:
  3625. RC = &PPC::VRRCRegClass;
  3626. break;
  3627. case MVT::v4f32:
  3628. RC = &PPC::VRRCRegClass;
  3629. break;
  3630. case MVT::v2f64:
  3631. case MVT::v2i64:
  3632. RC = &PPC::VRRCRegClass;
  3633. break;
  3634. }
  3635. SDValue ArgValue;
  3636. // Transform the arguments stored in physical registers into
  3637. // virtual ones.
  3638. if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
  3639. assert(i + 1 < e && "No second half of double precision argument");
  3640. Register RegLo = MF.addLiveIn(VA.getLocReg(), RC);
  3641. Register RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
  3642. SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
  3643. SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
  3644. if (!Subtarget.isLittleEndian())
  3645. std::swap (ArgValueLo, ArgValueHi);
  3646. ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
  3647. ArgValueHi);
  3648. } else {
  3649. Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
  3650. ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
  3651. ValVT == MVT::i1 ? MVT::i32 : ValVT);
  3652. if (ValVT == MVT::i1)
  3653. ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
  3654. }
  3655. InVals.push_back(ArgValue);
  3656. } else {
  3657. // Argument stored in memory.
  3658. assert(VA.isMemLoc());
  3659. // Get the extended size of the argument type in stack
  3660. unsigned ArgSize = VA.getLocVT().getStoreSize();
  3661. // Get the actual size of the argument type
  3662. unsigned ObjSize = VA.getValVT().getStoreSize();
  3663. unsigned ArgOffset = VA.getLocMemOffset();
  3664. // Stack objects in PPC32 are right justified.
  3665. ArgOffset += ArgSize - ObjSize;
  3666. int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
  3667. // Create load nodes to retrieve arguments from the stack.
  3668. SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
  3669. InVals.push_back(
  3670. DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
  3671. }
  3672. }
  3673. // Assign locations to all of the incoming aggregate by value arguments.
  3674. // Aggregates passed by value are stored in the local variable space of the
  3675. // caller's stack frame, right above the parameter list area.
  3676. SmallVector<CCValAssign, 16> ByValArgLocs;
  3677. CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
  3678. ByValArgLocs, *DAG.getContext());
  3679. // Reserve stack space for the allocations in CCInfo.
  3680. CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
  3681. CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
  3682. // Area that is at least reserved in the caller of this function.
  3683. unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
  3684. MinReservedArea = std::max(MinReservedArea, LinkageSize);
  3685. // Set the size that is at least reserved in caller of this function. Tail
  3686. // call optimized function's reserved stack space needs to be aligned so that
  3687. // taking the difference between two stack areas will result in an aligned
  3688. // stack.
  3689. MinReservedArea =
  3690. EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
  3691. FuncInfo->setMinReservedArea(MinReservedArea);
  3692. SmallVector<SDValue, 8> MemOps;
  3693. // If the function takes variable number of arguments, make a frame index for
  3694. // the start of the first vararg value... for expansion of llvm.va_start.
  3695. if (isVarArg) {
  3696. static const MCPhysReg GPArgRegs[] = {
  3697. PPC::R3, PPC::R4, PPC::R5, PPC::R6,
  3698. PPC::R7, PPC::R8, PPC::R9, PPC::R10,
  3699. };
  3700. const unsigned NumGPArgRegs = std::size(GPArgRegs);
  3701. static const MCPhysReg FPArgRegs[] = {
  3702. PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
  3703. PPC::F8
  3704. };
  3705. unsigned NumFPArgRegs = std::size(FPArgRegs);
  3706. if (useSoftFloat() || hasSPE())
  3707. NumFPArgRegs = 0;
  3708. FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
  3709. FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
  3710. // Make room for NumGPArgRegs and NumFPArgRegs.
  3711. int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
  3712. NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
  3713. FuncInfo->setVarArgsStackOffset(
  3714. MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
  3715. CCInfo.getNextStackOffset(), true));
  3716. FuncInfo->setVarArgsFrameIndex(
  3717. MFI.CreateStackObject(Depth, Align(8), false));
  3718. SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
  3719. // The fixed integer arguments of a variadic function are stored to the
  3720. // VarArgsFrameIndex on the stack so that they may be loaded by
  3721. // dereferencing the result of va_next.
  3722. for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
  3723. // Get an existing live-in vreg, or add a new one.
  3724. Register VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
  3725. if (!VReg)
  3726. VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
  3727. SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
  3728. SDValue Store =
  3729. DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
  3730. MemOps.push_back(Store);
  3731. // Increment the address by four for the next argument to store
  3732. SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
  3733. FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
  3734. }
  3735. // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
  3736. // is set.
  3737. // The double arguments are stored to the VarArgsFrameIndex
  3738. // on the stack.
  3739. for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
  3740. // Get an existing live-in vreg, or add a new one.
  3741. Register VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
  3742. if (!VReg)
  3743. VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
  3744. SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
  3745. SDValue Store =
  3746. DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
  3747. MemOps.push_back(Store);
  3748. // Increment the address by eight for the next argument to store
  3749. SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
  3750. PtrVT);
  3751. FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
  3752. }
  3753. }
  3754. if (!MemOps.empty())
  3755. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
  3756. return Chain;
  3757. }
  3758. // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
  3759. // value to MVT::i64 and then truncate to the correct register size.
  3760. SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
  3761. EVT ObjectVT, SelectionDAG &DAG,
  3762. SDValue ArgVal,
  3763. const SDLoc &dl) const {
  3764. if (Flags.isSExt())
  3765. ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
  3766. DAG.getValueType(ObjectVT));
  3767. else if (Flags.isZExt())
  3768. ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
  3769. DAG.getValueType(ObjectVT));
  3770. return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
  3771. }
  3772. SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
  3773. SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
  3774. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
  3775. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
  3776. // TODO: add description of PPC stack frame format, or at least some docs.
  3777. //
  3778. bool isELFv2ABI = Subtarget.isELFv2ABI();
  3779. bool isLittleEndian = Subtarget.isLittleEndian();
  3780. MachineFunction &MF = DAG.getMachineFunction();
  3781. MachineFrameInfo &MFI = MF.getFrameInfo();
  3782. PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  3783. assert(!(CallConv == CallingConv::Fast && isVarArg) &&
  3784. "fastcc not supported on varargs functions");
  3785. EVT PtrVT = getPointerTy(MF.getDataLayout());
  3786. // Potential tail calls could cause overwriting of argument stack slots.
  3787. bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
  3788. (CallConv == CallingConv::Fast));
  3789. unsigned PtrByteSize = 8;
  3790. unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
  3791. static const MCPhysReg GPR[] = {
  3792. PPC::X3, PPC::X4, PPC::X5, PPC::X6,
  3793. PPC::X7, PPC::X8, PPC::X9, PPC::X10,
  3794. };
  3795. static const MCPhysReg VR[] = {
  3796. PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
  3797. PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
  3798. };
  3799. const unsigned Num_GPR_Regs = std::size(GPR);
  3800. const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
  3801. const unsigned Num_VR_Regs = std::size(VR);
  3802. // Do a first pass over the arguments to determine whether the ABI
  3803. // guarantees that our caller has allocated the parameter save area
  3804. // on its stack frame. In the ELFv1 ABI, this is always the case;
  3805. // in the ELFv2 ABI, it is true if this is a vararg function or if
  3806. // any parameter is located in a stack slot.
  3807. bool HasParameterArea = !isELFv2ABI || isVarArg;
  3808. unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
  3809. unsigned NumBytes = LinkageSize;
  3810. unsigned AvailableFPRs = Num_FPR_Regs;
  3811. unsigned AvailableVRs = Num_VR_Regs;
  3812. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  3813. if (Ins[i].Flags.isNest())
  3814. continue;
  3815. if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
  3816. PtrByteSize, LinkageSize, ParamAreaSize,
  3817. NumBytes, AvailableFPRs, AvailableVRs))
  3818. HasParameterArea = true;
  3819. }
  3820. // Add DAG nodes to load the arguments or copy them out of registers. On
  3821. // entry to a function on PPC, the arguments start after the linkage area,
  3822. // although the first ones are often in registers.
  3823. unsigned ArgOffset = LinkageSize;
  3824. unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
  3825. SmallVector<SDValue, 8> MemOps;
  3826. Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
  3827. unsigned CurArgIdx = 0;
  3828. for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
  3829. SDValue ArgVal;
  3830. bool needsLoad = false;
  3831. EVT ObjectVT = Ins[ArgNo].VT;
  3832. EVT OrigVT = Ins[ArgNo].ArgVT;
  3833. unsigned ObjSize = ObjectVT.getStoreSize();
  3834. unsigned ArgSize = ObjSize;
  3835. ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
  3836. if (Ins[ArgNo].isOrigArg()) {
  3837. std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
  3838. CurArgIdx = Ins[ArgNo].getOrigArgIndex();
  3839. }
  3840. // We re-align the argument offset for each argument, except when using the
  3841. // fast calling convention, when we need to make sure we do that only when
  3842. // we'll actually use a stack slot.
  3843. unsigned CurArgOffset;
  3844. Align Alignment;
  3845. auto ComputeArgOffset = [&]() {
  3846. /* Respect alignment of argument on the stack. */
  3847. Alignment =
  3848. CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
  3849. ArgOffset = alignTo(ArgOffset, Alignment);
  3850. CurArgOffset = ArgOffset;
  3851. };
  3852. if (CallConv != CallingConv::Fast) {
  3853. ComputeArgOffset();
  3854. /* Compute GPR index associated with argument offset. */
  3855. GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
  3856. GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
  3857. }
  3858. // FIXME the codegen can be much improved in some cases.
  3859. // We do not have to keep everything in memory.
  3860. if (Flags.isByVal()) {
  3861. assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
  3862. if (CallConv == CallingConv::Fast)
  3863. ComputeArgOffset();
  3864. // ObjSize is the true size, ArgSize rounded up to multiple of registers.
  3865. ObjSize = Flags.getByValSize();
  3866. ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
  3867. // Empty aggregate parameters do not take up registers. Examples:
  3868. // struct { } a;
  3869. // union { } b;
  3870. // int c[0];
  3871. // etc. However, we have to provide a place-holder in InVals, so
  3872. // pretend we have an 8-byte item at the current address for that
  3873. // purpose.
  3874. if (!ObjSize) {
  3875. int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
  3876. SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
  3877. InVals.push_back(FIN);
  3878. continue;
  3879. }
  3880. // Create a stack object covering all stack doublewords occupied
  3881. // by the argument. If the argument is (fully or partially) on
  3882. // the stack, or if the argument is fully in registers but the
  3883. // caller has allocated the parameter save anyway, we can refer
  3884. // directly to the caller's stack frame. Otherwise, create a
  3885. // local copy in our own frame.
  3886. int FI;
  3887. if (HasParameterArea ||
  3888. ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
  3889. FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
  3890. else
  3891. FI = MFI.CreateStackObject(ArgSize, Alignment, false);
  3892. SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
  3893. // Handle aggregates smaller than 8 bytes.
  3894. if (ObjSize < PtrByteSize) {
  3895. // The value of the object is its address, which differs from the
  3896. // address of the enclosing doubleword on big-endian systems.
  3897. SDValue Arg = FIN;
  3898. if (!isLittleEndian) {
  3899. SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
  3900. Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
  3901. }
  3902. InVals.push_back(Arg);
  3903. if (GPR_idx != Num_GPR_Regs) {
  3904. Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
  3905. FuncInfo->addLiveInAttr(VReg, Flags);
  3906. SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
  3907. EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8);
  3908. SDValue Store =
  3909. DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
  3910. MachinePointerInfo(&*FuncArg), ObjType);
  3911. MemOps.push_back(Store);
  3912. }
  3913. // Whether we copied from a register or not, advance the offset
  3914. // into the parameter save area by a full doubleword.
  3915. ArgOffset += PtrByteSize;
  3916. continue;
  3917. }
  3918. // The value of the object is its address, which is the address of
  3919. // its first stack doubleword.
  3920. InVals.push_back(FIN);
  3921. // Store whatever pieces of the object are in registers to memory.
  3922. for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
  3923. if (GPR_idx == Num_GPR_Regs)
  3924. break;
  3925. Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
  3926. FuncInfo->addLiveInAttr(VReg, Flags);
  3927. SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
  3928. SDValue Addr = FIN;
  3929. if (j) {
  3930. SDValue Off = DAG.getConstant(j, dl, PtrVT);
  3931. Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
  3932. }
  3933. unsigned StoreSizeInBits = std::min(PtrByteSize, (ObjSize - j)) * 8;
  3934. EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), StoreSizeInBits);
  3935. SDValue Store =
  3936. DAG.getTruncStore(Val.getValue(1), dl, Val, Addr,
  3937. MachinePointerInfo(&*FuncArg, j), ObjType);
  3938. MemOps.push_back(Store);
  3939. ++GPR_idx;
  3940. }
  3941. ArgOffset += ArgSize;
  3942. continue;
  3943. }
  3944. switch (ObjectVT.getSimpleVT().SimpleTy) {
  3945. default: llvm_unreachable("Unhandled argument type!");
  3946. case MVT::i1:
  3947. case MVT::i32:
  3948. case MVT::i64:
  3949. if (Flags.isNest()) {
  3950. // The 'nest' parameter, if any, is passed in R11.
  3951. Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
  3952. ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
  3953. if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
  3954. ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
  3955. break;
  3956. }
  3957. // These can be scalar arguments or elements of an integer array type
  3958. // passed directly. Clang may use those instead of "byval" aggregate
  3959. // types to avoid forcing arguments to memory unnecessarily.
  3960. if (GPR_idx != Num_GPR_Regs) {
  3961. Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
  3962. FuncInfo->addLiveInAttr(VReg, Flags);
  3963. ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
  3964. if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
  3965. // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
  3966. // value to MVT::i64 and then truncate to the correct register size.
  3967. ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
  3968. } else {
  3969. if (CallConv == CallingConv::Fast)
  3970. ComputeArgOffset();
  3971. needsLoad = true;
  3972. ArgSize = PtrByteSize;
  3973. }
  3974. if (CallConv != CallingConv::Fast || needsLoad)
  3975. ArgOffset += 8;
  3976. break;
  3977. case MVT::f32:
  3978. case MVT::f64:
  3979. // These can be scalar arguments or elements of a float array type
  3980. // passed directly. The latter are used to implement ELFv2 homogenous
  3981. // float aggregates.
  3982. if (FPR_idx != Num_FPR_Regs) {
  3983. unsigned VReg;
  3984. if (ObjectVT == MVT::f32)
  3985. VReg = MF.addLiveIn(FPR[FPR_idx],
  3986. Subtarget.hasP8Vector()
  3987. ? &PPC::VSSRCRegClass
  3988. : &PPC::F4RCRegClass);
  3989. else
  3990. VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
  3991. ? &PPC::VSFRCRegClass
  3992. : &PPC::F8RCRegClass);
  3993. ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
  3994. ++FPR_idx;
  3995. } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
  3996. // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
  3997. // once we support fp <-> gpr moves.
  3998. // This can only ever happen in the presence of f32 array types,
  3999. // since otherwise we never run out of FPRs before running out
  4000. // of GPRs.
  4001. Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
  4002. FuncInfo->addLiveInAttr(VReg, Flags);
  4003. ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
  4004. if (ObjectVT == MVT::f32) {
  4005. if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
  4006. ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
  4007. DAG.getConstant(32, dl, MVT::i32));
  4008. ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
  4009. }
  4010. ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
  4011. } else {
  4012. if (CallConv == CallingConv::Fast)
  4013. ComputeArgOffset();
  4014. needsLoad = true;
  4015. }
  4016. // When passing an array of floats, the array occupies consecutive
  4017. // space in the argument area; only round up to the next doubleword
  4018. // at the end of the array. Otherwise, each float takes 8 bytes.
  4019. if (CallConv != CallingConv::Fast || needsLoad) {
  4020. ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
  4021. ArgOffset += ArgSize;
  4022. if (Flags.isInConsecutiveRegsLast())
  4023. ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
  4024. }
  4025. break;
  4026. case MVT::v4f32:
  4027. case MVT::v4i32:
  4028. case MVT::v8i16:
  4029. case MVT::v16i8:
  4030. case MVT::v2f64:
  4031. case MVT::v2i64:
  4032. case MVT::v1i128:
  4033. case MVT::f128:
  4034. // These can be scalar arguments or elements of a vector array type
  4035. // passed directly. The latter are used to implement ELFv2 homogenous
  4036. // vector aggregates.
  4037. if (VR_idx != Num_VR_Regs) {
  4038. Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
  4039. ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
  4040. ++VR_idx;
  4041. } else {
  4042. if (CallConv == CallingConv::Fast)
  4043. ComputeArgOffset();
  4044. needsLoad = true;
  4045. }
  4046. if (CallConv != CallingConv::Fast || needsLoad)
  4047. ArgOffset += 16;
  4048. break;
  4049. }
  4050. // We need to load the argument to a virtual register if we determined
  4051. // above that we ran out of physical registers of the appropriate type.
  4052. if (needsLoad) {
  4053. if (ObjSize < ArgSize && !isLittleEndian)
  4054. CurArgOffset += ArgSize - ObjSize;
  4055. int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
  4056. SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
  4057. ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
  4058. }
  4059. InVals.push_back(ArgVal);
  4060. }
  4061. // Area that is at least reserved in the caller of this function.
  4062. unsigned MinReservedArea;
  4063. if (HasParameterArea)
  4064. MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
  4065. else
  4066. MinReservedArea = LinkageSize;
  4067. // Set the size that is at least reserved in caller of this function. Tail
  4068. // call optimized functions' reserved stack space needs to be aligned so that
  4069. // taking the difference between two stack areas will result in an aligned
  4070. // stack.
  4071. MinReservedArea =
  4072. EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
  4073. FuncInfo->setMinReservedArea(MinReservedArea);
  4074. // If the function takes variable number of arguments, make a frame index for
  4075. // the start of the first vararg value... for expansion of llvm.va_start.
  4076. // On ELFv2ABI spec, it writes:
  4077. // C programs that are intended to be *portable* across different compilers
  4078. // and architectures must use the header file <stdarg.h> to deal with variable
  4079. // argument lists.
  4080. if (isVarArg && MFI.hasVAStart()) {
  4081. int Depth = ArgOffset;
  4082. FuncInfo->setVarArgsFrameIndex(
  4083. MFI.CreateFixedObject(PtrByteSize, Depth, true));
  4084. SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
  4085. // If this function is vararg, store any remaining integer argument regs
  4086. // to their spots on the stack so that they may be loaded by dereferencing
  4087. // the result of va_next.
  4088. for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
  4089. GPR_idx < Num_GPR_Regs; ++GPR_idx) {
  4090. Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
  4091. SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
  4092. SDValue Store =
  4093. DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
  4094. MemOps.push_back(Store);
  4095. // Increment the address by four for the next argument to store
  4096. SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
  4097. FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
  4098. }
  4099. }
  4100. if (!MemOps.empty())
  4101. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
  4102. return Chain;
  4103. }
  4104. /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
  4105. /// adjusted to accommodate the arguments for the tailcall.
  4106. static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
  4107. unsigned ParamSize) {
  4108. if (!isTailCall) return 0;
  4109. PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
  4110. unsigned CallerMinReservedArea = FI->getMinReservedArea();
  4111. int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
  4112. // Remember only if the new adjustment is bigger.
  4113. if (SPDiff < FI->getTailCallSPDelta())
  4114. FI->setTailCallSPDelta(SPDiff);
  4115. return SPDiff;
  4116. }
  4117. static bool isFunctionGlobalAddress(SDValue Callee);
  4118. static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
  4119. const TargetMachine &TM) {
  4120. // It does not make sense to call callsShareTOCBase() with a caller that
  4121. // is PC Relative since PC Relative callers do not have a TOC.
  4122. #ifndef NDEBUG
  4123. const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
  4124. assert(!STICaller->isUsingPCRelativeCalls() &&
  4125. "PC Relative callers do not have a TOC and cannot share a TOC Base");
  4126. #endif
  4127. // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
  4128. // don't have enough information to determine if the caller and callee share
  4129. // the same TOC base, so we have to pessimistically assume they don't for
  4130. // correctness.
  4131. GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
  4132. if (!G)
  4133. return false;
  4134. const GlobalValue *GV = G->getGlobal();
  4135. // If the callee is preemptable, then the static linker will use a plt-stub
  4136. // which saves the toc to the stack, and needs a nop after the call
  4137. // instruction to convert to a toc-restore.
  4138. if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
  4139. return false;
  4140. // Functions with PC Relative enabled may clobber the TOC in the same DSO.
  4141. // We may need a TOC restore in the situation where the caller requires a
  4142. // valid TOC but the callee is PC Relative and does not.
  4143. const Function *F = dyn_cast<Function>(GV);
  4144. const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
  4145. // If we have an Alias we can try to get the function from there.
  4146. if (Alias) {
  4147. const GlobalObject *GlobalObj = Alias->getAliaseeObject();
  4148. F = dyn_cast<Function>(GlobalObj);
  4149. }
  4150. // If we still have no valid function pointer we do not have enough
  4151. // information to determine if the callee uses PC Relative calls so we must
  4152. // assume that it does.
  4153. if (!F)
  4154. return false;
  4155. // If the callee uses PC Relative we cannot guarantee that the callee won't
  4156. // clobber the TOC of the caller and so we must assume that the two
  4157. // functions do not share a TOC base.
  4158. const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
  4159. if (STICallee->isUsingPCRelativeCalls())
  4160. return false;
  4161. // If the GV is not a strong definition then we need to assume it can be
  4162. // replaced by another function at link time. The function that replaces
  4163. // it may not share the same TOC as the caller since the callee may be
  4164. // replaced by a PC Relative version of the same function.
  4165. if (!GV->isStrongDefinitionForLinker())
  4166. return false;
  4167. // The medium and large code models are expected to provide a sufficiently
  4168. // large TOC to provide all data addressing needs of a module with a
  4169. // single TOC.
  4170. if (CodeModel::Medium == TM.getCodeModel() ||
  4171. CodeModel::Large == TM.getCodeModel())
  4172. return true;
  4173. // Any explicitly-specified sections and section prefixes must also match.
  4174. // Also, if we're using -ffunction-sections, then each function is always in
  4175. // a different section (the same is true for COMDAT functions).
  4176. if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
  4177. GV->getSection() != Caller->getSection())
  4178. return false;
  4179. if (const auto *F = dyn_cast<Function>(GV)) {
  4180. if (F->getSectionPrefix() != Caller->getSectionPrefix())
  4181. return false;
  4182. }
  4183. return true;
  4184. }
  4185. static bool
  4186. needStackSlotPassParameters(const PPCSubtarget &Subtarget,
  4187. const SmallVectorImpl<ISD::OutputArg> &Outs) {
  4188. assert(Subtarget.is64BitELFABI());
  4189. const unsigned PtrByteSize = 8;
  4190. const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
  4191. static const MCPhysReg GPR[] = {
  4192. PPC::X3, PPC::X4, PPC::X5, PPC::X6,
  4193. PPC::X7, PPC::X8, PPC::X9, PPC::X10,
  4194. };
  4195. static const MCPhysReg VR[] = {
  4196. PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
  4197. PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
  4198. };
  4199. const unsigned NumGPRs = std::size(GPR);
  4200. const unsigned NumFPRs = 13;
  4201. const unsigned NumVRs = std::size(VR);
  4202. const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
  4203. unsigned NumBytes = LinkageSize;
  4204. unsigned AvailableFPRs = NumFPRs;
  4205. unsigned AvailableVRs = NumVRs;
  4206. for (const ISD::OutputArg& Param : Outs) {
  4207. if (Param.Flags.isNest()) continue;
  4208. if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
  4209. LinkageSize, ParamAreaSize, NumBytes,
  4210. AvailableFPRs, AvailableVRs))
  4211. return true;
  4212. }
  4213. return false;
  4214. }
  4215. static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
  4216. if (CB.arg_size() != CallerFn->arg_size())
  4217. return false;
  4218. auto CalleeArgIter = CB.arg_begin();
  4219. auto CalleeArgEnd = CB.arg_end();
  4220. Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
  4221. for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
  4222. const Value* CalleeArg = *CalleeArgIter;
  4223. const Value* CallerArg = &(*CallerArgIter);
  4224. if (CalleeArg == CallerArg)
  4225. continue;
  4226. // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
  4227. // tail call @callee([4 x i64] undef, [4 x i64] %b)
  4228. // }
  4229. // 1st argument of callee is undef and has the same type as caller.
  4230. if (CalleeArg->getType() == CallerArg->getType() &&
  4231. isa<UndefValue>(CalleeArg))
  4232. continue;
  4233. return false;
  4234. }
  4235. return true;
  4236. }
  4237. // Returns true if TCO is possible between the callers and callees
  4238. // calling conventions.
  4239. static bool
  4240. areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
  4241. CallingConv::ID CalleeCC) {
  4242. // Tail calls are possible with fastcc and ccc.
  4243. auto isTailCallableCC = [] (CallingConv::ID CC){
  4244. return CC == CallingConv::C || CC == CallingConv::Fast;
  4245. };
  4246. if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
  4247. return false;
  4248. // We can safely tail call both fastcc and ccc callees from a c calling
  4249. // convention caller. If the caller is fastcc, we may have less stack space
  4250. // than a non-fastcc caller with the same signature so disable tail-calls in
  4251. // that case.
  4252. return CallerCC == CallingConv::C || CallerCC == CalleeCC;
  4253. }
  4254. bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
  4255. SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
  4256. const SmallVectorImpl<ISD::OutputArg> &Outs,
  4257. const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
  4258. bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
  4259. if (DisableSCO && !TailCallOpt) return false;
  4260. // Variadic argument functions are not supported.
  4261. if (isVarArg) return false;
  4262. auto &Caller = DAG.getMachineFunction().getFunction();
  4263. // Check that the calling conventions are compatible for tco.
  4264. if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
  4265. return false;
  4266. // Caller contains any byval parameter is not supported.
  4267. if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
  4268. return false;
  4269. // Callee contains any byval parameter is not supported, too.
  4270. // Note: This is a quick work around, because in some cases, e.g.
  4271. // caller's stack size > callee's stack size, we are still able to apply
  4272. // sibling call optimization. For example, gcc is able to do SCO for caller1
  4273. // in the following example, but not for caller2.
  4274. // struct test {
  4275. // long int a;
  4276. // char ary[56];
  4277. // } gTest;
  4278. // __attribute__((noinline)) int callee(struct test v, struct test *b) {
  4279. // b->a = v.a;
  4280. // return 0;
  4281. // }
  4282. // void caller1(struct test a, struct test c, struct test *b) {
  4283. // callee(gTest, b); }
  4284. // void caller2(struct test *b) { callee(gTest, b); }
  4285. if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
  4286. return false;
  4287. // If callee and caller use different calling conventions, we cannot pass
  4288. // parameters on stack since offsets for the parameter area may be different.
  4289. if (Caller.getCallingConv() != CalleeCC &&
  4290. needStackSlotPassParameters(Subtarget, Outs))
  4291. return false;
  4292. // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
  4293. // the caller and callee share the same TOC for TCO/SCO. If the caller and
  4294. // callee potentially have different TOC bases then we cannot tail call since
  4295. // we need to restore the TOC pointer after the call.
  4296. // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
  4297. // We cannot guarantee this for indirect calls or calls to external functions.
  4298. // When PC-Relative addressing is used, the concept of the TOC is no longer
  4299. // applicable so this check is not required.
  4300. // Check first for indirect calls.
  4301. if (!Subtarget.isUsingPCRelativeCalls() &&
  4302. !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
  4303. return false;
  4304. // Check if we share the TOC base.
  4305. if (!Subtarget.isUsingPCRelativeCalls() &&
  4306. !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
  4307. return false;
  4308. // TCO allows altering callee ABI, so we don't have to check further.
  4309. if (CalleeCC == CallingConv::Fast && TailCallOpt)
  4310. return true;
  4311. if (DisableSCO) return false;
  4312. // If callee use the same argument list that caller is using, then we can
  4313. // apply SCO on this case. If it is not, then we need to check if callee needs
  4314. // stack for passing arguments.
  4315. // PC Relative tail calls may not have a CallBase.
  4316. // If there is no CallBase we cannot verify if we have the same argument
  4317. // list so assume that we don't have the same argument list.
  4318. if (CB && !hasSameArgumentList(&Caller, *CB) &&
  4319. needStackSlotPassParameters(Subtarget, Outs))
  4320. return false;
  4321. else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
  4322. return false;
  4323. return true;
  4324. }
  4325. /// IsEligibleForTailCallOptimization - Check whether the call is eligible
  4326. /// for tail call optimization. Targets which want to do tail call
  4327. /// optimization should implement this function.
  4328. bool
  4329. PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
  4330. CallingConv::ID CalleeCC,
  4331. bool isVarArg,
  4332. const SmallVectorImpl<ISD::InputArg> &Ins,
  4333. SelectionDAG& DAG) const {
  4334. if (!getTargetMachine().Options.GuaranteedTailCallOpt)
  4335. return false;
  4336. // Variable argument functions are not supported.
  4337. if (isVarArg)
  4338. return false;
  4339. MachineFunction &MF = DAG.getMachineFunction();
  4340. CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
  4341. if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
  4342. // Functions containing by val parameters are not supported.
  4343. for (unsigned i = 0; i != Ins.size(); i++) {
  4344. ISD::ArgFlagsTy Flags = Ins[i].Flags;
  4345. if (Flags.isByVal()) return false;
  4346. }
  4347. // Non-PIC/GOT tail calls are supported.
  4348. if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
  4349. return true;
  4350. // At the moment we can only do local tail calls (in same module, hidden
  4351. // or protected) if we are generating PIC.
  4352. if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
  4353. return G->getGlobal()->hasHiddenVisibility()
  4354. || G->getGlobal()->hasProtectedVisibility();
  4355. }
  4356. return false;
  4357. }
  4358. /// isCallCompatibleAddress - Return the immediate to use if the specified
  4359. /// 32-bit value is representable in the immediate field of a BxA instruction.
  4360. static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
  4361. ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
  4362. if (!C) return nullptr;
  4363. int Addr = C->getZExtValue();
  4364. if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
  4365. SignExtend32<26>(Addr) != Addr)
  4366. return nullptr; // Top 6 bits have to be sext of immediate.
  4367. return DAG
  4368. .getConstant(
  4369. (int)C->getZExtValue() >> 2, SDLoc(Op),
  4370. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
  4371. .getNode();
  4372. }
  4373. namespace {
  4374. struct TailCallArgumentInfo {
  4375. SDValue Arg;
  4376. SDValue FrameIdxOp;
  4377. int FrameIdx = 0;
  4378. TailCallArgumentInfo() = default;
  4379. };
  4380. } // end anonymous namespace
  4381. /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
  4382. static void StoreTailCallArgumentsToStackSlot(
  4383. SelectionDAG &DAG, SDValue Chain,
  4384. const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
  4385. SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
  4386. for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
  4387. SDValue Arg = TailCallArgs[i].Arg;
  4388. SDValue FIN = TailCallArgs[i].FrameIdxOp;
  4389. int FI = TailCallArgs[i].FrameIdx;
  4390. // Store relative to framepointer.
  4391. MemOpChains.push_back(DAG.getStore(
  4392. Chain, dl, Arg, FIN,
  4393. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
  4394. }
  4395. }
  4396. /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
  4397. /// the appropriate stack slot for the tail call optimized function call.
  4398. static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
  4399. SDValue OldRetAddr, SDValue OldFP,
  4400. int SPDiff, const SDLoc &dl) {
  4401. if (SPDiff) {
  4402. // Calculate the new stack slot for the return address.
  4403. MachineFunction &MF = DAG.getMachineFunction();
  4404. const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
  4405. const PPCFrameLowering *FL = Subtarget.getFrameLowering();
  4406. bool isPPC64 = Subtarget.isPPC64();
  4407. int SlotSize = isPPC64 ? 8 : 4;
  4408. int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
  4409. int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
  4410. NewRetAddrLoc, true);
  4411. EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
  4412. SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
  4413. Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
  4414. MachinePointerInfo::getFixedStack(MF, NewRetAddr));
  4415. }
  4416. return Chain;
  4417. }
  4418. /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
  4419. /// the position of the argument.
  4420. static void
  4421. CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
  4422. SDValue Arg, int SPDiff, unsigned ArgOffset,
  4423. SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
  4424. int Offset = ArgOffset + SPDiff;
  4425. uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
  4426. int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
  4427. EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
  4428. SDValue FIN = DAG.getFrameIndex(FI, VT);
  4429. TailCallArgumentInfo Info;
  4430. Info.Arg = Arg;
  4431. Info.FrameIdxOp = FIN;
  4432. Info.FrameIdx = FI;
  4433. TailCallArguments.push_back(Info);
  4434. }
  4435. /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
  4436. /// stack slot. Returns the chain as result and the loaded frame pointers in
  4437. /// LROpOut/FPOpout. Used when tail calling.
  4438. SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
  4439. SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
  4440. SDValue &FPOpOut, const SDLoc &dl) const {
  4441. if (SPDiff) {
  4442. // Load the LR and FP stack slot for later adjusting.
  4443. EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
  4444. LROpOut = getReturnAddrFrameIndex(DAG);
  4445. LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
  4446. Chain = SDValue(LROpOut.getNode(), 1);
  4447. }
  4448. return Chain;
  4449. }
  4450. /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
  4451. /// by "Src" to address "Dst" of size "Size". Alignment information is
  4452. /// specified by the specific parameter attribute. The copy will be passed as
  4453. /// a byval function parameter.
  4454. /// Sometimes what we are copying is the end of a larger object, the part that
  4455. /// does not fit in registers.
  4456. static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
  4457. SDValue Chain, ISD::ArgFlagsTy Flags,
  4458. SelectionDAG &DAG, const SDLoc &dl) {
  4459. SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
  4460. return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
  4461. Flags.getNonZeroByValAlign(), false, false, false,
  4462. MachinePointerInfo(), MachinePointerInfo());
  4463. }
  4464. /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
  4465. /// tail calls.
  4466. static void LowerMemOpCallTo(
  4467. SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
  4468. SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
  4469. bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
  4470. SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
  4471. EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  4472. if (!isTailCall) {
  4473. if (isVector) {
  4474. SDValue StackPtr;
  4475. if (isPPC64)
  4476. StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
  4477. else
  4478. StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
  4479. PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
  4480. DAG.getConstant(ArgOffset, dl, PtrVT));
  4481. }
  4482. MemOpChains.push_back(
  4483. DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
  4484. // Calculate and remember argument location.
  4485. } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
  4486. TailCallArguments);
  4487. }
  4488. static void
  4489. PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
  4490. const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
  4491. SDValue FPOp,
  4492. SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
  4493. // Emit a sequence of copyto/copyfrom virtual registers for arguments that
  4494. // might overwrite each other in case of tail call optimization.
  4495. SmallVector<SDValue, 8> MemOpChains2;
  4496. // Do not flag preceding copytoreg stuff together with the following stuff.
  4497. InFlag = SDValue();
  4498. StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
  4499. MemOpChains2, dl);
  4500. if (!MemOpChains2.empty())
  4501. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
  4502. // Store the return address to the appropriate stack slot.
  4503. Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
  4504. // Emit callseq_end just before tailcall node.
  4505. Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InFlag, dl);
  4506. InFlag = Chain.getValue(1);
  4507. }
  4508. // Is this global address that of a function that can be called by name? (as
  4509. // opposed to something that must hold a descriptor for an indirect call).
  4510. static bool isFunctionGlobalAddress(SDValue Callee) {
  4511. if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
  4512. if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
  4513. Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
  4514. return false;
  4515. return G->getGlobal()->getValueType()->isFunctionTy();
  4516. }
  4517. return false;
  4518. }
  4519. SDValue PPCTargetLowering::LowerCallResult(
  4520. SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
  4521. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
  4522. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
  4523. SmallVector<CCValAssign, 16> RVLocs;
  4524. CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
  4525. *DAG.getContext());
  4526. CCRetInfo.AnalyzeCallResult(
  4527. Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
  4528. ? RetCC_PPC_Cold
  4529. : RetCC_PPC);
  4530. // Copy all of the result registers out of their specified physreg.
  4531. for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
  4532. CCValAssign &VA = RVLocs[i];
  4533. assert(VA.isRegLoc() && "Can only return in registers!");
  4534. SDValue Val;
  4535. if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
  4536. SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
  4537. InFlag);
  4538. Chain = Lo.getValue(1);
  4539. InFlag = Lo.getValue(2);
  4540. VA = RVLocs[++i]; // skip ahead to next loc
  4541. SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
  4542. InFlag);
  4543. Chain = Hi.getValue(1);
  4544. InFlag = Hi.getValue(2);
  4545. if (!Subtarget.isLittleEndian())
  4546. std::swap (Lo, Hi);
  4547. Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
  4548. } else {
  4549. Val = DAG.getCopyFromReg(Chain, dl,
  4550. VA.getLocReg(), VA.getLocVT(), InFlag);
  4551. Chain = Val.getValue(1);
  4552. InFlag = Val.getValue(2);
  4553. }
  4554. switch (VA.getLocInfo()) {
  4555. default: llvm_unreachable("Unknown loc info!");
  4556. case CCValAssign::Full: break;
  4557. case CCValAssign::AExt:
  4558. Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
  4559. break;
  4560. case CCValAssign::ZExt:
  4561. Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
  4562. DAG.getValueType(VA.getValVT()));
  4563. Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
  4564. break;
  4565. case CCValAssign::SExt:
  4566. Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
  4567. DAG.getValueType(VA.getValVT()));
  4568. Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
  4569. break;
  4570. }
  4571. InVals.push_back(Val);
  4572. }
  4573. return Chain;
  4574. }
  4575. static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
  4576. const PPCSubtarget &Subtarget, bool isPatchPoint) {
  4577. // PatchPoint calls are not indirect.
  4578. if (isPatchPoint)
  4579. return false;
  4580. if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee))
  4581. return false;
  4582. // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
  4583. // becuase the immediate function pointer points to a descriptor instead of
  4584. // a function entry point. The ELFv2 ABI cannot use a BLA because the function
  4585. // pointer immediate points to the global entry point, while the BLA would
  4586. // need to jump to the local entry point (see rL211174).
  4587. if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
  4588. isBLACompatibleAddress(Callee, DAG))
  4589. return false;
  4590. return true;
  4591. }
  4592. // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
  4593. static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
  4594. return Subtarget.isAIXABI() ||
  4595. (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
  4596. }
  4597. static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
  4598. const Function &Caller, const SDValue &Callee,
  4599. const PPCSubtarget &Subtarget,
  4600. const TargetMachine &TM,
  4601. bool IsStrictFPCall = false) {
  4602. if (CFlags.IsTailCall)
  4603. return PPCISD::TC_RETURN;
  4604. unsigned RetOpc = 0;
  4605. // This is a call through a function pointer.
  4606. if (CFlags.IsIndirect) {
  4607. // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
  4608. // indirect calls. The save of the caller's TOC pointer to the stack will be
  4609. // inserted into the DAG as part of call lowering. The restore of the TOC
  4610. // pointer is modeled by using a pseudo instruction for the call opcode that
  4611. // represents the 2 instruction sequence of an indirect branch and link,
  4612. // immediately followed by a load of the TOC pointer from the the stack save
  4613. // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
  4614. // as it is not saved or used.
  4615. RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
  4616. : PPCISD::BCTRL;
  4617. } else if (Subtarget.isUsingPCRelativeCalls()) {
  4618. assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
  4619. RetOpc = PPCISD::CALL_NOTOC;
  4620. } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
  4621. // The ABIs that maintain a TOC pointer accross calls need to have a nop
  4622. // immediately following the call instruction if the caller and callee may
  4623. // have different TOC bases. At link time if the linker determines the calls
  4624. // may not share a TOC base, the call is redirected to a trampoline inserted
  4625. // by the linker. The trampoline will (among other things) save the callers
  4626. // TOC pointer at an ABI designated offset in the linkage area and the
  4627. // linker will rewrite the nop to be a load of the TOC pointer from the
  4628. // linkage area into gpr2.
  4629. RetOpc = callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
  4630. : PPCISD::CALL_NOP;
  4631. else
  4632. RetOpc = PPCISD::CALL;
  4633. if (IsStrictFPCall) {
  4634. switch (RetOpc) {
  4635. default:
  4636. llvm_unreachable("Unknown call opcode");
  4637. case PPCISD::BCTRL_LOAD_TOC:
  4638. RetOpc = PPCISD::BCTRL_LOAD_TOC_RM;
  4639. break;
  4640. case PPCISD::BCTRL:
  4641. RetOpc = PPCISD::BCTRL_RM;
  4642. break;
  4643. case PPCISD::CALL_NOTOC:
  4644. RetOpc = PPCISD::CALL_NOTOC_RM;
  4645. break;
  4646. case PPCISD::CALL:
  4647. RetOpc = PPCISD::CALL_RM;
  4648. break;
  4649. case PPCISD::CALL_NOP:
  4650. RetOpc = PPCISD::CALL_NOP_RM;
  4651. break;
  4652. }
  4653. }
  4654. return RetOpc;
  4655. }
  4656. static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
  4657. const SDLoc &dl, const PPCSubtarget &Subtarget) {
  4658. if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
  4659. if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
  4660. return SDValue(Dest, 0);
  4661. // Returns true if the callee is local, and false otherwise.
  4662. auto isLocalCallee = [&]() {
  4663. const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
  4664. const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
  4665. const GlobalValue *GV = G ? G->getGlobal() : nullptr;
  4666. return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
  4667. !isa_and_nonnull<GlobalIFunc>(GV);
  4668. };
  4669. // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in
  4670. // a static relocation model causes some versions of GNU LD (2.17.50, at
  4671. // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
  4672. // built with secure-PLT.
  4673. bool UsePlt =
  4674. Subtarget.is32BitELFABI() && !isLocalCallee() &&
  4675. Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
  4676. const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
  4677. const TargetMachine &TM = Subtarget.getTargetMachine();
  4678. const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
  4679. MCSymbolXCOFF *S =
  4680. cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
  4681. MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  4682. return DAG.getMCSymbol(S, PtrVT);
  4683. };
  4684. if (isFunctionGlobalAddress(Callee)) {
  4685. const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
  4686. if (Subtarget.isAIXABI()) {
  4687. assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
  4688. return getAIXFuncEntryPointSymbolSDNode(GV);
  4689. }
  4690. return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
  4691. UsePlt ? PPCII::MO_PLT : 0);
  4692. }
  4693. if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
  4694. const char *SymName = S->getSymbol();
  4695. if (Subtarget.isAIXABI()) {
  4696. // If there exists a user-declared function whose name is the same as the
  4697. // ExternalSymbol's, then we pick up the user-declared version.
  4698. const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
  4699. if (const Function *F =
  4700. dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
  4701. return getAIXFuncEntryPointSymbolSDNode(F);
  4702. // On AIX, direct function calls reference the symbol for the function's
  4703. // entry point, which is named by prepending a "." before the function's
  4704. // C-linkage name. A Qualname is returned here because an external
  4705. // function entry point is a csect with XTY_ER property.
  4706. const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
  4707. auto &Context = DAG.getMachineFunction().getMMI().getContext();
  4708. MCSectionXCOFF *Sec = Context.getXCOFFSection(
  4709. (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
  4710. XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER));
  4711. return Sec->getQualNameSymbol();
  4712. };
  4713. SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
  4714. }
  4715. return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
  4716. UsePlt ? PPCII::MO_PLT : 0);
  4717. }
  4718. // No transformation needed.
  4719. assert(Callee.getNode() && "What no callee?");
  4720. return Callee;
  4721. }
  4722. static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
  4723. assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
  4724. "Expected a CALLSEQ_STARTSDNode.");
  4725. // The last operand is the chain, except when the node has glue. If the node
  4726. // has glue, then the last operand is the glue, and the chain is the second
  4727. // last operand.
  4728. SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
  4729. if (LastValue.getValueType() != MVT::Glue)
  4730. return LastValue;
  4731. return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
  4732. }
  4733. // Creates the node that moves a functions address into the count register
  4734. // to prepare for an indirect call instruction.
  4735. static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
  4736. SDValue &Glue, SDValue &Chain,
  4737. const SDLoc &dl) {
  4738. SDValue MTCTROps[] = {Chain, Callee, Glue};
  4739. EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
  4740. Chain = DAG.getNode(PPCISD::MTCTR, dl, ArrayRef(ReturnTypes, 2),
  4741. ArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
  4742. // The glue is the second value produced.
  4743. Glue = Chain.getValue(1);
  4744. }
  4745. static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
  4746. SDValue &Glue, SDValue &Chain,
  4747. SDValue CallSeqStart,
  4748. const CallBase *CB, const SDLoc &dl,
  4749. bool hasNest,
  4750. const PPCSubtarget &Subtarget) {
  4751. // Function pointers in the 64-bit SVR4 ABI do not point to the function
  4752. // entry point, but to the function descriptor (the function entry point
  4753. // address is part of the function descriptor though).
  4754. // The function descriptor is a three doubleword structure with the
  4755. // following fields: function entry point, TOC base address and
  4756. // environment pointer.
  4757. // Thus for a call through a function pointer, the following actions need
  4758. // to be performed:
  4759. // 1. Save the TOC of the caller in the TOC save area of its stack
  4760. // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
  4761. // 2. Load the address of the function entry point from the function
  4762. // descriptor.
  4763. // 3. Load the TOC of the callee from the function descriptor into r2.
  4764. // 4. Load the environment pointer from the function descriptor into
  4765. // r11.
  4766. // 5. Branch to the function entry point address.
  4767. // 6. On return of the callee, the TOC of the caller needs to be
  4768. // restored (this is done in FinishCall()).
  4769. //
  4770. // The loads are scheduled at the beginning of the call sequence, and the
  4771. // register copies are flagged together to ensure that no other
  4772. // operations can be scheduled in between. E.g. without flagging the
  4773. // copies together, a TOC access in the caller could be scheduled between
  4774. // the assignment of the callee TOC and the branch to the callee, which leads
  4775. // to incorrect code.
  4776. // Start by loading the function address from the descriptor.
  4777. SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
  4778. auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
  4779. ? (MachineMemOperand::MODereferenceable |
  4780. MachineMemOperand::MOInvariant)
  4781. : MachineMemOperand::MONone;
  4782. MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
  4783. // Registers used in building the DAG.
  4784. const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
  4785. const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
  4786. // Offsets of descriptor members.
  4787. const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
  4788. const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
  4789. const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
  4790. const Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
  4791. // One load for the functions entry point address.
  4792. SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
  4793. Alignment, MMOFlags);
  4794. // One for loading the TOC anchor for the module that contains the called
  4795. // function.
  4796. SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
  4797. SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
  4798. SDValue TOCPtr =
  4799. DAG.getLoad(RegVT, dl, LDChain, AddTOC,
  4800. MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
  4801. // One for loading the environment pointer.
  4802. SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
  4803. SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
  4804. SDValue LoadEnvPtr =
  4805. DAG.getLoad(RegVT, dl, LDChain, AddPtr,
  4806. MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
  4807. // Then copy the newly loaded TOC anchor to the TOC pointer.
  4808. SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
  4809. Chain = TOCVal.getValue(0);
  4810. Glue = TOCVal.getValue(1);
  4811. // If the function call has an explicit 'nest' parameter, it takes the
  4812. // place of the environment pointer.
  4813. assert((!hasNest || !Subtarget.isAIXABI()) &&
  4814. "Nest parameter is not supported on AIX.");
  4815. if (!hasNest) {
  4816. SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
  4817. Chain = EnvVal.getValue(0);
  4818. Glue = EnvVal.getValue(1);
  4819. }
  4820. // The rest of the indirect call sequence is the same as the non-descriptor
  4821. // DAG.
  4822. prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
  4823. }
  4824. static void
  4825. buildCallOperands(SmallVectorImpl<SDValue> &Ops,
  4826. PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
  4827. SelectionDAG &DAG,
  4828. SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
  4829. SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
  4830. const PPCSubtarget &Subtarget) {
  4831. const bool IsPPC64 = Subtarget.isPPC64();
  4832. // MVT for a general purpose register.
  4833. const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
  4834. // First operand is always the chain.
  4835. Ops.push_back(Chain);
  4836. // If it's a direct call pass the callee as the second operand.
  4837. if (!CFlags.IsIndirect)
  4838. Ops.push_back(Callee);
  4839. else {
  4840. assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
  4841. // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
  4842. // on the stack (this would have been done in `LowerCall_64SVR4` or
  4843. // `LowerCall_AIX`). The call instruction is a pseudo instruction that
  4844. // represents both the indirect branch and a load that restores the TOC
  4845. // pointer from the linkage area. The operand for the TOC restore is an add
  4846. // of the TOC save offset to the stack pointer. This must be the second
  4847. // operand: after the chain input but before any other variadic arguments.
  4848. // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
  4849. // saved or used.
  4850. if (isTOCSaveRestoreRequired(Subtarget)) {
  4851. const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
  4852. SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
  4853. unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
  4854. SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
  4855. SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
  4856. Ops.push_back(AddTOC);
  4857. }
  4858. // Add the register used for the environment pointer.
  4859. if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
  4860. Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
  4861. RegVT));
  4862. // Add CTR register as callee so a bctr can be emitted later.
  4863. if (CFlags.IsTailCall)
  4864. Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
  4865. }
  4866. // If this is a tail call add stack pointer delta.
  4867. if (CFlags.IsTailCall)
  4868. Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
  4869. // Add argument registers to the end of the list so that they are known live
  4870. // into the call.
  4871. for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
  4872. Ops.push_back(DAG.getRegister(RegsToPass[i].first,
  4873. RegsToPass[i].second.getValueType()));
  4874. // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
  4875. // no way to mark dependencies as implicit here.
  4876. // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
  4877. if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
  4878. !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
  4879. Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
  4880. // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
  4881. if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
  4882. Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
  4883. // Add a register mask operand representing the call-preserved registers.
  4884. const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
  4885. const uint32_t *Mask =
  4886. TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
  4887. assert(Mask && "Missing call preserved mask for calling convention");
  4888. Ops.push_back(DAG.getRegisterMask(Mask));
  4889. // If the glue is valid, it is the last operand.
  4890. if (Glue.getNode())
  4891. Ops.push_back(Glue);
  4892. }
  4893. SDValue PPCTargetLowering::FinishCall(
  4894. CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
  4895. SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
  4896. SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
  4897. unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
  4898. SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
  4899. if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
  4900. Subtarget.isAIXABI())
  4901. setUsesTOCBasePtr(DAG);
  4902. unsigned CallOpc =
  4903. getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
  4904. Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false);
  4905. if (!CFlags.IsIndirect)
  4906. Callee = transformCallee(Callee, DAG, dl, Subtarget);
  4907. else if (Subtarget.usesFunctionDescriptors())
  4908. prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
  4909. dl, CFlags.HasNest, Subtarget);
  4910. else
  4911. prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
  4912. // Build the operand list for the call instruction.
  4913. SmallVector<SDValue, 8> Ops;
  4914. buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
  4915. SPDiff, Subtarget);
  4916. // Emit tail call.
  4917. if (CFlags.IsTailCall) {
  4918. // Indirect tail call when using PC Relative calls do not have the same
  4919. // constraints.
  4920. assert(((Callee.getOpcode() == ISD::Register &&
  4921. cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
  4922. Callee.getOpcode() == ISD::TargetExternalSymbol ||
  4923. Callee.getOpcode() == ISD::TargetGlobalAddress ||
  4924. isa<ConstantSDNode>(Callee) ||
  4925. (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
  4926. "Expecting a global address, external symbol, absolute value, "
  4927. "register or an indirect tail call when PC Relative calls are "
  4928. "used.");
  4929. // PC Relative calls also use TC_RETURN as the way to mark tail calls.
  4930. assert(CallOpc == PPCISD::TC_RETURN &&
  4931. "Unexpected call opcode for a tail call.");
  4932. DAG.getMachineFunction().getFrameInfo().setHasTailCall();
  4933. return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
  4934. }
  4935. std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
  4936. Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
  4937. DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
  4938. Glue = Chain.getValue(1);
  4939. // When performing tail call optimization the callee pops its arguments off
  4940. // the stack. Account for this here so these bytes can be pushed back on in
  4941. // PPCFrameLowering::eliminateCallFramePseudoInstr.
  4942. int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
  4943. getTargetMachine().Options.GuaranteedTailCallOpt)
  4944. ? NumBytes
  4945. : 0;
  4946. Chain = DAG.getCALLSEQ_END(Chain, NumBytes, BytesCalleePops, Glue, dl);
  4947. Glue = Chain.getValue(1);
  4948. return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
  4949. DAG, InVals);
  4950. }
  4951. SDValue
  4952. PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
  4953. SmallVectorImpl<SDValue> &InVals) const {
  4954. SelectionDAG &DAG = CLI.DAG;
  4955. SDLoc &dl = CLI.DL;
  4956. SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
  4957. SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
  4958. SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
  4959. SDValue Chain = CLI.Chain;
  4960. SDValue Callee = CLI.Callee;
  4961. bool &isTailCall = CLI.IsTailCall;
  4962. CallingConv::ID CallConv = CLI.CallConv;
  4963. bool isVarArg = CLI.IsVarArg;
  4964. bool isPatchPoint = CLI.IsPatchPoint;
  4965. const CallBase *CB = CLI.CB;
  4966. if (isTailCall) {
  4967. if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
  4968. isTailCall = false;
  4969. else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
  4970. isTailCall = IsEligibleForTailCallOptimization_64SVR4(
  4971. Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
  4972. else
  4973. isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
  4974. Ins, DAG);
  4975. if (isTailCall) {
  4976. ++NumTailCalls;
  4977. if (!getTargetMachine().Options.GuaranteedTailCallOpt)
  4978. ++NumSiblingCalls;
  4979. // PC Relative calls no longer guarantee that the callee is a Global
  4980. // Address Node. The callee could be an indirect tail call in which
  4981. // case the SDValue for the callee could be a load (to load the address
  4982. // of a function pointer) or it may be a register copy (to move the
  4983. // address of the callee from a function parameter into a virtual
  4984. // register). It may also be an ExternalSymbolSDNode (ex memcopy).
  4985. assert((Subtarget.isUsingPCRelativeCalls() ||
  4986. isa<GlobalAddressSDNode>(Callee)) &&
  4987. "Callee should be an llvm::Function object.");
  4988. LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
  4989. << "\nTCO callee: ");
  4990. LLVM_DEBUG(Callee.dump());
  4991. }
  4992. }
  4993. if (!isTailCall && CB && CB->isMustTailCall())
  4994. report_fatal_error("failed to perform tail call elimination on a call "
  4995. "site marked musttail");
  4996. // When long calls (i.e. indirect calls) are always used, calls are always
  4997. // made via function pointer. If we have a function name, first translate it
  4998. // into a pointer.
  4999. if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
  5000. !isTailCall)
  5001. Callee = LowerGlobalAddress(Callee, DAG);
  5002. CallFlags CFlags(
  5003. CallConv, isTailCall, isVarArg, isPatchPoint,
  5004. isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
  5005. // hasNest
  5006. Subtarget.is64BitELFABI() &&
  5007. any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
  5008. CLI.NoMerge);
  5009. if (Subtarget.isAIXABI())
  5010. return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
  5011. InVals, CB);
  5012. assert(Subtarget.isSVR4ABI());
  5013. if (Subtarget.isPPC64())
  5014. return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
  5015. InVals, CB);
  5016. return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
  5017. InVals, CB);
  5018. }
  5019. SDValue PPCTargetLowering::LowerCall_32SVR4(
  5020. SDValue Chain, SDValue Callee, CallFlags CFlags,
  5021. const SmallVectorImpl<ISD::OutputArg> &Outs,
  5022. const SmallVectorImpl<SDValue> &OutVals,
  5023. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
  5024. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
  5025. const CallBase *CB) const {
  5026. // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
  5027. // of the 32-bit SVR4 ABI stack frame layout.
  5028. const CallingConv::ID CallConv = CFlags.CallConv;
  5029. const bool IsVarArg = CFlags.IsVarArg;
  5030. const bool IsTailCall = CFlags.IsTailCall;
  5031. assert((CallConv == CallingConv::C ||
  5032. CallConv == CallingConv::Cold ||
  5033. CallConv == CallingConv::Fast) && "Unknown calling convention!");
  5034. const Align PtrAlign(4);
  5035. MachineFunction &MF = DAG.getMachineFunction();
  5036. // Mark this function as potentially containing a function that contains a
  5037. // tail call. As a consequence the frame pointer will be used for dynamicalloc
  5038. // and restoring the callers stack pointer in this functions epilog. This is
  5039. // done because by tail calling the called function might overwrite the value
  5040. // in this function's (MF) stack pointer stack slot 0(SP).
  5041. if (getTargetMachine().Options.GuaranteedTailCallOpt &&
  5042. CallConv == CallingConv::Fast)
  5043. MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
  5044. // Count how many bytes are to be pushed on the stack, including the linkage
  5045. // area, parameter list area and the part of the local variable space which
  5046. // contains copies of aggregates which are passed by value.
  5047. // Assign locations to all of the outgoing arguments.
  5048. SmallVector<CCValAssign, 16> ArgLocs;
  5049. PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
  5050. // Reserve space for the linkage area on the stack.
  5051. CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
  5052. PtrAlign);
  5053. if (useSoftFloat())
  5054. CCInfo.PreAnalyzeCallOperands(Outs);
  5055. if (IsVarArg) {
  5056. // Handle fixed and variable vector arguments differently.
  5057. // Fixed vector arguments go into registers as long as registers are
  5058. // available. Variable vector arguments always go into memory.
  5059. unsigned NumArgs = Outs.size();
  5060. for (unsigned i = 0; i != NumArgs; ++i) {
  5061. MVT ArgVT = Outs[i].VT;
  5062. ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
  5063. bool Result;
  5064. if (Outs[i].IsFixed) {
  5065. Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
  5066. CCInfo);
  5067. } else {
  5068. Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
  5069. ArgFlags, CCInfo);
  5070. }
  5071. if (Result) {
  5072. #ifndef NDEBUG
  5073. errs() << "Call operand #" << i << " has unhandled type "
  5074. << EVT(ArgVT).getEVTString() << "\n";
  5075. #endif
  5076. llvm_unreachable(nullptr);
  5077. }
  5078. }
  5079. } else {
  5080. // All arguments are treated the same.
  5081. CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
  5082. }
  5083. CCInfo.clearWasPPCF128();
  5084. // Assign locations to all of the outgoing aggregate by value arguments.
  5085. SmallVector<CCValAssign, 16> ByValArgLocs;
  5086. CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
  5087. // Reserve stack space for the allocations in CCInfo.
  5088. CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
  5089. CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
  5090. // Size of the linkage area, parameter list area and the part of the local
  5091. // space variable where copies of aggregates which are passed by value are
  5092. // stored.
  5093. unsigned NumBytes = CCByValInfo.getNextStackOffset();
  5094. // Calculate by how many bytes the stack has to be adjusted in case of tail
  5095. // call optimization.
  5096. int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
  5097. // Adjust the stack pointer for the new arguments...
  5098. // These operations are automatically eliminated by the prolog/epilog pass
  5099. Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
  5100. SDValue CallSeqStart = Chain;
  5101. // Load the return address and frame pointer so it can be moved somewhere else
  5102. // later.
  5103. SDValue LROp, FPOp;
  5104. Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
  5105. // Set up a copy of the stack pointer for use loading and storing any
  5106. // arguments that may not fit in the registers available for argument
  5107. // passing.
  5108. SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
  5109. SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
  5110. SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
  5111. SmallVector<SDValue, 8> MemOpChains;
  5112. bool seenFloatArg = false;
  5113. // Walk the register/memloc assignments, inserting copies/loads.
  5114. // i - Tracks the index into the list of registers allocated for the call
  5115. // RealArgIdx - Tracks the index into the list of actual function arguments
  5116. // j - Tracks the index into the list of byval arguments
  5117. for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
  5118. i != e;
  5119. ++i, ++RealArgIdx) {
  5120. CCValAssign &VA = ArgLocs[i];
  5121. SDValue Arg = OutVals[RealArgIdx];
  5122. ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
  5123. if (Flags.isByVal()) {
  5124. // Argument is an aggregate which is passed by value, thus we need to
  5125. // create a copy of it in the local variable space of the current stack
  5126. // frame (which is the stack frame of the caller) and pass the address of
  5127. // this copy to the callee.
  5128. assert((j < ByValArgLocs.size()) && "Index out of bounds!");
  5129. CCValAssign &ByValVA = ByValArgLocs[j++];
  5130. assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
  5131. // Memory reserved in the local variable space of the callers stack frame.
  5132. unsigned LocMemOffset = ByValVA.getLocMemOffset();
  5133. SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
  5134. PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
  5135. StackPtr, PtrOff);
  5136. // Create a copy of the argument in the local area of the current
  5137. // stack frame.
  5138. SDValue MemcpyCall =
  5139. CreateCopyOfByValArgument(Arg, PtrOff,
  5140. CallSeqStart.getNode()->getOperand(0),
  5141. Flags, DAG, dl);
  5142. // This must go outside the CALLSEQ_START..END.
  5143. SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
  5144. SDLoc(MemcpyCall));
  5145. DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
  5146. NewCallSeqStart.getNode());
  5147. Chain = CallSeqStart = NewCallSeqStart;
  5148. // Pass the address of the aggregate copy on the stack either in a
  5149. // physical register or in the parameter list area of the current stack
  5150. // frame to the callee.
  5151. Arg = PtrOff;
  5152. }
  5153. // When useCRBits() is true, there can be i1 arguments.
  5154. // It is because getRegisterType(MVT::i1) => MVT::i1,
  5155. // and for other integer types getRegisterType() => MVT::i32.
  5156. // Extend i1 and ensure callee will get i32.
  5157. if (Arg.getValueType() == MVT::i1)
  5158. Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
  5159. dl, MVT::i32, Arg);
  5160. if (VA.isRegLoc()) {
  5161. seenFloatArg |= VA.getLocVT().isFloatingPoint();
  5162. // Put argument in a physical register.
  5163. if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
  5164. bool IsLE = Subtarget.isLittleEndian();
  5165. SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
  5166. DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
  5167. RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
  5168. SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
  5169. DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
  5170. RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
  5171. SVal.getValue(0)));
  5172. } else
  5173. RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
  5174. } else {
  5175. // Put argument in the parameter list area of the current stack frame.
  5176. assert(VA.isMemLoc());
  5177. unsigned LocMemOffset = VA.getLocMemOffset();
  5178. if (!IsTailCall) {
  5179. SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
  5180. PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
  5181. StackPtr, PtrOff);
  5182. MemOpChains.push_back(
  5183. DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
  5184. } else {
  5185. // Calculate and remember argument location.
  5186. CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
  5187. TailCallArguments);
  5188. }
  5189. }
  5190. }
  5191. if (!MemOpChains.empty())
  5192. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
  5193. // Build a sequence of copy-to-reg nodes chained together with token chain
  5194. // and flag operands which copy the outgoing args into the appropriate regs.
  5195. SDValue InFlag;
  5196. for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
  5197. Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
  5198. RegsToPass[i].second, InFlag);
  5199. InFlag = Chain.getValue(1);
  5200. }
  5201. // Set CR bit 6 to true if this is a vararg call with floating args passed in
  5202. // registers.
  5203. if (IsVarArg) {
  5204. SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
  5205. SDValue Ops[] = { Chain, InFlag };
  5206. Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, dl,
  5207. VTs, ArrayRef(Ops, InFlag.getNode() ? 2 : 1));
  5208. InFlag = Chain.getValue(1);
  5209. }
  5210. if (IsTailCall)
  5211. PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
  5212. TailCallArguments);
  5213. return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
  5214. Callee, SPDiff, NumBytes, Ins, InVals, CB);
  5215. }
  5216. // Copy an argument into memory, being careful to do this outside the
  5217. // call sequence for the call to which the argument belongs.
  5218. SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
  5219. SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
  5220. SelectionDAG &DAG, const SDLoc &dl) const {
  5221. SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
  5222. CallSeqStart.getNode()->getOperand(0),
  5223. Flags, DAG, dl);
  5224. // The MEMCPY must go outside the CALLSEQ_START..END.
  5225. int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
  5226. SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
  5227. SDLoc(MemcpyCall));
  5228. DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
  5229. NewCallSeqStart.getNode());
  5230. return NewCallSeqStart;
  5231. }
  5232. SDValue PPCTargetLowering::LowerCall_64SVR4(
  5233. SDValue Chain, SDValue Callee, CallFlags CFlags,
  5234. const SmallVectorImpl<ISD::OutputArg> &Outs,
  5235. const SmallVectorImpl<SDValue> &OutVals,
  5236. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
  5237. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
  5238. const CallBase *CB) const {
  5239. bool isELFv2ABI = Subtarget.isELFv2ABI();
  5240. bool isLittleEndian = Subtarget.isLittleEndian();
  5241. unsigned NumOps = Outs.size();
  5242. bool IsSibCall = false;
  5243. bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
  5244. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  5245. unsigned PtrByteSize = 8;
  5246. MachineFunction &MF = DAG.getMachineFunction();
  5247. if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
  5248. IsSibCall = true;
  5249. // Mark this function as potentially containing a function that contains a
  5250. // tail call. As a consequence the frame pointer will be used for dynamicalloc
  5251. // and restoring the callers stack pointer in this functions epilog. This is
  5252. // done because by tail calling the called function might overwrite the value
  5253. // in this function's (MF) stack pointer stack slot 0(SP).
  5254. if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
  5255. MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
  5256. assert(!(IsFastCall && CFlags.IsVarArg) &&
  5257. "fastcc not supported on varargs functions");
  5258. // Count how many bytes are to be pushed on the stack, including the linkage
  5259. // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
  5260. // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
  5261. // area is 32 bytes reserved space for [SP][CR][LR][TOC].
  5262. unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
  5263. unsigned NumBytes = LinkageSize;
  5264. unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
  5265. static const MCPhysReg GPR[] = {
  5266. PPC::X3, PPC::X4, PPC::X5, PPC::X6,
  5267. PPC::X7, PPC::X8, PPC::X9, PPC::X10,
  5268. };
  5269. static const MCPhysReg VR[] = {
  5270. PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
  5271. PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
  5272. };
  5273. const unsigned NumGPRs = std::size(GPR);
  5274. const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
  5275. const unsigned NumVRs = std::size(VR);
  5276. // On ELFv2, we can avoid allocating the parameter area if all the arguments
  5277. // can be passed to the callee in registers.
  5278. // For the fast calling convention, there is another check below.
  5279. // Note: We should keep consistent with LowerFormalArguments_64SVR4()
  5280. bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
  5281. if (!HasParameterArea) {
  5282. unsigned ParamAreaSize = NumGPRs * PtrByteSize;
  5283. unsigned AvailableFPRs = NumFPRs;
  5284. unsigned AvailableVRs = NumVRs;
  5285. unsigned NumBytesTmp = NumBytes;
  5286. for (unsigned i = 0; i != NumOps; ++i) {
  5287. if (Outs[i].Flags.isNest()) continue;
  5288. if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
  5289. PtrByteSize, LinkageSize, ParamAreaSize,
  5290. NumBytesTmp, AvailableFPRs, AvailableVRs))
  5291. HasParameterArea = true;
  5292. }
  5293. }
  5294. // When using the fast calling convention, we don't provide backing for
  5295. // arguments that will be in registers.
  5296. unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
  5297. // Avoid allocating parameter area for fastcc functions if all the arguments
  5298. // can be passed in the registers.
  5299. if (IsFastCall)
  5300. HasParameterArea = false;
  5301. // Add up all the space actually used.
  5302. for (unsigned i = 0; i != NumOps; ++i) {
  5303. ISD::ArgFlagsTy Flags = Outs[i].Flags;
  5304. EVT ArgVT = Outs[i].VT;
  5305. EVT OrigVT = Outs[i].ArgVT;
  5306. if (Flags.isNest())
  5307. continue;
  5308. if (IsFastCall) {
  5309. if (Flags.isByVal()) {
  5310. NumGPRsUsed += (Flags.getByValSize()+7)/8;
  5311. if (NumGPRsUsed > NumGPRs)
  5312. HasParameterArea = true;
  5313. } else {
  5314. switch (ArgVT.getSimpleVT().SimpleTy) {
  5315. default: llvm_unreachable("Unexpected ValueType for argument!");
  5316. case MVT::i1:
  5317. case MVT::i32:
  5318. case MVT::i64:
  5319. if (++NumGPRsUsed <= NumGPRs)
  5320. continue;
  5321. break;
  5322. case MVT::v4i32:
  5323. case MVT::v8i16:
  5324. case MVT::v16i8:
  5325. case MVT::v2f64:
  5326. case MVT::v2i64:
  5327. case MVT::v1i128:
  5328. case MVT::f128:
  5329. if (++NumVRsUsed <= NumVRs)
  5330. continue;
  5331. break;
  5332. case MVT::v4f32:
  5333. if (++NumVRsUsed <= NumVRs)
  5334. continue;
  5335. break;
  5336. case MVT::f32:
  5337. case MVT::f64:
  5338. if (++NumFPRsUsed <= NumFPRs)
  5339. continue;
  5340. break;
  5341. }
  5342. HasParameterArea = true;
  5343. }
  5344. }
  5345. /* Respect alignment of argument on the stack. */
  5346. auto Alignement =
  5347. CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
  5348. NumBytes = alignTo(NumBytes, Alignement);
  5349. NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
  5350. if (Flags.isInConsecutiveRegsLast())
  5351. NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
  5352. }
  5353. unsigned NumBytesActuallyUsed = NumBytes;
  5354. // In the old ELFv1 ABI,
  5355. // the prolog code of the callee may store up to 8 GPR argument registers to
  5356. // the stack, allowing va_start to index over them in memory if its varargs.
  5357. // Because we cannot tell if this is needed on the caller side, we have to
  5358. // conservatively assume that it is needed. As such, make sure we have at
  5359. // least enough stack space for the caller to store the 8 GPRs.
  5360. // In the ELFv2 ABI, we allocate the parameter area iff a callee
  5361. // really requires memory operands, e.g. a vararg function.
  5362. if (HasParameterArea)
  5363. NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
  5364. else
  5365. NumBytes = LinkageSize;
  5366. // Tail call needs the stack to be aligned.
  5367. if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
  5368. NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
  5369. int SPDiff = 0;
  5370. // Calculate by how many bytes the stack has to be adjusted in case of tail
  5371. // call optimization.
  5372. if (!IsSibCall)
  5373. SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
  5374. // To protect arguments on the stack from being clobbered in a tail call,
  5375. // force all the loads to happen before doing any other lowering.
  5376. if (CFlags.IsTailCall)
  5377. Chain = DAG.getStackArgumentTokenFactor(Chain);
  5378. // Adjust the stack pointer for the new arguments...
  5379. // These operations are automatically eliminated by the prolog/epilog pass
  5380. if (!IsSibCall)
  5381. Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
  5382. SDValue CallSeqStart = Chain;
  5383. // Load the return address and frame pointer so it can be move somewhere else
  5384. // later.
  5385. SDValue LROp, FPOp;
  5386. Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
  5387. // Set up a copy of the stack pointer for use loading and storing any
  5388. // arguments that may not fit in the registers available for argument
  5389. // passing.
  5390. SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
  5391. // Figure out which arguments are going to go in registers, and which in
  5392. // memory. Also, if this is a vararg function, floating point operations
  5393. // must be stored to our stack, and loaded into integer regs as well, if
  5394. // any integer regs are available for argument passing.
  5395. unsigned ArgOffset = LinkageSize;
  5396. SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
  5397. SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
  5398. SmallVector<SDValue, 8> MemOpChains;
  5399. for (unsigned i = 0; i != NumOps; ++i) {
  5400. SDValue Arg = OutVals[i];
  5401. ISD::ArgFlagsTy Flags = Outs[i].Flags;
  5402. EVT ArgVT = Outs[i].VT;
  5403. EVT OrigVT = Outs[i].ArgVT;
  5404. // PtrOff will be used to store the current argument to the stack if a
  5405. // register cannot be found for it.
  5406. SDValue PtrOff;
  5407. // We re-align the argument offset for each argument, except when using the
  5408. // fast calling convention, when we need to make sure we do that only when
  5409. // we'll actually use a stack slot.
  5410. auto ComputePtrOff = [&]() {
  5411. /* Respect alignment of argument on the stack. */
  5412. auto Alignment =
  5413. CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
  5414. ArgOffset = alignTo(ArgOffset, Alignment);
  5415. PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
  5416. PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
  5417. };
  5418. if (!IsFastCall) {
  5419. ComputePtrOff();
  5420. /* Compute GPR index associated with argument offset. */
  5421. GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
  5422. GPR_idx = std::min(GPR_idx, NumGPRs);
  5423. }
  5424. // Promote integers to 64-bit values.
  5425. if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
  5426. // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
  5427. unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  5428. Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
  5429. }
  5430. // FIXME memcpy is used way more than necessary. Correctness first.
  5431. // Note: "by value" is code for passing a structure by value, not
  5432. // basic types.
  5433. if (Flags.isByVal()) {
  5434. // Note: Size includes alignment padding, so
  5435. // struct x { short a; char b; }
  5436. // will have Size = 4. With #pragma pack(1), it will have Size = 3.
  5437. // These are the proper values we need for right-justifying the
  5438. // aggregate in a parameter register.
  5439. unsigned Size = Flags.getByValSize();
  5440. // An empty aggregate parameter takes up no storage and no
  5441. // registers.
  5442. if (Size == 0)
  5443. continue;
  5444. if (IsFastCall)
  5445. ComputePtrOff();
  5446. // All aggregates smaller than 8 bytes must be passed right-justified.
  5447. if (Size==1 || Size==2 || Size==4) {
  5448. EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
  5449. if (GPR_idx != NumGPRs) {
  5450. SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
  5451. MachinePointerInfo(), VT);
  5452. MemOpChains.push_back(Load.getValue(1));
  5453. RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
  5454. ArgOffset += PtrByteSize;
  5455. continue;
  5456. }
  5457. }
  5458. if (GPR_idx == NumGPRs && Size < 8) {
  5459. SDValue AddPtr = PtrOff;
  5460. if (!isLittleEndian) {
  5461. SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
  5462. PtrOff.getValueType());
  5463. AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
  5464. }
  5465. Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
  5466. CallSeqStart,
  5467. Flags, DAG, dl);
  5468. ArgOffset += PtrByteSize;
  5469. continue;
  5470. }
  5471. // Copy the object to parameter save area if it can not be entirely passed
  5472. // by registers.
  5473. // FIXME: we only need to copy the parts which need to be passed in
  5474. // parameter save area. For the parts passed by registers, we don't need
  5475. // to copy them to the stack although we need to allocate space for them
  5476. // in parameter save area.
  5477. if ((NumGPRs - GPR_idx) * PtrByteSize < Size)
  5478. Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
  5479. CallSeqStart,
  5480. Flags, DAG, dl);
  5481. // When a register is available, pass a small aggregate right-justified.
  5482. if (Size < 8 && GPR_idx != NumGPRs) {
  5483. // The easiest way to get this right-justified in a register
  5484. // is to copy the structure into the rightmost portion of a
  5485. // local variable slot, then load the whole slot into the
  5486. // register.
  5487. // FIXME: The memcpy seems to produce pretty awful code for
  5488. // small aggregates, particularly for packed ones.
  5489. // FIXME: It would be preferable to use the slot in the
  5490. // parameter save area instead of a new local variable.
  5491. SDValue AddPtr = PtrOff;
  5492. if (!isLittleEndian) {
  5493. SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
  5494. AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
  5495. }
  5496. Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
  5497. CallSeqStart,
  5498. Flags, DAG, dl);
  5499. // Load the slot into the register.
  5500. SDValue Load =
  5501. DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
  5502. MemOpChains.push_back(Load.getValue(1));
  5503. RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
  5504. // Done with this argument.
  5505. ArgOffset += PtrByteSize;
  5506. continue;
  5507. }
  5508. // For aggregates larger than PtrByteSize, copy the pieces of the
  5509. // object that fit into registers from the parameter save area.
  5510. for (unsigned j=0; j<Size; j+=PtrByteSize) {
  5511. SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
  5512. SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
  5513. if (GPR_idx != NumGPRs) {
  5514. unsigned LoadSizeInBits = std::min(PtrByteSize, (Size - j)) * 8;
  5515. EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), LoadSizeInBits);
  5516. SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, AddArg,
  5517. MachinePointerInfo(), ObjType);
  5518. MemOpChains.push_back(Load.getValue(1));
  5519. RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
  5520. ArgOffset += PtrByteSize;
  5521. } else {
  5522. ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
  5523. break;
  5524. }
  5525. }
  5526. continue;
  5527. }
  5528. switch (Arg.getSimpleValueType().SimpleTy) {
  5529. default: llvm_unreachable("Unexpected ValueType for argument!");
  5530. case MVT::i1:
  5531. case MVT::i32:
  5532. case MVT::i64:
  5533. if (Flags.isNest()) {
  5534. // The 'nest' parameter, if any, is passed in R11.
  5535. RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
  5536. break;
  5537. }
  5538. // These can be scalar arguments or elements of an integer array type
  5539. // passed directly. Clang may use those instead of "byval" aggregate
  5540. // types to avoid forcing arguments to memory unnecessarily.
  5541. if (GPR_idx != NumGPRs) {
  5542. RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
  5543. } else {
  5544. if (IsFastCall)
  5545. ComputePtrOff();
  5546. assert(HasParameterArea &&
  5547. "Parameter area must exist to pass an argument in memory.");
  5548. LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
  5549. true, CFlags.IsTailCall, false, MemOpChains,
  5550. TailCallArguments, dl);
  5551. if (IsFastCall)
  5552. ArgOffset += PtrByteSize;
  5553. }
  5554. if (!IsFastCall)
  5555. ArgOffset += PtrByteSize;
  5556. break;
  5557. case MVT::f32:
  5558. case MVT::f64: {
  5559. // These can be scalar arguments or elements of a float array type
  5560. // passed directly. The latter are used to implement ELFv2 homogenous
  5561. // float aggregates.
  5562. // Named arguments go into FPRs first, and once they overflow, the
  5563. // remaining arguments go into GPRs and then the parameter save area.
  5564. // Unnamed arguments for vararg functions always go to GPRs and
  5565. // then the parameter save area. For now, put all arguments to vararg
  5566. // routines always in both locations (FPR *and* GPR or stack slot).
  5567. bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
  5568. bool NeededLoad = false;
  5569. // First load the argument into the next available FPR.
  5570. if (FPR_idx != NumFPRs)
  5571. RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
  5572. // Next, load the argument into GPR or stack slot if needed.
  5573. if (!NeedGPROrStack)
  5574. ;
  5575. else if (GPR_idx != NumGPRs && !IsFastCall) {
  5576. // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
  5577. // once we support fp <-> gpr moves.
  5578. // In the non-vararg case, this can only ever happen in the
  5579. // presence of f32 array types, since otherwise we never run
  5580. // out of FPRs before running out of GPRs.
  5581. SDValue ArgVal;
  5582. // Double values are always passed in a single GPR.
  5583. if (Arg.getValueType() != MVT::f32) {
  5584. ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
  5585. // Non-array float values are extended and passed in a GPR.
  5586. } else if (!Flags.isInConsecutiveRegs()) {
  5587. ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
  5588. ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
  5589. // If we have an array of floats, we collect every odd element
  5590. // together with its predecessor into one GPR.
  5591. } else if (ArgOffset % PtrByteSize != 0) {
  5592. SDValue Lo, Hi;
  5593. Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
  5594. Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
  5595. if (!isLittleEndian)
  5596. std::swap(Lo, Hi);
  5597. ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
  5598. // The final element, if even, goes into the first half of a GPR.
  5599. } else if (Flags.isInConsecutiveRegsLast()) {
  5600. ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
  5601. ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
  5602. if (!isLittleEndian)
  5603. ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
  5604. DAG.getConstant(32, dl, MVT::i32));
  5605. // Non-final even elements are skipped; they will be handled
  5606. // together the with subsequent argument on the next go-around.
  5607. } else
  5608. ArgVal = SDValue();
  5609. if (ArgVal.getNode())
  5610. RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
  5611. } else {
  5612. if (IsFastCall)
  5613. ComputePtrOff();
  5614. // Single-precision floating-point values are mapped to the
  5615. // second (rightmost) word of the stack doubleword.
  5616. if (Arg.getValueType() == MVT::f32 &&
  5617. !isLittleEndian && !Flags.isInConsecutiveRegs()) {
  5618. SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
  5619. PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
  5620. }
  5621. assert(HasParameterArea &&
  5622. "Parameter area must exist to pass an argument in memory.");
  5623. LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
  5624. true, CFlags.IsTailCall, false, MemOpChains,
  5625. TailCallArguments, dl);
  5626. NeededLoad = true;
  5627. }
  5628. // When passing an array of floats, the array occupies consecutive
  5629. // space in the argument area; only round up to the next doubleword
  5630. // at the end of the array. Otherwise, each float takes 8 bytes.
  5631. if (!IsFastCall || NeededLoad) {
  5632. ArgOffset += (Arg.getValueType() == MVT::f32 &&
  5633. Flags.isInConsecutiveRegs()) ? 4 : 8;
  5634. if (Flags.isInConsecutiveRegsLast())
  5635. ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
  5636. }
  5637. break;
  5638. }
  5639. case MVT::v4f32:
  5640. case MVT::v4i32:
  5641. case MVT::v8i16:
  5642. case MVT::v16i8:
  5643. case MVT::v2f64:
  5644. case MVT::v2i64:
  5645. case MVT::v1i128:
  5646. case MVT::f128:
  5647. // These can be scalar arguments or elements of a vector array type
  5648. // passed directly. The latter are used to implement ELFv2 homogenous
  5649. // vector aggregates.
  5650. // For a varargs call, named arguments go into VRs or on the stack as
  5651. // usual; unnamed arguments always go to the stack or the corresponding
  5652. // GPRs when within range. For now, we always put the value in both
  5653. // locations (or even all three).
  5654. if (CFlags.IsVarArg) {
  5655. assert(HasParameterArea &&
  5656. "Parameter area must exist if we have a varargs call.");
  5657. // We could elide this store in the case where the object fits
  5658. // entirely in R registers. Maybe later.
  5659. SDValue Store =
  5660. DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
  5661. MemOpChains.push_back(Store);
  5662. if (VR_idx != NumVRs) {
  5663. SDValue Load =
  5664. DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
  5665. MemOpChains.push_back(Load.getValue(1));
  5666. RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
  5667. }
  5668. ArgOffset += 16;
  5669. for (unsigned i=0; i<16; i+=PtrByteSize) {
  5670. if (GPR_idx == NumGPRs)
  5671. break;
  5672. SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
  5673. DAG.getConstant(i, dl, PtrVT));
  5674. SDValue Load =
  5675. DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
  5676. MemOpChains.push_back(Load.getValue(1));
  5677. RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
  5678. }
  5679. break;
  5680. }
  5681. // Non-varargs Altivec params go into VRs or on the stack.
  5682. if (VR_idx != NumVRs) {
  5683. RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
  5684. } else {
  5685. if (IsFastCall)
  5686. ComputePtrOff();
  5687. assert(HasParameterArea &&
  5688. "Parameter area must exist to pass an argument in memory.");
  5689. LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
  5690. true, CFlags.IsTailCall, true, MemOpChains,
  5691. TailCallArguments, dl);
  5692. if (IsFastCall)
  5693. ArgOffset += 16;
  5694. }
  5695. if (!IsFastCall)
  5696. ArgOffset += 16;
  5697. break;
  5698. }
  5699. }
  5700. assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
  5701. "mismatch in size of parameter area");
  5702. (void)NumBytesActuallyUsed;
  5703. if (!MemOpChains.empty())
  5704. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
  5705. // Check if this is an indirect call (MTCTR/BCTRL).
  5706. // See prepareDescriptorIndirectCall and buildCallOperands for more
  5707. // information about calls through function pointers in the 64-bit SVR4 ABI.
  5708. if (CFlags.IsIndirect) {
  5709. // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
  5710. // caller in the TOC save area.
  5711. if (isTOCSaveRestoreRequired(Subtarget)) {
  5712. assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
  5713. // Load r2 into a virtual register and store it to the TOC save area.
  5714. setUsesTOCBasePtr(DAG);
  5715. SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
  5716. // TOC save area offset.
  5717. unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
  5718. SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
  5719. SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
  5720. Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
  5721. MachinePointerInfo::getStack(
  5722. DAG.getMachineFunction(), TOCSaveOffset));
  5723. }
  5724. // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
  5725. // This does not mean the MTCTR instruction must use R12; it's easier
  5726. // to model this as an extra parameter, so do that.
  5727. if (isELFv2ABI && !CFlags.IsPatchPoint)
  5728. RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
  5729. }
  5730. // Build a sequence of copy-to-reg nodes chained together with token chain
  5731. // and flag operands which copy the outgoing args into the appropriate regs.
  5732. SDValue InFlag;
  5733. for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
  5734. Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
  5735. RegsToPass[i].second, InFlag);
  5736. InFlag = Chain.getValue(1);
  5737. }
  5738. if (CFlags.IsTailCall && !IsSibCall)
  5739. PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
  5740. TailCallArguments);
  5741. return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
  5742. Callee, SPDiff, NumBytes, Ins, InVals, CB);
  5743. }
  5744. // Returns true when the shadow of a general purpose argument register
  5745. // in the parameter save area is aligned to at least 'RequiredAlign'.
  5746. static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
  5747. assert(RequiredAlign.value() <= 16 &&
  5748. "Required alignment greater than stack alignment.");
  5749. switch (Reg) {
  5750. default:
  5751. report_fatal_error("called on invalid register.");
  5752. case PPC::R5:
  5753. case PPC::R9:
  5754. case PPC::X3:
  5755. case PPC::X5:
  5756. case PPC::X7:
  5757. case PPC::X9:
  5758. // These registers are 16 byte aligned which is the most strict aligment
  5759. // we can support.
  5760. return true;
  5761. case PPC::R3:
  5762. case PPC::R7:
  5763. case PPC::X4:
  5764. case PPC::X6:
  5765. case PPC::X8:
  5766. case PPC::X10:
  5767. // The shadow of these registers in the PSA is 8 byte aligned.
  5768. return RequiredAlign <= 8;
  5769. case PPC::R4:
  5770. case PPC::R6:
  5771. case PPC::R8:
  5772. case PPC::R10:
  5773. return RequiredAlign <= 4;
  5774. }
  5775. }
  5776. static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
  5777. CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
  5778. CCState &S) {
  5779. AIXCCState &State = static_cast<AIXCCState &>(S);
  5780. const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
  5781. State.getMachineFunction().getSubtarget());
  5782. const bool IsPPC64 = Subtarget.isPPC64();
  5783. const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
  5784. const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
  5785. if (ValVT == MVT::f128)
  5786. report_fatal_error("f128 is unimplemented on AIX.");
  5787. if (ArgFlags.isNest())
  5788. report_fatal_error("Nest arguments are unimplemented.");
  5789. static const MCPhysReg GPR_32[] = {// 32-bit registers.
  5790. PPC::R3, PPC::R4, PPC::R5, PPC::R6,
  5791. PPC::R7, PPC::R8, PPC::R9, PPC::R10};
  5792. static const MCPhysReg GPR_64[] = {// 64-bit registers.
  5793. PPC::X3, PPC::X4, PPC::X5, PPC::X6,
  5794. PPC::X7, PPC::X8, PPC::X9, PPC::X10};
  5795. static const MCPhysReg VR[] = {// Vector registers.
  5796. PPC::V2, PPC::V3, PPC::V4, PPC::V5,
  5797. PPC::V6, PPC::V7, PPC::V8, PPC::V9,
  5798. PPC::V10, PPC::V11, PPC::V12, PPC::V13};
  5799. if (ArgFlags.isByVal()) {
  5800. if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
  5801. report_fatal_error("Pass-by-value arguments with alignment greater than "
  5802. "register width are not supported.");
  5803. const unsigned ByValSize = ArgFlags.getByValSize();
  5804. // An empty aggregate parameter takes up no storage and no registers,
  5805. // but needs a MemLoc for a stack slot for the formal arguments side.
  5806. if (ByValSize == 0) {
  5807. State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
  5808. State.getNextStackOffset(), RegVT,
  5809. LocInfo));
  5810. return false;
  5811. }
  5812. const unsigned StackSize = alignTo(ByValSize, PtrAlign);
  5813. unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
  5814. for (const unsigned E = Offset + StackSize; Offset < E;
  5815. Offset += PtrAlign.value()) {
  5816. if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
  5817. State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
  5818. else {
  5819. State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
  5820. Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
  5821. LocInfo));
  5822. break;
  5823. }
  5824. }
  5825. return false;
  5826. }
  5827. // Arguments always reserve parameter save area.
  5828. switch (ValVT.SimpleTy) {
  5829. default:
  5830. report_fatal_error("Unhandled value type for argument.");
  5831. case MVT::i64:
  5832. // i64 arguments should have been split to i32 for PPC32.
  5833. assert(IsPPC64 && "PPC32 should have split i64 values.");
  5834. [[fallthrough]];
  5835. case MVT::i1:
  5836. case MVT::i32: {
  5837. const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
  5838. // AIX integer arguments are always passed in register width.
  5839. if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
  5840. LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
  5841. : CCValAssign::LocInfo::ZExt;
  5842. if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
  5843. State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
  5844. else
  5845. State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
  5846. return false;
  5847. }
  5848. case MVT::f32:
  5849. case MVT::f64: {
  5850. // Parameter save area (PSA) is reserved even if the float passes in fpr.
  5851. const unsigned StoreSize = LocVT.getStoreSize();
  5852. // Floats are always 4-byte aligned in the PSA on AIX.
  5853. // This includes f64 in 64-bit mode for ABI compatibility.
  5854. const unsigned Offset =
  5855. State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
  5856. unsigned FReg = State.AllocateReg(FPR);
  5857. if (FReg)
  5858. State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
  5859. // Reserve and initialize GPRs or initialize the PSA as required.
  5860. for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
  5861. if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
  5862. assert(FReg && "An FPR should be available when a GPR is reserved.");
  5863. if (State.isVarArg()) {
  5864. // Successfully reserved GPRs are only initialized for vararg calls.
  5865. // Custom handling is required for:
  5866. // f64 in PPC32 needs to be split into 2 GPRs.
  5867. // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
  5868. State.addLoc(
  5869. CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
  5870. }
  5871. } else {
  5872. // If there are insufficient GPRs, the PSA needs to be initialized.
  5873. // Initialization occurs even if an FPR was initialized for
  5874. // compatibility with the AIX XL compiler. The full memory for the
  5875. // argument will be initialized even if a prior word is saved in GPR.
  5876. // A custom memLoc is used when the argument also passes in FPR so
  5877. // that the callee handling can skip over it easily.
  5878. State.addLoc(
  5879. FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
  5880. LocInfo)
  5881. : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
  5882. break;
  5883. }
  5884. }
  5885. return false;
  5886. }
  5887. case MVT::v4f32:
  5888. case MVT::v4i32:
  5889. case MVT::v8i16:
  5890. case MVT::v16i8:
  5891. case MVT::v2i64:
  5892. case MVT::v2f64:
  5893. case MVT::v1i128: {
  5894. const unsigned VecSize = 16;
  5895. const Align VecAlign(VecSize);
  5896. if (!State.isVarArg()) {
  5897. // If there are vector registers remaining we don't consume any stack
  5898. // space.
  5899. if (unsigned VReg = State.AllocateReg(VR)) {
  5900. State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
  5901. return false;
  5902. }
  5903. // Vectors passed on the stack do not shadow GPRs or FPRs even though they
  5904. // might be allocated in the portion of the PSA that is shadowed by the
  5905. // GPRs.
  5906. const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
  5907. State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
  5908. return false;
  5909. }
  5910. const unsigned PtrSize = IsPPC64 ? 8 : 4;
  5911. ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
  5912. unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
  5913. // Burn any underaligned registers and their shadowed stack space until
  5914. // we reach the required alignment.
  5915. while (NextRegIndex != GPRs.size() &&
  5916. !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
  5917. // Shadow allocate register and its stack shadow.
  5918. unsigned Reg = State.AllocateReg(GPRs);
  5919. State.AllocateStack(PtrSize, PtrAlign);
  5920. assert(Reg && "Allocating register unexpectedly failed.");
  5921. (void)Reg;
  5922. NextRegIndex = State.getFirstUnallocated(GPRs);
  5923. }
  5924. // Vectors that are passed as fixed arguments are handled differently.
  5925. // They are passed in VRs if any are available (unlike arguments passed
  5926. // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
  5927. // functions)
  5928. if (State.isFixed(ValNo)) {
  5929. if (unsigned VReg = State.AllocateReg(VR)) {
  5930. State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
  5931. // Shadow allocate GPRs and stack space even though we pass in a VR.
  5932. for (unsigned I = 0; I != VecSize; I += PtrSize)
  5933. State.AllocateReg(GPRs);
  5934. State.AllocateStack(VecSize, VecAlign);
  5935. return false;
  5936. }
  5937. // No vector registers remain so pass on the stack.
  5938. const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
  5939. State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
  5940. return false;
  5941. }
  5942. // If all GPRS are consumed then we pass the argument fully on the stack.
  5943. if (NextRegIndex == GPRs.size()) {
  5944. const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
  5945. State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
  5946. return false;
  5947. }
  5948. // Corner case for 32-bit codegen. We have 2 registers to pass the first
  5949. // half of the argument, and then need to pass the remaining half on the
  5950. // stack.
  5951. if (GPRs[NextRegIndex] == PPC::R9) {
  5952. const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
  5953. State.addLoc(
  5954. CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
  5955. const unsigned FirstReg = State.AllocateReg(PPC::R9);
  5956. const unsigned SecondReg = State.AllocateReg(PPC::R10);
  5957. assert(FirstReg && SecondReg &&
  5958. "Allocating R9 or R10 unexpectedly failed.");
  5959. State.addLoc(
  5960. CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
  5961. State.addLoc(
  5962. CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
  5963. return false;
  5964. }
  5965. // We have enough GPRs to fully pass the vector argument, and we have
  5966. // already consumed any underaligned registers. Start with the custom
  5967. // MemLoc and then the custom RegLocs.
  5968. const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
  5969. State.addLoc(
  5970. CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
  5971. for (unsigned I = 0; I != VecSize; I += PtrSize) {
  5972. const unsigned Reg = State.AllocateReg(GPRs);
  5973. assert(Reg && "Failed to allocated register for vararg vector argument");
  5974. State.addLoc(
  5975. CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
  5976. }
  5977. return false;
  5978. }
  5979. }
  5980. return true;
  5981. }
  5982. // So far, this function is only used by LowerFormalArguments_AIX()
  5983. static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
  5984. bool IsPPC64,
  5985. bool HasP8Vector,
  5986. bool HasVSX) {
  5987. assert((IsPPC64 || SVT != MVT::i64) &&
  5988. "i64 should have been split for 32-bit codegen.");
  5989. switch (SVT) {
  5990. default:
  5991. report_fatal_error("Unexpected value type for formal argument");
  5992. case MVT::i1:
  5993. case MVT::i32:
  5994. case MVT::i64:
  5995. return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
  5996. case MVT::f32:
  5997. return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass;
  5998. case MVT::f64:
  5999. return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass;
  6000. case MVT::v4f32:
  6001. case MVT::v4i32:
  6002. case MVT::v8i16:
  6003. case MVT::v16i8:
  6004. case MVT::v2i64:
  6005. case MVT::v2f64:
  6006. case MVT::v1i128:
  6007. return &PPC::VRRCRegClass;
  6008. }
  6009. }
  6010. static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
  6011. SelectionDAG &DAG, SDValue ArgValue,
  6012. MVT LocVT, const SDLoc &dl) {
  6013. assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
  6014. assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
  6015. if (Flags.isSExt())
  6016. ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
  6017. DAG.getValueType(ValVT));
  6018. else if (Flags.isZExt())
  6019. ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
  6020. DAG.getValueType(ValVT));
  6021. return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
  6022. }
  6023. static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
  6024. const unsigned LASize = FL->getLinkageSize();
  6025. if (PPC::GPRCRegClass.contains(Reg)) {
  6026. assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
  6027. "Reg must be a valid argument register!");
  6028. return LASize + 4 * (Reg - PPC::R3);
  6029. }
  6030. if (PPC::G8RCRegClass.contains(Reg)) {
  6031. assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
  6032. "Reg must be a valid argument register!");
  6033. return LASize + 8 * (Reg - PPC::X3);
  6034. }
  6035. llvm_unreachable("Only general purpose registers expected.");
  6036. }
  6037. // AIX ABI Stack Frame Layout:
  6038. //
  6039. // Low Memory +--------------------------------------------+
  6040. // SP +---> | Back chain | ---+
  6041. // | +--------------------------------------------+ |
  6042. // | | Saved Condition Register | |
  6043. // | +--------------------------------------------+ |
  6044. // | | Saved Linkage Register | |
  6045. // | +--------------------------------------------+ | Linkage Area
  6046. // | | Reserved for compilers | |
  6047. // | +--------------------------------------------+ |
  6048. // | | Reserved for binders | |
  6049. // | +--------------------------------------------+ |
  6050. // | | Saved TOC pointer | ---+
  6051. // | +--------------------------------------------+
  6052. // | | Parameter save area |
  6053. // | +--------------------------------------------+
  6054. // | | Alloca space |
  6055. // | +--------------------------------------------+
  6056. // | | Local variable space |
  6057. // | +--------------------------------------------+
  6058. // | | Float/int conversion temporary |
  6059. // | +--------------------------------------------+
  6060. // | | Save area for AltiVec registers |
  6061. // | +--------------------------------------------+
  6062. // | | AltiVec alignment padding |
  6063. // | +--------------------------------------------+
  6064. // | | Save area for VRSAVE register |
  6065. // | +--------------------------------------------+
  6066. // | | Save area for General Purpose registers |
  6067. // | +--------------------------------------------+
  6068. // | | Save area for Floating Point registers |
  6069. // | +--------------------------------------------+
  6070. // +---- | Back chain |
  6071. // High Memory +--------------------------------------------+
  6072. //
  6073. // Specifications:
  6074. // AIX 7.2 Assembler Language Reference
  6075. // Subroutine linkage convention
  6076. SDValue PPCTargetLowering::LowerFormalArguments_AIX(
  6077. SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
  6078. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
  6079. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
  6080. assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
  6081. CallConv == CallingConv::Fast) &&
  6082. "Unexpected calling convention!");
  6083. if (getTargetMachine().Options.GuaranteedTailCallOpt)
  6084. report_fatal_error("Tail call support is unimplemented on AIX.");
  6085. if (useSoftFloat())
  6086. report_fatal_error("Soft float support is unimplemented on AIX.");
  6087. const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
  6088. const bool IsPPC64 = Subtarget.isPPC64();
  6089. const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
  6090. // Assign locations to all of the incoming arguments.
  6091. SmallVector<CCValAssign, 16> ArgLocs;
  6092. MachineFunction &MF = DAG.getMachineFunction();
  6093. MachineFrameInfo &MFI = MF.getFrameInfo();
  6094. PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  6095. AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
  6096. const EVT PtrVT = getPointerTy(MF.getDataLayout());
  6097. // Reserve space for the linkage area on the stack.
  6098. const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
  6099. CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
  6100. CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
  6101. SmallVector<SDValue, 8> MemOps;
  6102. for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
  6103. CCValAssign &VA = ArgLocs[I++];
  6104. MVT LocVT = VA.getLocVT();
  6105. MVT ValVT = VA.getValVT();
  6106. ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
  6107. // For compatibility with the AIX XL compiler, the float args in the
  6108. // parameter save area are initialized even if the argument is available
  6109. // in register. The caller is required to initialize both the register
  6110. // and memory, however, the callee can choose to expect it in either.
  6111. // The memloc is dismissed here because the argument is retrieved from
  6112. // the register.
  6113. if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
  6114. continue;
  6115. auto HandleMemLoc = [&]() {
  6116. const unsigned LocSize = LocVT.getStoreSize();
  6117. const unsigned ValSize = ValVT.getStoreSize();
  6118. assert((ValSize <= LocSize) &&
  6119. "Object size is larger than size of MemLoc");
  6120. int CurArgOffset = VA.getLocMemOffset();
  6121. // Objects are right-justified because AIX is big-endian.
  6122. if (LocSize > ValSize)
  6123. CurArgOffset += LocSize - ValSize;
  6124. // Potential tail calls could cause overwriting of argument stack slots.
  6125. const bool IsImmutable =
  6126. !(getTargetMachine().Options.GuaranteedTailCallOpt &&
  6127. (CallConv == CallingConv::Fast));
  6128. int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
  6129. SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
  6130. SDValue ArgValue =
  6131. DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
  6132. InVals.push_back(ArgValue);
  6133. };
  6134. // Vector arguments to VaArg functions are passed both on the stack, and
  6135. // in any available GPRs. Load the value from the stack and add the GPRs
  6136. // as live ins.
  6137. if (VA.isMemLoc() && VA.needsCustom()) {
  6138. assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
  6139. assert(isVarArg && "Only use custom memloc for vararg.");
  6140. // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
  6141. // matching custom RegLocs.
  6142. const unsigned OriginalValNo = VA.getValNo();
  6143. (void)OriginalValNo;
  6144. auto HandleCustomVecRegLoc = [&]() {
  6145. assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
  6146. "Missing custom RegLoc.");
  6147. VA = ArgLocs[I++];
  6148. assert(VA.getValVT().isVector() &&
  6149. "Unexpected Val type for custom RegLoc.");
  6150. assert(VA.getValNo() == OriginalValNo &&
  6151. "ValNo mismatch between custom MemLoc and RegLoc.");
  6152. MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy;
  6153. MF.addLiveIn(VA.getLocReg(),
  6154. getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
  6155. Subtarget.hasVSX()));
  6156. };
  6157. HandleMemLoc();
  6158. // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
  6159. // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
  6160. // R10.
  6161. HandleCustomVecRegLoc();
  6162. HandleCustomVecRegLoc();
  6163. // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
  6164. // we passed the vector in R5, R6, R7 and R8.
  6165. if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
  6166. assert(!IsPPC64 &&
  6167. "Only 2 custom RegLocs expected for 64-bit codegen.");
  6168. HandleCustomVecRegLoc();
  6169. HandleCustomVecRegLoc();
  6170. }
  6171. continue;
  6172. }
  6173. if (VA.isRegLoc()) {
  6174. if (VA.getValVT().isScalarInteger())
  6175. FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
  6176. else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) {
  6177. switch (VA.getValVT().SimpleTy) {
  6178. default:
  6179. report_fatal_error("Unhandled value type for argument.");
  6180. case MVT::f32:
  6181. FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint);
  6182. break;
  6183. case MVT::f64:
  6184. FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint);
  6185. break;
  6186. }
  6187. } else if (VA.getValVT().isVector()) {
  6188. switch (VA.getValVT().SimpleTy) {
  6189. default:
  6190. report_fatal_error("Unhandled value type for argument.");
  6191. case MVT::v16i8:
  6192. FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar);
  6193. break;
  6194. case MVT::v8i16:
  6195. FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort);
  6196. break;
  6197. case MVT::v4i32:
  6198. case MVT::v2i64:
  6199. case MVT::v1i128:
  6200. FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt);
  6201. break;
  6202. case MVT::v4f32:
  6203. case MVT::v2f64:
  6204. FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat);
  6205. break;
  6206. }
  6207. }
  6208. }
  6209. if (Flags.isByVal() && VA.isMemLoc()) {
  6210. const unsigned Size =
  6211. alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
  6212. PtrByteSize);
  6213. const int FI = MF.getFrameInfo().CreateFixedObject(
  6214. Size, VA.getLocMemOffset(), /* IsImmutable */ false,
  6215. /* IsAliased */ true);
  6216. SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
  6217. InVals.push_back(FIN);
  6218. continue;
  6219. }
  6220. if (Flags.isByVal()) {
  6221. assert(VA.isRegLoc() && "MemLocs should already be handled.");
  6222. const MCPhysReg ArgReg = VA.getLocReg();
  6223. const PPCFrameLowering *FL = Subtarget.getFrameLowering();
  6224. if (Flags.getNonZeroByValAlign() > PtrByteSize)
  6225. report_fatal_error("Over aligned byvals not supported yet.");
  6226. const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
  6227. const int FI = MF.getFrameInfo().CreateFixedObject(
  6228. StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
  6229. /* IsAliased */ true);
  6230. SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
  6231. InVals.push_back(FIN);
  6232. // Add live ins for all the RegLocs for the same ByVal.
  6233. const TargetRegisterClass *RegClass =
  6234. IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
  6235. auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
  6236. unsigned Offset) {
  6237. const Register VReg = MF.addLiveIn(PhysReg, RegClass);
  6238. // Since the callers side has left justified the aggregate in the
  6239. // register, we can simply store the entire register into the stack
  6240. // slot.
  6241. SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
  6242. // The store to the fixedstack object is needed becuase accessing a
  6243. // field of the ByVal will use a gep and load. Ideally we will optimize
  6244. // to extracting the value from the register directly, and elide the
  6245. // stores when the arguments address is not taken, but that will need to
  6246. // be future work.
  6247. SDValue Store = DAG.getStore(
  6248. CopyFrom.getValue(1), dl, CopyFrom,
  6249. DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
  6250. MachinePointerInfo::getFixedStack(MF, FI, Offset));
  6251. MemOps.push_back(Store);
  6252. };
  6253. unsigned Offset = 0;
  6254. HandleRegLoc(VA.getLocReg(), Offset);
  6255. Offset += PtrByteSize;
  6256. for (; Offset != StackSize && ArgLocs[I].isRegLoc();
  6257. Offset += PtrByteSize) {
  6258. assert(ArgLocs[I].getValNo() == VA.getValNo() &&
  6259. "RegLocs should be for ByVal argument.");
  6260. const CCValAssign RL = ArgLocs[I++];
  6261. HandleRegLoc(RL.getLocReg(), Offset);
  6262. FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
  6263. }
  6264. if (Offset != StackSize) {
  6265. assert(ArgLocs[I].getValNo() == VA.getValNo() &&
  6266. "Expected MemLoc for remaining bytes.");
  6267. assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
  6268. // Consume the MemLoc.The InVal has already been emitted, so nothing
  6269. // more needs to be done.
  6270. ++I;
  6271. }
  6272. continue;
  6273. }
  6274. if (VA.isRegLoc() && !VA.needsCustom()) {
  6275. MVT::SimpleValueType SVT = ValVT.SimpleTy;
  6276. Register VReg =
  6277. MF.addLiveIn(VA.getLocReg(),
  6278. getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
  6279. Subtarget.hasVSX()));
  6280. SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
  6281. if (ValVT.isScalarInteger() &&
  6282. (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
  6283. ArgValue =
  6284. truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
  6285. }
  6286. InVals.push_back(ArgValue);
  6287. continue;
  6288. }
  6289. if (VA.isMemLoc()) {
  6290. HandleMemLoc();
  6291. continue;
  6292. }
  6293. }
  6294. // On AIX a minimum of 8 words is saved to the parameter save area.
  6295. const unsigned MinParameterSaveArea = 8 * PtrByteSize;
  6296. // Area that is at least reserved in the caller of this function.
  6297. unsigned CallerReservedArea =
  6298. std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
  6299. // Set the size that is at least reserved in caller of this function. Tail
  6300. // call optimized function's reserved stack space needs to be aligned so
  6301. // that taking the difference between two stack areas will result in an
  6302. // aligned stack.
  6303. CallerReservedArea =
  6304. EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
  6305. FuncInfo->setMinReservedArea(CallerReservedArea);
  6306. if (isVarArg) {
  6307. FuncInfo->setVarArgsFrameIndex(
  6308. MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
  6309. SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
  6310. static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
  6311. PPC::R7, PPC::R8, PPC::R9, PPC::R10};
  6312. static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
  6313. PPC::X7, PPC::X8, PPC::X9, PPC::X10};
  6314. const unsigned NumGPArgRegs = std::size(IsPPC64 ? GPR_64 : GPR_32);
  6315. // The fixed integer arguments of a variadic function are stored to the
  6316. // VarArgsFrameIndex on the stack so that they may be loaded by
  6317. // dereferencing the result of va_next.
  6318. for (unsigned GPRIndex =
  6319. (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
  6320. GPRIndex < NumGPArgRegs; ++GPRIndex) {
  6321. const Register VReg =
  6322. IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
  6323. : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
  6324. SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
  6325. SDValue Store =
  6326. DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
  6327. MemOps.push_back(Store);
  6328. // Increment the address for the next argument to store.
  6329. SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
  6330. FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
  6331. }
  6332. }
  6333. if (!MemOps.empty())
  6334. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
  6335. return Chain;
  6336. }
  6337. SDValue PPCTargetLowering::LowerCall_AIX(
  6338. SDValue Chain, SDValue Callee, CallFlags CFlags,
  6339. const SmallVectorImpl<ISD::OutputArg> &Outs,
  6340. const SmallVectorImpl<SDValue> &OutVals,
  6341. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
  6342. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
  6343. const CallBase *CB) const {
  6344. // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
  6345. // AIX ABI stack frame layout.
  6346. assert((CFlags.CallConv == CallingConv::C ||
  6347. CFlags.CallConv == CallingConv::Cold ||
  6348. CFlags.CallConv == CallingConv::Fast) &&
  6349. "Unexpected calling convention!");
  6350. if (CFlags.IsPatchPoint)
  6351. report_fatal_error("This call type is unimplemented on AIX.");
  6352. const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
  6353. MachineFunction &MF = DAG.getMachineFunction();
  6354. SmallVector<CCValAssign, 16> ArgLocs;
  6355. AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
  6356. *DAG.getContext());
  6357. // Reserve space for the linkage save area (LSA) on the stack.
  6358. // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
  6359. // [SP][CR][LR][2 x reserved][TOC].
  6360. // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
  6361. const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
  6362. const bool IsPPC64 = Subtarget.isPPC64();
  6363. const EVT PtrVT = getPointerTy(DAG.getDataLayout());
  6364. const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
  6365. CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
  6366. CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
  6367. // The prolog code of the callee may store up to 8 GPR argument registers to
  6368. // the stack, allowing va_start to index over them in memory if the callee
  6369. // is variadic.
  6370. // Because we cannot tell if this is needed on the caller side, we have to
  6371. // conservatively assume that it is needed. As such, make sure we have at
  6372. // least enough stack space for the caller to store the 8 GPRs.
  6373. const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
  6374. const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
  6375. CCInfo.getNextStackOffset());
  6376. // Adjust the stack pointer for the new arguments...
  6377. // These operations are automatically eliminated by the prolog/epilog pass.
  6378. Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
  6379. SDValue CallSeqStart = Chain;
  6380. SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
  6381. SmallVector<SDValue, 8> MemOpChains;
  6382. // Set up a copy of the stack pointer for loading and storing any
  6383. // arguments that may not fit in the registers available for argument
  6384. // passing.
  6385. const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
  6386. : DAG.getRegister(PPC::R1, MVT::i32);
  6387. for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
  6388. const unsigned ValNo = ArgLocs[I].getValNo();
  6389. SDValue Arg = OutVals[ValNo];
  6390. ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
  6391. if (Flags.isByVal()) {
  6392. const unsigned ByValSize = Flags.getByValSize();
  6393. // Nothing to do for zero-sized ByVals on the caller side.
  6394. if (!ByValSize) {
  6395. ++I;
  6396. continue;
  6397. }
  6398. auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
  6399. return DAG.getExtLoad(
  6400. ISD::ZEXTLOAD, dl, PtrVT, Chain,
  6401. (LoadOffset != 0)
  6402. ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
  6403. : Arg,
  6404. MachinePointerInfo(), VT);
  6405. };
  6406. unsigned LoadOffset = 0;
  6407. // Initialize registers, which are fully occupied by the by-val argument.
  6408. while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
  6409. SDValue Load = GetLoad(PtrVT, LoadOffset);
  6410. MemOpChains.push_back(Load.getValue(1));
  6411. LoadOffset += PtrByteSize;
  6412. const CCValAssign &ByValVA = ArgLocs[I++];
  6413. assert(ByValVA.getValNo() == ValNo &&
  6414. "Unexpected location for pass-by-value argument.");
  6415. RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
  6416. }
  6417. if (LoadOffset == ByValSize)
  6418. continue;
  6419. // There must be one more loc to handle the remainder.
  6420. assert(ArgLocs[I].getValNo() == ValNo &&
  6421. "Expected additional location for by-value argument.");
  6422. if (ArgLocs[I].isMemLoc()) {
  6423. assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
  6424. const CCValAssign &ByValVA = ArgLocs[I++];
  6425. ISD::ArgFlagsTy MemcpyFlags = Flags;
  6426. // Only memcpy the bytes that don't pass in register.
  6427. MemcpyFlags.setByValSize(ByValSize - LoadOffset);
  6428. Chain = CallSeqStart = createMemcpyOutsideCallSeq(
  6429. (LoadOffset != 0)
  6430. ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
  6431. : Arg,
  6432. DAG.getObjectPtrOffset(dl, StackPtr,
  6433. TypeSize::Fixed(ByValVA.getLocMemOffset())),
  6434. CallSeqStart, MemcpyFlags, DAG, dl);
  6435. continue;
  6436. }
  6437. // Initialize the final register residue.
  6438. // Any residue that occupies the final by-val arg register must be
  6439. // left-justified on AIX. Loads must be a power-of-2 size and cannot be
  6440. // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
  6441. // 2 and 1 byte loads.
  6442. const unsigned ResidueBytes = ByValSize % PtrByteSize;
  6443. assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
  6444. "Unexpected register residue for by-value argument.");
  6445. SDValue ResidueVal;
  6446. for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
  6447. const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
  6448. const MVT VT =
  6449. N == 1 ? MVT::i8
  6450. : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
  6451. SDValue Load = GetLoad(VT, LoadOffset);
  6452. MemOpChains.push_back(Load.getValue(1));
  6453. LoadOffset += N;
  6454. Bytes += N;
  6455. // By-val arguments are passed left-justfied in register.
  6456. // Every load here needs to be shifted, otherwise a full register load
  6457. // should have been used.
  6458. assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
  6459. "Unexpected load emitted during handling of pass-by-value "
  6460. "argument.");
  6461. unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
  6462. EVT ShiftAmountTy =
  6463. getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
  6464. SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
  6465. SDValue ShiftedLoad =
  6466. DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
  6467. ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
  6468. ShiftedLoad)
  6469. : ShiftedLoad;
  6470. }
  6471. const CCValAssign &ByValVA = ArgLocs[I++];
  6472. RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
  6473. continue;
  6474. }
  6475. CCValAssign &VA = ArgLocs[I++];
  6476. const MVT LocVT = VA.getLocVT();
  6477. const MVT ValVT = VA.getValVT();
  6478. switch (VA.getLocInfo()) {
  6479. default:
  6480. report_fatal_error("Unexpected argument extension type.");
  6481. case CCValAssign::Full:
  6482. break;
  6483. case CCValAssign::ZExt:
  6484. Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
  6485. break;
  6486. case CCValAssign::SExt:
  6487. Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
  6488. break;
  6489. }
  6490. if (VA.isRegLoc() && !VA.needsCustom()) {
  6491. RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
  6492. continue;
  6493. }
  6494. // Vector arguments passed to VarArg functions need custom handling when
  6495. // they are passed (at least partially) in GPRs.
  6496. if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
  6497. assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
  6498. // Store value to its stack slot.
  6499. SDValue PtrOff =
  6500. DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
  6501. PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
  6502. SDValue Store =
  6503. DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
  6504. MemOpChains.push_back(Store);
  6505. const unsigned OriginalValNo = VA.getValNo();
  6506. // Then load the GPRs from the stack
  6507. unsigned LoadOffset = 0;
  6508. auto HandleCustomVecRegLoc = [&]() {
  6509. assert(I != E && "Unexpected end of CCvalAssigns.");
  6510. assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
  6511. "Expected custom RegLoc.");
  6512. CCValAssign RegVA = ArgLocs[I++];
  6513. assert(RegVA.getValNo() == OriginalValNo &&
  6514. "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
  6515. SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
  6516. DAG.getConstant(LoadOffset, dl, PtrVT));
  6517. SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
  6518. MemOpChains.push_back(Load.getValue(1));
  6519. RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
  6520. LoadOffset += PtrByteSize;
  6521. };
  6522. // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
  6523. // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
  6524. // R10.
  6525. HandleCustomVecRegLoc();
  6526. HandleCustomVecRegLoc();
  6527. if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
  6528. ArgLocs[I].getValNo() == OriginalValNo) {
  6529. assert(!IsPPC64 &&
  6530. "Only 2 custom RegLocs expected for 64-bit codegen.");
  6531. HandleCustomVecRegLoc();
  6532. HandleCustomVecRegLoc();
  6533. }
  6534. continue;
  6535. }
  6536. if (VA.isMemLoc()) {
  6537. SDValue PtrOff =
  6538. DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
  6539. PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
  6540. MemOpChains.push_back(
  6541. DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
  6542. continue;
  6543. }
  6544. if (!ValVT.isFloatingPoint())
  6545. report_fatal_error(
  6546. "Unexpected register handling for calling convention.");
  6547. // Custom handling is used for GPR initializations for vararg float
  6548. // arguments.
  6549. assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
  6550. LocVT.isInteger() &&
  6551. "Custom register handling only expected for VarArg.");
  6552. SDValue ArgAsInt =
  6553. DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
  6554. if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
  6555. // f32 in 32-bit GPR
  6556. // f64 in 64-bit GPR
  6557. RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
  6558. else if (Arg.getValueType().getFixedSizeInBits() <
  6559. LocVT.getFixedSizeInBits())
  6560. // f32 in 64-bit GPR.
  6561. RegsToPass.push_back(std::make_pair(
  6562. VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
  6563. else {
  6564. // f64 in two 32-bit GPRs
  6565. // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
  6566. assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
  6567. "Unexpected custom register for argument!");
  6568. CCValAssign &GPR1 = VA;
  6569. SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
  6570. DAG.getConstant(32, dl, MVT::i8));
  6571. RegsToPass.push_back(std::make_pair(
  6572. GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
  6573. if (I != E) {
  6574. // If only 1 GPR was available, there will only be one custom GPR and
  6575. // the argument will also pass in memory.
  6576. CCValAssign &PeekArg = ArgLocs[I];
  6577. if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
  6578. assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
  6579. CCValAssign &GPR2 = ArgLocs[I++];
  6580. RegsToPass.push_back(std::make_pair(
  6581. GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
  6582. }
  6583. }
  6584. }
  6585. }
  6586. if (!MemOpChains.empty())
  6587. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
  6588. // For indirect calls, we need to save the TOC base to the stack for
  6589. // restoration after the call.
  6590. if (CFlags.IsIndirect) {
  6591. assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
  6592. const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
  6593. const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
  6594. const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
  6595. const unsigned TOCSaveOffset =
  6596. Subtarget.getFrameLowering()->getTOCSaveOffset();
  6597. setUsesTOCBasePtr(DAG);
  6598. SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
  6599. SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
  6600. SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
  6601. SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
  6602. Chain = DAG.getStore(
  6603. Val.getValue(1), dl, Val, AddPtr,
  6604. MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
  6605. }
  6606. // Build a sequence of copy-to-reg nodes chained together with token chain
  6607. // and flag operands which copy the outgoing args into the appropriate regs.
  6608. SDValue InFlag;
  6609. for (auto Reg : RegsToPass) {
  6610. Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
  6611. InFlag = Chain.getValue(1);
  6612. }
  6613. const int SPDiff = 0;
  6614. return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
  6615. Callee, SPDiff, NumBytes, Ins, InVals, CB);
  6616. }
  6617. bool
  6618. PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
  6619. MachineFunction &MF, bool isVarArg,
  6620. const SmallVectorImpl<ISD::OutputArg> &Outs,
  6621. LLVMContext &Context) const {
  6622. SmallVector<CCValAssign, 16> RVLocs;
  6623. CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
  6624. return CCInfo.CheckReturn(
  6625. Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
  6626. ? RetCC_PPC_Cold
  6627. : RetCC_PPC);
  6628. }
  6629. SDValue
  6630. PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
  6631. bool isVarArg,
  6632. const SmallVectorImpl<ISD::OutputArg> &Outs,
  6633. const SmallVectorImpl<SDValue> &OutVals,
  6634. const SDLoc &dl, SelectionDAG &DAG) const {
  6635. SmallVector<CCValAssign, 16> RVLocs;
  6636. CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
  6637. *DAG.getContext());
  6638. CCInfo.AnalyzeReturn(Outs,
  6639. (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
  6640. ? RetCC_PPC_Cold
  6641. : RetCC_PPC);
  6642. SDValue Flag;
  6643. SmallVector<SDValue, 4> RetOps(1, Chain);
  6644. // Copy the result values into the output registers.
  6645. for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
  6646. CCValAssign &VA = RVLocs[i];
  6647. assert(VA.isRegLoc() && "Can only return in registers!");
  6648. SDValue Arg = OutVals[RealResIdx];
  6649. switch (VA.getLocInfo()) {
  6650. default: llvm_unreachable("Unknown loc info!");
  6651. case CCValAssign::Full: break;
  6652. case CCValAssign::AExt:
  6653. Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
  6654. break;
  6655. case CCValAssign::ZExt:
  6656. Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
  6657. break;
  6658. case CCValAssign::SExt:
  6659. Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
  6660. break;
  6661. }
  6662. if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
  6663. bool isLittleEndian = Subtarget.isLittleEndian();
  6664. // Legalize ret f64 -> ret 2 x i32.
  6665. SDValue SVal =
  6666. DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
  6667. DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
  6668. Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
  6669. RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
  6670. SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
  6671. DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
  6672. Flag = Chain.getValue(1);
  6673. VA = RVLocs[++i]; // skip ahead to next loc
  6674. Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
  6675. } else
  6676. Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
  6677. Flag = Chain.getValue(1);
  6678. RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
  6679. }
  6680. RetOps[0] = Chain; // Update chain.
  6681. // Add the flag if we have it.
  6682. if (Flag.getNode())
  6683. RetOps.push_back(Flag);
  6684. return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
  6685. }
  6686. SDValue
  6687. PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
  6688. SelectionDAG &DAG) const {
  6689. SDLoc dl(Op);
  6690. // Get the correct type for integers.
  6691. EVT IntVT = Op.getValueType();
  6692. // Get the inputs.
  6693. SDValue Chain = Op.getOperand(0);
  6694. SDValue FPSIdx = getFramePointerFrameIndex(DAG);
  6695. // Build a DYNAREAOFFSET node.
  6696. SDValue Ops[2] = {Chain, FPSIdx};
  6697. SDVTList VTs = DAG.getVTList(IntVT);
  6698. return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
  6699. }
  6700. SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
  6701. SelectionDAG &DAG) const {
  6702. // When we pop the dynamic allocation we need to restore the SP link.
  6703. SDLoc dl(Op);
  6704. // Get the correct type for pointers.
  6705. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  6706. // Construct the stack pointer operand.
  6707. bool isPPC64 = Subtarget.isPPC64();
  6708. unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
  6709. SDValue StackPtr = DAG.getRegister(SP, PtrVT);
  6710. // Get the operands for the STACKRESTORE.
  6711. SDValue Chain = Op.getOperand(0);
  6712. SDValue SaveSP = Op.getOperand(1);
  6713. // Load the old link SP.
  6714. SDValue LoadLinkSP =
  6715. DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
  6716. // Restore the stack pointer.
  6717. Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
  6718. // Store the old link SP.
  6719. return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
  6720. }
  6721. SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
  6722. MachineFunction &MF = DAG.getMachineFunction();
  6723. bool isPPC64 = Subtarget.isPPC64();
  6724. EVT PtrVT = getPointerTy(MF.getDataLayout());
  6725. // Get current frame pointer save index. The users of this index will be
  6726. // primarily DYNALLOC instructions.
  6727. PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
  6728. int RASI = FI->getReturnAddrSaveIndex();
  6729. // If the frame pointer save index hasn't been defined yet.
  6730. if (!RASI) {
  6731. // Find out what the fix offset of the frame pointer save area.
  6732. int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
  6733. // Allocate the frame index for frame pointer save area.
  6734. RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
  6735. // Save the result.
  6736. FI->setReturnAddrSaveIndex(RASI);
  6737. }
  6738. return DAG.getFrameIndex(RASI, PtrVT);
  6739. }
  6740. SDValue
  6741. PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
  6742. MachineFunction &MF = DAG.getMachineFunction();
  6743. bool isPPC64 = Subtarget.isPPC64();
  6744. EVT PtrVT = getPointerTy(MF.getDataLayout());
  6745. // Get current frame pointer save index. The users of this index will be
  6746. // primarily DYNALLOC instructions.
  6747. PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
  6748. int FPSI = FI->getFramePointerSaveIndex();
  6749. // If the frame pointer save index hasn't been defined yet.
  6750. if (!FPSI) {
  6751. // Find out what the fix offset of the frame pointer save area.
  6752. int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
  6753. // Allocate the frame index for frame pointer save area.
  6754. FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
  6755. // Save the result.
  6756. FI->setFramePointerSaveIndex(FPSI);
  6757. }
  6758. return DAG.getFrameIndex(FPSI, PtrVT);
  6759. }
  6760. SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
  6761. SelectionDAG &DAG) const {
  6762. MachineFunction &MF = DAG.getMachineFunction();
  6763. // Get the inputs.
  6764. SDValue Chain = Op.getOperand(0);
  6765. SDValue Size = Op.getOperand(1);
  6766. SDLoc dl(Op);
  6767. // Get the correct type for pointers.
  6768. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  6769. // Negate the size.
  6770. SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
  6771. DAG.getConstant(0, dl, PtrVT), Size);
  6772. // Construct a node for the frame pointer save index.
  6773. SDValue FPSIdx = getFramePointerFrameIndex(DAG);
  6774. SDValue Ops[3] = { Chain, NegSize, FPSIdx };
  6775. SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
  6776. if (hasInlineStackProbe(MF))
  6777. return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
  6778. return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
  6779. }
  6780. SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
  6781. SelectionDAG &DAG) const {
  6782. MachineFunction &MF = DAG.getMachineFunction();
  6783. bool isPPC64 = Subtarget.isPPC64();
  6784. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  6785. int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
  6786. return DAG.getFrameIndex(FI, PtrVT);
  6787. }
  6788. SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
  6789. SelectionDAG &DAG) const {
  6790. SDLoc DL(Op);
  6791. return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
  6792. DAG.getVTList(MVT::i32, MVT::Other),
  6793. Op.getOperand(0), Op.getOperand(1));
  6794. }
  6795. SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
  6796. SelectionDAG &DAG) const {
  6797. SDLoc DL(Op);
  6798. return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
  6799. Op.getOperand(0), Op.getOperand(1));
  6800. }
  6801. SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
  6802. if (Op.getValueType().isVector())
  6803. return LowerVectorLoad(Op, DAG);
  6804. assert(Op.getValueType() == MVT::i1 &&
  6805. "Custom lowering only for i1 loads");
  6806. // First, load 8 bits into 32 bits, then truncate to 1 bit.
  6807. SDLoc dl(Op);
  6808. LoadSDNode *LD = cast<LoadSDNode>(Op);
  6809. SDValue Chain = LD->getChain();
  6810. SDValue BasePtr = LD->getBasePtr();
  6811. MachineMemOperand *MMO = LD->getMemOperand();
  6812. SDValue NewLD =
  6813. DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
  6814. BasePtr, MVT::i8, MMO);
  6815. SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
  6816. SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
  6817. return DAG.getMergeValues(Ops, dl);
  6818. }
  6819. SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
  6820. if (Op.getOperand(1).getValueType().isVector())
  6821. return LowerVectorStore(Op, DAG);
  6822. assert(Op.getOperand(1).getValueType() == MVT::i1 &&
  6823. "Custom lowering only for i1 stores");
  6824. // First, zero extend to 32 bits, then use a truncating store to 8 bits.
  6825. SDLoc dl(Op);
  6826. StoreSDNode *ST = cast<StoreSDNode>(Op);
  6827. SDValue Chain = ST->getChain();
  6828. SDValue BasePtr = ST->getBasePtr();
  6829. SDValue Value = ST->getValue();
  6830. MachineMemOperand *MMO = ST->getMemOperand();
  6831. Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
  6832. Value);
  6833. return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
  6834. }
  6835. // FIXME: Remove this once the ANDI glue bug is fixed:
  6836. SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
  6837. assert(Op.getValueType() == MVT::i1 &&
  6838. "Custom lowering only for i1 results");
  6839. SDLoc DL(Op);
  6840. return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
  6841. }
  6842. SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
  6843. SelectionDAG &DAG) const {
  6844. // Implements a vector truncate that fits in a vector register as a shuffle.
  6845. // We want to legalize vector truncates down to where the source fits in
  6846. // a vector register (and target is therefore smaller than vector register
  6847. // size). At that point legalization will try to custom lower the sub-legal
  6848. // result and get here - where we can contain the truncate as a single target
  6849. // operation.
  6850. // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
  6851. // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
  6852. //
  6853. // We will implement it for big-endian ordering as this (where x denotes
  6854. // undefined):
  6855. // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
  6856. // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
  6857. //
  6858. // The same operation in little-endian ordering will be:
  6859. // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
  6860. // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
  6861. EVT TrgVT = Op.getValueType();
  6862. assert(TrgVT.isVector() && "Vector type expected.");
  6863. unsigned TrgNumElts = TrgVT.getVectorNumElements();
  6864. EVT EltVT = TrgVT.getVectorElementType();
  6865. if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
  6866. TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
  6867. !isPowerOf2_32(EltVT.getSizeInBits()))
  6868. return SDValue();
  6869. SDValue N1 = Op.getOperand(0);
  6870. EVT SrcVT = N1.getValueType();
  6871. unsigned SrcSize = SrcVT.getSizeInBits();
  6872. if (SrcSize > 256 ||
  6873. !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
  6874. !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
  6875. return SDValue();
  6876. if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
  6877. return SDValue();
  6878. unsigned WideNumElts = 128 / EltVT.getSizeInBits();
  6879. EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
  6880. SDLoc DL(Op);
  6881. SDValue Op1, Op2;
  6882. if (SrcSize == 256) {
  6883. EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
  6884. EVT SplitVT =
  6885. N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
  6886. unsigned SplitNumElts = SplitVT.getVectorNumElements();
  6887. Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
  6888. DAG.getConstant(0, DL, VecIdxTy));
  6889. Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
  6890. DAG.getConstant(SplitNumElts, DL, VecIdxTy));
  6891. }
  6892. else {
  6893. Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
  6894. Op2 = DAG.getUNDEF(WideVT);
  6895. }
  6896. // First list the elements we want to keep.
  6897. unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
  6898. SmallVector<int, 16> ShuffV;
  6899. if (Subtarget.isLittleEndian())
  6900. for (unsigned i = 0; i < TrgNumElts; ++i)
  6901. ShuffV.push_back(i * SizeMult);
  6902. else
  6903. for (unsigned i = 1; i <= TrgNumElts; ++i)
  6904. ShuffV.push_back(i * SizeMult - 1);
  6905. // Populate the remaining elements with undefs.
  6906. for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
  6907. // ShuffV.push_back(i + WideNumElts);
  6908. ShuffV.push_back(WideNumElts + 1);
  6909. Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
  6910. Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
  6911. return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
  6912. }
  6913. /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
  6914. /// possible.
  6915. SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
  6916. ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
  6917. EVT ResVT = Op.getValueType();
  6918. EVT CmpVT = Op.getOperand(0).getValueType();
  6919. SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
  6920. SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
  6921. SDLoc dl(Op);
  6922. // Without power9-vector, we don't have native instruction for f128 comparison.
  6923. // Following transformation to libcall is needed for setcc:
  6924. // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
  6925. if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
  6926. SDValue Z = DAG.getSetCC(
  6927. dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
  6928. LHS, RHS, CC);
  6929. SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
  6930. return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
  6931. }
  6932. // Not FP, or using SPE? Not a fsel.
  6933. if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
  6934. Subtarget.hasSPE())
  6935. return Op;
  6936. SDNodeFlags Flags = Op.getNode()->getFlags();
  6937. // We have xsmaxc[dq]p/xsminc[dq]p which are OK to emit even in the
  6938. // presence of infinities.
  6939. if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
  6940. switch (CC) {
  6941. default:
  6942. break;
  6943. case ISD::SETOGT:
  6944. case ISD::SETGT:
  6945. return DAG.getNode(PPCISD::XSMAXC, dl, Op.getValueType(), LHS, RHS);
  6946. case ISD::SETOLT:
  6947. case ISD::SETLT:
  6948. return DAG.getNode(PPCISD::XSMINC, dl, Op.getValueType(), LHS, RHS);
  6949. }
  6950. }
  6951. // We might be able to do better than this under some circumstances, but in
  6952. // general, fsel-based lowering of select is a finite-math-only optimization.
  6953. // For more information, see section F.3 of the 2.06 ISA specification.
  6954. // With ISA 3.0
  6955. if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
  6956. (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
  6957. return Op;
  6958. // If the RHS of the comparison is a 0.0, we don't need to do the
  6959. // subtraction at all.
  6960. SDValue Sel1;
  6961. if (isFloatingPointZero(RHS))
  6962. switch (CC) {
  6963. default: break; // SETUO etc aren't handled by fsel.
  6964. case ISD::SETNE:
  6965. std::swap(TV, FV);
  6966. [[fallthrough]];
  6967. case ISD::SETEQ:
  6968. if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
  6969. LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
  6970. Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
  6971. if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
  6972. Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
  6973. return DAG.getNode(PPCISD::FSEL, dl, ResVT,
  6974. DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
  6975. case ISD::SETULT:
  6976. case ISD::SETLT:
  6977. std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
  6978. [[fallthrough]];
  6979. case ISD::SETOGE:
  6980. case ISD::SETGE:
  6981. if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
  6982. LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
  6983. return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
  6984. case ISD::SETUGT:
  6985. case ISD::SETGT:
  6986. std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
  6987. [[fallthrough]];
  6988. case ISD::SETOLE:
  6989. case ISD::SETLE:
  6990. if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
  6991. LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
  6992. return DAG.getNode(PPCISD::FSEL, dl, ResVT,
  6993. DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
  6994. }
  6995. SDValue Cmp;
  6996. switch (CC) {
  6997. default: break; // SETUO etc aren't handled by fsel.
  6998. case ISD::SETNE:
  6999. std::swap(TV, FV);
  7000. [[fallthrough]];
  7001. case ISD::SETEQ:
  7002. Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
  7003. if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
  7004. Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
  7005. Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
  7006. if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
  7007. Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
  7008. return DAG.getNode(PPCISD::FSEL, dl, ResVT,
  7009. DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
  7010. case ISD::SETULT:
  7011. case ISD::SETLT:
  7012. Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
  7013. if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
  7014. Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
  7015. return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
  7016. case ISD::SETOGE:
  7017. case ISD::SETGE:
  7018. Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
  7019. if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
  7020. Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
  7021. return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
  7022. case ISD::SETUGT:
  7023. case ISD::SETGT:
  7024. Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
  7025. if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
  7026. Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
  7027. return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
  7028. case ISD::SETOLE:
  7029. case ISD::SETLE:
  7030. Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
  7031. if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
  7032. Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
  7033. return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
  7034. }
  7035. return Op;
  7036. }
  7037. static unsigned getPPCStrictOpcode(unsigned Opc) {
  7038. switch (Opc) {
  7039. default:
  7040. llvm_unreachable("No strict version of this opcode!");
  7041. case PPCISD::FCTIDZ:
  7042. return PPCISD::STRICT_FCTIDZ;
  7043. case PPCISD::FCTIWZ:
  7044. return PPCISD::STRICT_FCTIWZ;
  7045. case PPCISD::FCTIDUZ:
  7046. return PPCISD::STRICT_FCTIDUZ;
  7047. case PPCISD::FCTIWUZ:
  7048. return PPCISD::STRICT_FCTIWUZ;
  7049. case PPCISD::FCFID:
  7050. return PPCISD::STRICT_FCFID;
  7051. case PPCISD::FCFIDU:
  7052. return PPCISD::STRICT_FCFIDU;
  7053. case PPCISD::FCFIDS:
  7054. return PPCISD::STRICT_FCFIDS;
  7055. case PPCISD::FCFIDUS:
  7056. return PPCISD::STRICT_FCFIDUS;
  7057. }
  7058. }
  7059. static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
  7060. const PPCSubtarget &Subtarget) {
  7061. SDLoc dl(Op);
  7062. bool IsStrict = Op->isStrictFPOpcode();
  7063. bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
  7064. Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
  7065. // TODO: Any other flags to propagate?
  7066. SDNodeFlags Flags;
  7067. Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
  7068. // For strict nodes, source is the second operand.
  7069. SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
  7070. SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
  7071. assert(Src.getValueType().isFloatingPoint());
  7072. if (Src.getValueType() == MVT::f32) {
  7073. if (IsStrict) {
  7074. Src =
  7075. DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
  7076. DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
  7077. Chain = Src.getValue(1);
  7078. } else
  7079. Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
  7080. }
  7081. SDValue Conv;
  7082. unsigned Opc = ISD::DELETED_NODE;
  7083. switch (Op.getSimpleValueType().SimpleTy) {
  7084. default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
  7085. case MVT::i32:
  7086. Opc = IsSigned ? PPCISD::FCTIWZ
  7087. : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
  7088. break;
  7089. case MVT::i64:
  7090. assert((IsSigned || Subtarget.hasFPCVT()) &&
  7091. "i64 FP_TO_UINT is supported only with FPCVT");
  7092. Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
  7093. }
  7094. if (IsStrict) {
  7095. Opc = getPPCStrictOpcode(Opc);
  7096. Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
  7097. {Chain, Src}, Flags);
  7098. } else {
  7099. Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
  7100. }
  7101. return Conv;
  7102. }
  7103. void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
  7104. SelectionDAG &DAG,
  7105. const SDLoc &dl) const {
  7106. SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
  7107. bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
  7108. Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
  7109. bool IsStrict = Op->isStrictFPOpcode();
  7110. // Convert the FP value to an int value through memory.
  7111. bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
  7112. (IsSigned || Subtarget.hasFPCVT());
  7113. SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
  7114. int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
  7115. MachinePointerInfo MPI =
  7116. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
  7117. // Emit a store to the stack slot.
  7118. SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
  7119. Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
  7120. if (i32Stack) {
  7121. MachineFunction &MF = DAG.getMachineFunction();
  7122. Alignment = Align(4);
  7123. MachineMemOperand *MMO =
  7124. MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
  7125. SDValue Ops[] = { Chain, Tmp, FIPtr };
  7126. Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
  7127. DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
  7128. } else
  7129. Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
  7130. // Result is a load from the stack slot. If loading 4 bytes, make sure to
  7131. // add in a bias on big endian.
  7132. if (Op.getValueType() == MVT::i32 && !i32Stack) {
  7133. FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
  7134. DAG.getConstant(4, dl, FIPtr.getValueType()));
  7135. MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
  7136. }
  7137. RLI.Chain = Chain;
  7138. RLI.Ptr = FIPtr;
  7139. RLI.MPI = MPI;
  7140. RLI.Alignment = Alignment;
  7141. }
  7142. /// Custom lowers floating point to integer conversions to use
  7143. /// the direct move instructions available in ISA 2.07 to avoid the
  7144. /// need for load/store combinations.
  7145. SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
  7146. SelectionDAG &DAG,
  7147. const SDLoc &dl) const {
  7148. SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
  7149. SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
  7150. if (Op->isStrictFPOpcode())
  7151. return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
  7152. else
  7153. return Mov;
  7154. }
  7155. SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
  7156. const SDLoc &dl) const {
  7157. bool IsStrict = Op->isStrictFPOpcode();
  7158. bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
  7159. Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
  7160. SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
  7161. EVT SrcVT = Src.getValueType();
  7162. EVT DstVT = Op.getValueType();
  7163. // FP to INT conversions are legal for f128.
  7164. if (SrcVT == MVT::f128)
  7165. return Subtarget.hasP9Vector() ? Op : SDValue();
  7166. // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
  7167. // PPC (the libcall is not available).
  7168. if (SrcVT == MVT::ppcf128) {
  7169. if (DstVT == MVT::i32) {
  7170. // TODO: Conservatively pass only nofpexcept flag here. Need to check and
  7171. // set other fast-math flags to FP operations in both strict and
  7172. // non-strict cases. (FP_TO_SINT, FSUB)
  7173. SDNodeFlags Flags;
  7174. Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
  7175. if (IsSigned) {
  7176. SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
  7177. DAG.getIntPtrConstant(0, dl));
  7178. SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
  7179. DAG.getIntPtrConstant(1, dl));
  7180. // Add the two halves of the long double in round-to-zero mode, and use
  7181. // a smaller FP_TO_SINT.
  7182. if (IsStrict) {
  7183. SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
  7184. DAG.getVTList(MVT::f64, MVT::Other),
  7185. {Op.getOperand(0), Lo, Hi}, Flags);
  7186. return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
  7187. DAG.getVTList(MVT::i32, MVT::Other),
  7188. {Res.getValue(1), Res}, Flags);
  7189. } else {
  7190. SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
  7191. return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
  7192. }
  7193. } else {
  7194. const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
  7195. APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
  7196. SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
  7197. SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
  7198. if (IsStrict) {
  7199. // Sel = Src < 0x80000000
  7200. // FltOfs = select Sel, 0.0, 0x80000000
  7201. // IntOfs = select Sel, 0, 0x80000000
  7202. // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
  7203. SDValue Chain = Op.getOperand(0);
  7204. EVT SetCCVT =
  7205. getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
  7206. EVT DstSetCCVT =
  7207. getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
  7208. SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
  7209. Chain, true);
  7210. Chain = Sel.getValue(1);
  7211. SDValue FltOfs = DAG.getSelect(
  7212. dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
  7213. Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
  7214. SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
  7215. DAG.getVTList(SrcVT, MVT::Other),
  7216. {Chain, Src, FltOfs}, Flags);
  7217. Chain = Val.getValue(1);
  7218. SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
  7219. DAG.getVTList(DstVT, MVT::Other),
  7220. {Chain, Val}, Flags);
  7221. Chain = SInt.getValue(1);
  7222. SDValue IntOfs = DAG.getSelect(
  7223. dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
  7224. SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
  7225. return DAG.getMergeValues({Result, Chain}, dl);
  7226. } else {
  7227. // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
  7228. // FIXME: generated code sucks.
  7229. SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
  7230. True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
  7231. True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
  7232. SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
  7233. return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
  7234. }
  7235. }
  7236. }
  7237. return SDValue();
  7238. }
  7239. if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
  7240. return LowerFP_TO_INTDirectMove(Op, DAG, dl);
  7241. ReuseLoadInfo RLI;
  7242. LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
  7243. return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
  7244. RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
  7245. }
  7246. // We're trying to insert a regular store, S, and then a load, L. If the
  7247. // incoming value, O, is a load, we might just be able to have our load use the
  7248. // address used by O. However, we don't know if anything else will store to
  7249. // that address before we can load from it. To prevent this situation, we need
  7250. // to insert our load, L, into the chain as a peer of O. To do this, we give L
  7251. // the same chain operand as O, we create a token factor from the chain results
  7252. // of O and L, and we replace all uses of O's chain result with that token
  7253. // factor (see spliceIntoChain below for this last part).
  7254. bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
  7255. ReuseLoadInfo &RLI,
  7256. SelectionDAG &DAG,
  7257. ISD::LoadExtType ET) const {
  7258. // Conservatively skip reusing for constrained FP nodes.
  7259. if (Op->isStrictFPOpcode())
  7260. return false;
  7261. SDLoc dl(Op);
  7262. bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
  7263. (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
  7264. if (ET == ISD::NON_EXTLOAD &&
  7265. (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
  7266. isOperationLegalOrCustom(Op.getOpcode(),
  7267. Op.getOperand(0).getValueType())) {
  7268. LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
  7269. return true;
  7270. }
  7271. LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
  7272. if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
  7273. LD->isNonTemporal())
  7274. return false;
  7275. if (LD->getMemoryVT() != MemVT)
  7276. return false;
  7277. // If the result of the load is an illegal type, then we can't build a
  7278. // valid chain for reuse since the legalised loads and token factor node that
  7279. // ties the legalised loads together uses a different output chain then the
  7280. // illegal load.
  7281. if (!isTypeLegal(LD->getValueType(0)))
  7282. return false;
  7283. RLI.Ptr = LD->getBasePtr();
  7284. if (LD->isIndexed() && !LD->getOffset().isUndef()) {
  7285. assert(LD->getAddressingMode() == ISD::PRE_INC &&
  7286. "Non-pre-inc AM on PPC?");
  7287. RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
  7288. LD->getOffset());
  7289. }
  7290. RLI.Chain = LD->getChain();
  7291. RLI.MPI = LD->getPointerInfo();
  7292. RLI.IsDereferenceable = LD->isDereferenceable();
  7293. RLI.IsInvariant = LD->isInvariant();
  7294. RLI.Alignment = LD->getAlign();
  7295. RLI.AAInfo = LD->getAAInfo();
  7296. RLI.Ranges = LD->getRanges();
  7297. RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
  7298. return true;
  7299. }
  7300. // Given the head of the old chain, ResChain, insert a token factor containing
  7301. // it and NewResChain, and make users of ResChain now be users of that token
  7302. // factor.
  7303. // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
  7304. void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
  7305. SDValue NewResChain,
  7306. SelectionDAG &DAG) const {
  7307. if (!ResChain)
  7308. return;
  7309. SDLoc dl(NewResChain);
  7310. SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  7311. NewResChain, DAG.getUNDEF(MVT::Other));
  7312. assert(TF.getNode() != NewResChain.getNode() &&
  7313. "A new TF really is required here");
  7314. DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
  7315. DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
  7316. }
  7317. /// Analyze profitability of direct move
  7318. /// prefer float load to int load plus direct move
  7319. /// when there is no integer use of int load
  7320. bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
  7321. SDNode *Origin = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0).getNode();
  7322. if (Origin->getOpcode() != ISD::LOAD)
  7323. return true;
  7324. // If there is no LXSIBZX/LXSIHZX, like Power8,
  7325. // prefer direct move if the memory size is 1 or 2 bytes.
  7326. MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
  7327. if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
  7328. return true;
  7329. for (SDNode::use_iterator UI = Origin->use_begin(),
  7330. UE = Origin->use_end();
  7331. UI != UE; ++UI) {
  7332. // Only look at the users of the loaded value.
  7333. if (UI.getUse().get().getResNo() != 0)
  7334. continue;
  7335. if (UI->getOpcode() != ISD::SINT_TO_FP &&
  7336. UI->getOpcode() != ISD::UINT_TO_FP &&
  7337. UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
  7338. UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
  7339. return true;
  7340. }
  7341. return false;
  7342. }
  7343. static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
  7344. const PPCSubtarget &Subtarget,
  7345. SDValue Chain = SDValue()) {
  7346. bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
  7347. Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
  7348. SDLoc dl(Op);
  7349. // TODO: Any other flags to propagate?
  7350. SDNodeFlags Flags;
  7351. Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
  7352. // If we have FCFIDS, then use it when converting to single-precision.
  7353. // Otherwise, convert to double-precision and then round.
  7354. bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
  7355. unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
  7356. : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
  7357. EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
  7358. if (Op->isStrictFPOpcode()) {
  7359. if (!Chain)
  7360. Chain = Op.getOperand(0);
  7361. return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
  7362. DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
  7363. } else
  7364. return DAG.getNode(ConvOpc, dl, ConvTy, Src);
  7365. }
  7366. /// Custom lowers integer to floating point conversions to use
  7367. /// the direct move instructions available in ISA 2.07 to avoid the
  7368. /// need for load/store combinations.
  7369. SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
  7370. SelectionDAG &DAG,
  7371. const SDLoc &dl) const {
  7372. assert((Op.getValueType() == MVT::f32 ||
  7373. Op.getValueType() == MVT::f64) &&
  7374. "Invalid floating point type as target of conversion");
  7375. assert(Subtarget.hasFPCVT() &&
  7376. "Int to FP conversions with direct moves require FPCVT");
  7377. SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
  7378. bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
  7379. bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
  7380. Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
  7381. unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
  7382. SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
  7383. return convertIntToFP(Op, Mov, DAG, Subtarget);
  7384. }
  7385. static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
  7386. EVT VecVT = Vec.getValueType();
  7387. assert(VecVT.isVector() && "Expected a vector type.");
  7388. assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
  7389. EVT EltVT = VecVT.getVectorElementType();
  7390. unsigned WideNumElts = 128 / EltVT.getSizeInBits();
  7391. EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
  7392. unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
  7393. SmallVector<SDValue, 16> Ops(NumConcat);
  7394. Ops[0] = Vec;
  7395. SDValue UndefVec = DAG.getUNDEF(VecVT);
  7396. for (unsigned i = 1; i < NumConcat; ++i)
  7397. Ops[i] = UndefVec;
  7398. return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
  7399. }
  7400. SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
  7401. const SDLoc &dl) const {
  7402. bool IsStrict = Op->isStrictFPOpcode();
  7403. unsigned Opc = Op.getOpcode();
  7404. SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
  7405. assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
  7406. Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
  7407. "Unexpected conversion type");
  7408. assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
  7409. "Supports conversions to v2f64/v4f32 only.");
  7410. // TODO: Any other flags to propagate?
  7411. SDNodeFlags Flags;
  7412. Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
  7413. bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
  7414. bool FourEltRes = Op.getValueType() == MVT::v4f32;
  7415. SDValue Wide = widenVec(DAG, Src, dl);
  7416. EVT WideVT = Wide.getValueType();
  7417. unsigned WideNumElts = WideVT.getVectorNumElements();
  7418. MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
  7419. SmallVector<int, 16> ShuffV;
  7420. for (unsigned i = 0; i < WideNumElts; ++i)
  7421. ShuffV.push_back(i + WideNumElts);
  7422. int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
  7423. int SaveElts = FourEltRes ? 4 : 2;
  7424. if (Subtarget.isLittleEndian())
  7425. for (int i = 0; i < SaveElts; i++)
  7426. ShuffV[i * Stride] = i;
  7427. else
  7428. for (int i = 1; i <= SaveElts; i++)
  7429. ShuffV[i * Stride - 1] = i - 1;
  7430. SDValue ShuffleSrc2 =
  7431. SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
  7432. SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
  7433. SDValue Extend;
  7434. if (SignedConv) {
  7435. Arrange = DAG.getBitcast(IntermediateVT, Arrange);
  7436. EVT ExtVT = Src.getValueType();
  7437. if (Subtarget.hasP9Altivec())
  7438. ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
  7439. IntermediateVT.getVectorNumElements());
  7440. Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
  7441. DAG.getValueType(ExtVT));
  7442. } else
  7443. Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
  7444. if (IsStrict)
  7445. return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
  7446. {Op.getOperand(0), Extend}, Flags);
  7447. return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
  7448. }
  7449. SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
  7450. SelectionDAG &DAG) const {
  7451. SDLoc dl(Op);
  7452. bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
  7453. Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
  7454. bool IsStrict = Op->isStrictFPOpcode();
  7455. SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
  7456. SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
  7457. // TODO: Any other flags to propagate?
  7458. SDNodeFlags Flags;
  7459. Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
  7460. EVT InVT = Src.getValueType();
  7461. EVT OutVT = Op.getValueType();
  7462. if (OutVT.isVector() && OutVT.isFloatingPoint() &&
  7463. isOperationCustom(Op.getOpcode(), InVT))
  7464. return LowerINT_TO_FPVector(Op, DAG, dl);
  7465. // Conversions to f128 are legal.
  7466. if (Op.getValueType() == MVT::f128)
  7467. return Subtarget.hasP9Vector() ? Op : SDValue();
  7468. // Don't handle ppc_fp128 here; let it be lowered to a libcall.
  7469. if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
  7470. return SDValue();
  7471. if (Src.getValueType() == MVT::i1) {
  7472. SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
  7473. DAG.getConstantFP(1.0, dl, Op.getValueType()),
  7474. DAG.getConstantFP(0.0, dl, Op.getValueType()));
  7475. if (IsStrict)
  7476. return DAG.getMergeValues({Sel, Chain}, dl);
  7477. else
  7478. return Sel;
  7479. }
  7480. // If we have direct moves, we can do all the conversion, skip the store/load
  7481. // however, without FPCVT we can't do most conversions.
  7482. if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
  7483. Subtarget.isPPC64() && Subtarget.hasFPCVT())
  7484. return LowerINT_TO_FPDirectMove(Op, DAG, dl);
  7485. assert((IsSigned || Subtarget.hasFPCVT()) &&
  7486. "UINT_TO_FP is supported only with FPCVT");
  7487. if (Src.getValueType() == MVT::i64) {
  7488. SDValue SINT = Src;
  7489. // When converting to single-precision, we actually need to convert
  7490. // to double-precision first and then round to single-precision.
  7491. // To avoid double-rounding effects during that operation, we have
  7492. // to prepare the input operand. Bits that might be truncated when
  7493. // converting to double-precision are replaced by a bit that won't
  7494. // be lost at this stage, but is below the single-precision rounding
  7495. // position.
  7496. //
  7497. // However, if -enable-unsafe-fp-math is in effect, accept double
  7498. // rounding to avoid the extra overhead.
  7499. if (Op.getValueType() == MVT::f32 &&
  7500. !Subtarget.hasFPCVT() &&
  7501. !DAG.getTarget().Options.UnsafeFPMath) {
  7502. // Twiddle input to make sure the low 11 bits are zero. (If this
  7503. // is the case, we are guaranteed the value will fit into the 53 bit
  7504. // mantissa of an IEEE double-precision value without rounding.)
  7505. // If any of those low 11 bits were not zero originally, make sure
  7506. // bit 12 (value 2048) is set instead, so that the final rounding
  7507. // to single-precision gets the correct result.
  7508. SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
  7509. SINT, DAG.getConstant(2047, dl, MVT::i64));
  7510. Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
  7511. Round, DAG.getConstant(2047, dl, MVT::i64));
  7512. Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
  7513. Round = DAG.getNode(ISD::AND, dl, MVT::i64,
  7514. Round, DAG.getConstant(-2048, dl, MVT::i64));
  7515. // However, we cannot use that value unconditionally: if the magnitude
  7516. // of the input value is small, the bit-twiddling we did above might
  7517. // end up visibly changing the output. Fortunately, in that case, we
  7518. // don't need to twiddle bits since the original input will convert
  7519. // exactly to double-precision floating-point already. Therefore,
  7520. // construct a conditional to use the original value if the top 11
  7521. // bits are all sign-bit copies, and use the rounded value computed
  7522. // above otherwise.
  7523. SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
  7524. SINT, DAG.getConstant(53, dl, MVT::i32));
  7525. Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
  7526. Cond, DAG.getConstant(1, dl, MVT::i64));
  7527. Cond = DAG.getSetCC(
  7528. dl,
  7529. getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
  7530. Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
  7531. SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
  7532. }
  7533. ReuseLoadInfo RLI;
  7534. SDValue Bits;
  7535. MachineFunction &MF = DAG.getMachineFunction();
  7536. if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
  7537. Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
  7538. RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
  7539. spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
  7540. } else if (Subtarget.hasLFIWAX() &&
  7541. canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
  7542. MachineMemOperand *MMO =
  7543. MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
  7544. RLI.Alignment, RLI.AAInfo, RLI.Ranges);
  7545. SDValue Ops[] = { RLI.Chain, RLI.Ptr };
  7546. Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
  7547. DAG.getVTList(MVT::f64, MVT::Other),
  7548. Ops, MVT::i32, MMO);
  7549. spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
  7550. } else if (Subtarget.hasFPCVT() &&
  7551. canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
  7552. MachineMemOperand *MMO =
  7553. MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
  7554. RLI.Alignment, RLI.AAInfo, RLI.Ranges);
  7555. SDValue Ops[] = { RLI.Chain, RLI.Ptr };
  7556. Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
  7557. DAG.getVTList(MVT::f64, MVT::Other),
  7558. Ops, MVT::i32, MMO);
  7559. spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
  7560. } else if (((Subtarget.hasLFIWAX() &&
  7561. SINT.getOpcode() == ISD::SIGN_EXTEND) ||
  7562. (Subtarget.hasFPCVT() &&
  7563. SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
  7564. SINT.getOperand(0).getValueType() == MVT::i32) {
  7565. MachineFrameInfo &MFI = MF.getFrameInfo();
  7566. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  7567. int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
  7568. SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
  7569. SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
  7570. MachinePointerInfo::getFixedStack(
  7571. DAG.getMachineFunction(), FrameIdx));
  7572. Chain = Store;
  7573. assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
  7574. "Expected an i32 store");
  7575. RLI.Ptr = FIdx;
  7576. RLI.Chain = Chain;
  7577. RLI.MPI =
  7578. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
  7579. RLI.Alignment = Align(4);
  7580. MachineMemOperand *MMO =
  7581. MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
  7582. RLI.Alignment, RLI.AAInfo, RLI.Ranges);
  7583. SDValue Ops[] = { RLI.Chain, RLI.Ptr };
  7584. Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
  7585. PPCISD::LFIWZX : PPCISD::LFIWAX,
  7586. dl, DAG.getVTList(MVT::f64, MVT::Other),
  7587. Ops, MVT::i32, MMO);
  7588. Chain = Bits.getValue(1);
  7589. } else
  7590. Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
  7591. SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
  7592. if (IsStrict)
  7593. Chain = FP.getValue(1);
  7594. if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
  7595. if (IsStrict)
  7596. FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
  7597. DAG.getVTList(MVT::f32, MVT::Other),
  7598. {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
  7599. else
  7600. FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
  7601. DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
  7602. }
  7603. return FP;
  7604. }
  7605. assert(Src.getValueType() == MVT::i32 &&
  7606. "Unhandled INT_TO_FP type in custom expander!");
  7607. // Since we only generate this in 64-bit mode, we can take advantage of
  7608. // 64-bit registers. In particular, sign extend the input value into the
  7609. // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
  7610. // then lfd it and fcfid it.
  7611. MachineFunction &MF = DAG.getMachineFunction();
  7612. MachineFrameInfo &MFI = MF.getFrameInfo();
  7613. EVT PtrVT = getPointerTy(MF.getDataLayout());
  7614. SDValue Ld;
  7615. if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
  7616. ReuseLoadInfo RLI;
  7617. bool ReusingLoad;
  7618. if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
  7619. int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
  7620. SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
  7621. SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
  7622. MachinePointerInfo::getFixedStack(
  7623. DAG.getMachineFunction(), FrameIdx));
  7624. Chain = Store;
  7625. assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
  7626. "Expected an i32 store");
  7627. RLI.Ptr = FIdx;
  7628. RLI.Chain = Chain;
  7629. RLI.MPI =
  7630. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
  7631. RLI.Alignment = Align(4);
  7632. }
  7633. MachineMemOperand *MMO =
  7634. MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
  7635. RLI.Alignment, RLI.AAInfo, RLI.Ranges);
  7636. SDValue Ops[] = { RLI.Chain, RLI.Ptr };
  7637. Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
  7638. DAG.getVTList(MVT::f64, MVT::Other), Ops,
  7639. MVT::i32, MMO);
  7640. Chain = Ld.getValue(1);
  7641. if (ReusingLoad)
  7642. spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
  7643. } else {
  7644. assert(Subtarget.isPPC64() &&
  7645. "i32->FP without LFIWAX supported only on PPC64");
  7646. int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
  7647. SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
  7648. SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
  7649. // STD the extended value into the stack slot.
  7650. SDValue Store = DAG.getStore(
  7651. Chain, dl, Ext64, FIdx,
  7652. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
  7653. Chain = Store;
  7654. // Load the value as a double.
  7655. Ld = DAG.getLoad(
  7656. MVT::f64, dl, Chain, FIdx,
  7657. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
  7658. Chain = Ld.getValue(1);
  7659. }
  7660. // FCFID it and return it.
  7661. SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
  7662. if (IsStrict)
  7663. Chain = FP.getValue(1);
  7664. if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
  7665. if (IsStrict)
  7666. FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
  7667. DAG.getVTList(MVT::f32, MVT::Other),
  7668. {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
  7669. else
  7670. FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
  7671. DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
  7672. }
  7673. return FP;
  7674. }
  7675. SDValue PPCTargetLowering::LowerGET_ROUNDING(SDValue Op,
  7676. SelectionDAG &DAG) const {
  7677. SDLoc dl(Op);
  7678. /*
  7679. The rounding mode is in bits 30:31 of FPSR, and has the following
  7680. settings:
  7681. 00 Round to nearest
  7682. 01 Round to 0
  7683. 10 Round to +inf
  7684. 11 Round to -inf
  7685. GET_ROUNDING, on the other hand, expects the following:
  7686. -1 Undefined
  7687. 0 Round to 0
  7688. 1 Round to nearest
  7689. 2 Round to +inf
  7690. 3 Round to -inf
  7691. To perform the conversion, we do:
  7692. ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
  7693. */
  7694. MachineFunction &MF = DAG.getMachineFunction();
  7695. EVT VT = Op.getValueType();
  7696. EVT PtrVT = getPointerTy(MF.getDataLayout());
  7697. // Save FP Control Word to register
  7698. SDValue Chain = Op.getOperand(0);
  7699. SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
  7700. Chain = MFFS.getValue(1);
  7701. SDValue CWD;
  7702. if (isTypeLegal(MVT::i64)) {
  7703. CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
  7704. DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
  7705. } else {
  7706. // Save FP register to stack slot
  7707. int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
  7708. SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
  7709. Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
  7710. // Load FP Control Word from low 32 bits of stack slot.
  7711. assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&
  7712. "Stack slot adjustment is valid only on big endian subtargets!");
  7713. SDValue Four = DAG.getConstant(4, dl, PtrVT);
  7714. SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
  7715. CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
  7716. Chain = CWD.getValue(1);
  7717. }
  7718. // Transform as necessary
  7719. SDValue CWD1 =
  7720. DAG.getNode(ISD::AND, dl, MVT::i32,
  7721. CWD, DAG.getConstant(3, dl, MVT::i32));
  7722. SDValue CWD2 =
  7723. DAG.getNode(ISD::SRL, dl, MVT::i32,
  7724. DAG.getNode(ISD::AND, dl, MVT::i32,
  7725. DAG.getNode(ISD::XOR, dl, MVT::i32,
  7726. CWD, DAG.getConstant(3, dl, MVT::i32)),
  7727. DAG.getConstant(3, dl, MVT::i32)),
  7728. DAG.getConstant(1, dl, MVT::i32));
  7729. SDValue RetVal =
  7730. DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
  7731. RetVal =
  7732. DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
  7733. dl, VT, RetVal);
  7734. return DAG.getMergeValues({RetVal, Chain}, dl);
  7735. }
  7736. SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
  7737. EVT VT = Op.getValueType();
  7738. unsigned BitWidth = VT.getSizeInBits();
  7739. SDLoc dl(Op);
  7740. assert(Op.getNumOperands() == 3 &&
  7741. VT == Op.getOperand(1).getValueType() &&
  7742. "Unexpected SHL!");
  7743. // Expand into a bunch of logical ops. Note that these ops
  7744. // depend on the PPC behavior for oversized shift amounts.
  7745. SDValue Lo = Op.getOperand(0);
  7746. SDValue Hi = Op.getOperand(1);
  7747. SDValue Amt = Op.getOperand(2);
  7748. EVT AmtVT = Amt.getValueType();
  7749. SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
  7750. DAG.getConstant(BitWidth, dl, AmtVT), Amt);
  7751. SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
  7752. SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
  7753. SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
  7754. SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
  7755. DAG.getConstant(-BitWidth, dl, AmtVT));
  7756. SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
  7757. SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
  7758. SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
  7759. SDValue OutOps[] = { OutLo, OutHi };
  7760. return DAG.getMergeValues(OutOps, dl);
  7761. }
  7762. SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
  7763. EVT VT = Op.getValueType();
  7764. SDLoc dl(Op);
  7765. unsigned BitWidth = VT.getSizeInBits();
  7766. assert(Op.getNumOperands() == 3 &&
  7767. VT == Op.getOperand(1).getValueType() &&
  7768. "Unexpected SRL!");
  7769. // Expand into a bunch of logical ops. Note that these ops
  7770. // depend on the PPC behavior for oversized shift amounts.
  7771. SDValue Lo = Op.getOperand(0);
  7772. SDValue Hi = Op.getOperand(1);
  7773. SDValue Amt = Op.getOperand(2);
  7774. EVT AmtVT = Amt.getValueType();
  7775. SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
  7776. DAG.getConstant(BitWidth, dl, AmtVT), Amt);
  7777. SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
  7778. SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
  7779. SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
  7780. SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
  7781. DAG.getConstant(-BitWidth, dl, AmtVT));
  7782. SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
  7783. SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
  7784. SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
  7785. SDValue OutOps[] = { OutLo, OutHi };
  7786. return DAG.getMergeValues(OutOps, dl);
  7787. }
  7788. SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
  7789. SDLoc dl(Op);
  7790. EVT VT = Op.getValueType();
  7791. unsigned BitWidth = VT.getSizeInBits();
  7792. assert(Op.getNumOperands() == 3 &&
  7793. VT == Op.getOperand(1).getValueType() &&
  7794. "Unexpected SRA!");
  7795. // Expand into a bunch of logical ops, followed by a select_cc.
  7796. SDValue Lo = Op.getOperand(0);
  7797. SDValue Hi = Op.getOperand(1);
  7798. SDValue Amt = Op.getOperand(2);
  7799. EVT AmtVT = Amt.getValueType();
  7800. SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
  7801. DAG.getConstant(BitWidth, dl, AmtVT), Amt);
  7802. SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
  7803. SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
  7804. SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
  7805. SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
  7806. DAG.getConstant(-BitWidth, dl, AmtVT));
  7807. SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
  7808. SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
  7809. SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
  7810. Tmp4, Tmp6, ISD::SETLE);
  7811. SDValue OutOps[] = { OutLo, OutHi };
  7812. return DAG.getMergeValues(OutOps, dl);
  7813. }
  7814. SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
  7815. SelectionDAG &DAG) const {
  7816. SDLoc dl(Op);
  7817. EVT VT = Op.getValueType();
  7818. unsigned BitWidth = VT.getSizeInBits();
  7819. bool IsFSHL = Op.getOpcode() == ISD::FSHL;
  7820. SDValue X = Op.getOperand(0);
  7821. SDValue Y = Op.getOperand(1);
  7822. SDValue Z = Op.getOperand(2);
  7823. EVT AmtVT = Z.getValueType();
  7824. // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
  7825. // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
  7826. // This is simpler than TargetLowering::expandFunnelShift because we can rely
  7827. // on PowerPC shift by BW being well defined.
  7828. Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
  7829. DAG.getConstant(BitWidth - 1, dl, AmtVT));
  7830. SDValue SubZ =
  7831. DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
  7832. X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
  7833. Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
  7834. return DAG.getNode(ISD::OR, dl, VT, X, Y);
  7835. }
  7836. //===----------------------------------------------------------------------===//
  7837. // Vector related lowering.
  7838. //
  7839. /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
  7840. /// element size of SplatSize. Cast the result to VT.
  7841. static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
  7842. SelectionDAG &DAG, const SDLoc &dl) {
  7843. static const MVT VTys[] = { // canonical VT to use for each size.
  7844. MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
  7845. };
  7846. EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
  7847. // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
  7848. if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
  7849. SplatSize = 1;
  7850. Val = 0xFF;
  7851. }
  7852. EVT CanonicalVT = VTys[SplatSize-1];
  7853. // Build a canonical splat for this value.
  7854. return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
  7855. }
  7856. /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
  7857. /// specified intrinsic ID.
  7858. static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
  7859. const SDLoc &dl, EVT DestVT = MVT::Other) {
  7860. if (DestVT == MVT::Other) DestVT = Op.getValueType();
  7861. return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
  7862. DAG.getConstant(IID, dl, MVT::i32), Op);
  7863. }
  7864. /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
  7865. /// specified intrinsic ID.
  7866. static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
  7867. SelectionDAG &DAG, const SDLoc &dl,
  7868. EVT DestVT = MVT::Other) {
  7869. if (DestVT == MVT::Other) DestVT = LHS.getValueType();
  7870. return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
  7871. DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
  7872. }
  7873. /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
  7874. /// specified intrinsic ID.
  7875. static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
  7876. SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
  7877. EVT DestVT = MVT::Other) {
  7878. if (DestVT == MVT::Other) DestVT = Op0.getValueType();
  7879. return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
  7880. DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
  7881. }
  7882. /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
  7883. /// amount. The result has the specified value type.
  7884. static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
  7885. SelectionDAG &DAG, const SDLoc &dl) {
  7886. // Force LHS/RHS to be the right type.
  7887. LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
  7888. RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
  7889. int Ops[16];
  7890. for (unsigned i = 0; i != 16; ++i)
  7891. Ops[i] = i + Amt;
  7892. SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
  7893. return DAG.getNode(ISD::BITCAST, dl, VT, T);
  7894. }
  7895. /// Do we have an efficient pattern in a .td file for this node?
  7896. ///
  7897. /// \param V - pointer to the BuildVectorSDNode being matched
  7898. /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
  7899. ///
  7900. /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
  7901. /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
  7902. /// the opposite is true (expansion is beneficial) are:
  7903. /// - The node builds a vector out of integers that are not 32 or 64-bits
  7904. /// - The node builds a vector out of constants
  7905. /// - The node is a "load-and-splat"
  7906. /// In all other cases, we will choose to keep the BUILD_VECTOR.
  7907. static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
  7908. bool HasDirectMove,
  7909. bool HasP8Vector) {
  7910. EVT VecVT = V->getValueType(0);
  7911. bool RightType = VecVT == MVT::v2f64 ||
  7912. (HasP8Vector && VecVT == MVT::v4f32) ||
  7913. (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
  7914. if (!RightType)
  7915. return false;
  7916. bool IsSplat = true;
  7917. bool IsLoad = false;
  7918. SDValue Op0 = V->getOperand(0);
  7919. // This function is called in a block that confirms the node is not a constant
  7920. // splat. So a constant BUILD_VECTOR here means the vector is built out of
  7921. // different constants.
  7922. if (V->isConstant())
  7923. return false;
  7924. for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
  7925. if (V->getOperand(i).isUndef())
  7926. return false;
  7927. // We want to expand nodes that represent load-and-splat even if the
  7928. // loaded value is a floating point truncation or conversion to int.
  7929. if (V->getOperand(i).getOpcode() == ISD::LOAD ||
  7930. (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
  7931. V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
  7932. (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
  7933. V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
  7934. (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
  7935. V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
  7936. IsLoad = true;
  7937. // If the operands are different or the input is not a load and has more
  7938. // uses than just this BV node, then it isn't a splat.
  7939. if (V->getOperand(i) != Op0 ||
  7940. (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
  7941. IsSplat = false;
  7942. }
  7943. return !(IsSplat && IsLoad);
  7944. }
  7945. // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
  7946. SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
  7947. SDLoc dl(Op);
  7948. SDValue Op0 = Op->getOperand(0);
  7949. if ((Op.getValueType() != MVT::f128) ||
  7950. (Op0.getOpcode() != ISD::BUILD_PAIR) ||
  7951. (Op0.getOperand(0).getValueType() != MVT::i64) ||
  7952. (Op0.getOperand(1).getValueType() != MVT::i64))
  7953. return SDValue();
  7954. return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
  7955. Op0.getOperand(1));
  7956. }
  7957. static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
  7958. const SDValue *InputLoad = &Op;
  7959. while (InputLoad->getOpcode() == ISD::BITCAST)
  7960. InputLoad = &InputLoad->getOperand(0);
  7961. if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
  7962. InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
  7963. IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
  7964. InputLoad = &InputLoad->getOperand(0);
  7965. }
  7966. if (InputLoad->getOpcode() != ISD::LOAD)
  7967. return nullptr;
  7968. LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
  7969. return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
  7970. }
  7971. // Convert the argument APFloat to a single precision APFloat if there is no
  7972. // loss in information during the conversion to single precision APFloat and the
  7973. // resulting number is not a denormal number. Return true if successful.
  7974. bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
  7975. APFloat APFloatToConvert = ArgAPFloat;
  7976. bool LosesInfo = true;
  7977. APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
  7978. &LosesInfo);
  7979. bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
  7980. if (Success)
  7981. ArgAPFloat = APFloatToConvert;
  7982. return Success;
  7983. }
  7984. // Bitcast the argument APInt to a double and convert it to a single precision
  7985. // APFloat, bitcast the APFloat to an APInt and assign it to the original
  7986. // argument if there is no loss in information during the conversion from
  7987. // double to single precision APFloat and the resulting number is not a denormal
  7988. // number. Return true if successful.
  7989. bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
  7990. double DpValue = ArgAPInt.bitsToDouble();
  7991. APFloat APFloatDp(DpValue);
  7992. bool Success = convertToNonDenormSingle(APFloatDp);
  7993. if (Success)
  7994. ArgAPInt = APFloatDp.bitcastToAPInt();
  7995. return Success;
  7996. }
  7997. // Nondestructive check for convertTonNonDenormSingle.
  7998. bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) {
  7999. // Only convert if it loses info, since XXSPLTIDP should
  8000. // handle the other case.
  8001. APFloat APFloatToConvert = ArgAPFloat;
  8002. bool LosesInfo = true;
  8003. APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
  8004. &LosesInfo);
  8005. return (!LosesInfo && !APFloatToConvert.isDenormal());
  8006. }
  8007. static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op,
  8008. unsigned &Opcode) {
  8009. LoadSDNode *InputNode = dyn_cast<LoadSDNode>(Op.getOperand(0));
  8010. if (!InputNode || !Subtarget.hasVSX() || !ISD::isUNINDEXEDLoad(InputNode))
  8011. return false;
  8012. EVT Ty = Op->getValueType(0);
  8013. // For v2f64, v4f32 and v4i32 types, we require the load to be non-extending
  8014. // as we cannot handle extending loads for these types.
  8015. if ((Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32) &&
  8016. ISD::isNON_EXTLoad(InputNode))
  8017. return true;
  8018. EVT MemVT = InputNode->getMemoryVT();
  8019. // For v8i16 and v16i8 types, extending loads can be handled as long as the
  8020. // memory VT is the same vector element VT type.
  8021. // The loads feeding into the v8i16 and v16i8 types will be extending because
  8022. // scalar i8/i16 are not legal types.
  8023. if ((Ty == MVT::v8i16 || Ty == MVT::v16i8) && ISD::isEXTLoad(InputNode) &&
  8024. (MemVT == Ty.getVectorElementType()))
  8025. return true;
  8026. if (Ty == MVT::v2i64) {
  8027. // Check the extend type, when the input type is i32, and the output vector
  8028. // type is v2i64.
  8029. if (MemVT == MVT::i32) {
  8030. if (ISD::isZEXTLoad(InputNode))
  8031. Opcode = PPCISD::ZEXT_LD_SPLAT;
  8032. if (ISD::isSEXTLoad(InputNode))
  8033. Opcode = PPCISD::SEXT_LD_SPLAT;
  8034. }
  8035. return true;
  8036. }
  8037. return false;
  8038. }
  8039. // If this is a case we can't handle, return null and let the default
  8040. // expansion code take care of it. If we CAN select this case, and if it
  8041. // selects to a single instruction, return Op. Otherwise, if we can codegen
  8042. // this case more efficiently than a constant pool load, lower it to the
  8043. // sequence of ops that should be used.
  8044. SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
  8045. SelectionDAG &DAG) const {
  8046. SDLoc dl(Op);
  8047. BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
  8048. assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
  8049. // Check if this is a splat of a constant value.
  8050. APInt APSplatBits, APSplatUndef;
  8051. unsigned SplatBitSize;
  8052. bool HasAnyUndefs;
  8053. bool BVNIsConstantSplat =
  8054. BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
  8055. HasAnyUndefs, 0, !Subtarget.isLittleEndian());
  8056. // If it is a splat of a double, check if we can shrink it to a 32 bit
  8057. // non-denormal float which when converted back to double gives us the same
  8058. // double. This is to exploit the XXSPLTIDP instruction.
  8059. // If we lose precision, we use XXSPLTI32DX.
  8060. if (BVNIsConstantSplat && (SplatBitSize == 64) &&
  8061. Subtarget.hasPrefixInstrs()) {
  8062. // Check the type first to short-circuit so we don't modify APSplatBits if
  8063. // this block isn't executed.
  8064. if ((Op->getValueType(0) == MVT::v2f64) &&
  8065. convertToNonDenormSingle(APSplatBits)) {
  8066. SDValue SplatNode = DAG.getNode(
  8067. PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
  8068. DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
  8069. return DAG.getBitcast(Op.getValueType(), SplatNode);
  8070. } else {
  8071. // We may lose precision, so we have to use XXSPLTI32DX.
  8072. uint32_t Hi =
  8073. (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32);
  8074. uint32_t Lo =
  8075. (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF);
  8076. SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
  8077. if (!Hi || !Lo)
  8078. // If either load is 0, then we should generate XXLXOR to set to 0.
  8079. SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
  8080. if (Hi)
  8081. SplatNode = DAG.getNode(
  8082. PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
  8083. DAG.getTargetConstant(0, dl, MVT::i32),
  8084. DAG.getTargetConstant(Hi, dl, MVT::i32));
  8085. if (Lo)
  8086. SplatNode =
  8087. DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
  8088. DAG.getTargetConstant(1, dl, MVT::i32),
  8089. DAG.getTargetConstant(Lo, dl, MVT::i32));
  8090. return DAG.getBitcast(Op.getValueType(), SplatNode);
  8091. }
  8092. }
  8093. if (!BVNIsConstantSplat || SplatBitSize > 32) {
  8094. unsigned NewOpcode = PPCISD::LD_SPLAT;
  8095. // Handle load-and-splat patterns as we have instructions that will do this
  8096. // in one go.
  8097. if (DAG.isSplatValue(Op, true) &&
  8098. isValidSplatLoad(Subtarget, Op, NewOpcode)) {
  8099. const SDValue *InputLoad = &Op.getOperand(0);
  8100. LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
  8101. // If the input load is an extending load, it will be an i32 -> i64
  8102. // extending load and isValidSplatLoad() will update NewOpcode.
  8103. unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits();
  8104. unsigned ElementSize =
  8105. MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2);
  8106. assert(((ElementSize == 2 * MemorySize)
  8107. ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT ||
  8108. NewOpcode == PPCISD::SEXT_LD_SPLAT)
  8109. : (NewOpcode == PPCISD::LD_SPLAT)) &&
  8110. "Unmatched element size and opcode!\n");
  8111. // Checking for a single use of this load, we have to check for vector
  8112. // width (128 bits) / ElementSize uses (since each operand of the
  8113. // BUILD_VECTOR is a separate use of the value.
  8114. unsigned NumUsesOfInputLD = 128 / ElementSize;
  8115. for (SDValue BVInOp : Op->ops())
  8116. if (BVInOp.isUndef())
  8117. NumUsesOfInputLD--;
  8118. // Exclude somes case where LD_SPLAT is worse than scalar_to_vector:
  8119. // Below cases should also happen for "lfiwzx/lfiwax + LE target + index
  8120. // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index
  8121. // 15", but funciton IsValidSplatLoad() now will only return true when
  8122. // the data at index 0 is not nullptr. So we will not get into trouble for
  8123. // these cases.
  8124. //
  8125. // case 1 - lfiwzx/lfiwax
  8126. // 1.1: load result is i32 and is sign/zero extend to i64;
  8127. // 1.2: build a v2i64 vector type with above loaded value;
  8128. // 1.3: the vector has only one value at index 0, others are all undef;
  8129. // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute.
  8130. if (NumUsesOfInputLD == 1 &&
  8131. (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT &&
  8132. !Subtarget.isLittleEndian() && Subtarget.hasVSX() &&
  8133. Subtarget.hasLFIWAX()))
  8134. return SDValue();
  8135. // case 2 - lxvr[hb]x
  8136. // 2.1: load result is at most i16;
  8137. // 2.2: build a vector with above loaded value;
  8138. // 2.3: the vector has only one value at index 0, others are all undef;
  8139. // 2.4: on LE target, so that lxvr[hb]x does not need any permute.
  8140. if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() &&
  8141. Subtarget.isISA3_1() && ElementSize <= 16)
  8142. return SDValue();
  8143. assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
  8144. if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
  8145. Subtarget.hasVSX()) {
  8146. SDValue Ops[] = {
  8147. LD->getChain(), // Chain
  8148. LD->getBasePtr(), // Ptr
  8149. DAG.getValueType(Op.getValueType()) // VT
  8150. };
  8151. SDValue LdSplt = DAG.getMemIntrinsicNode(
  8152. NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops,
  8153. LD->getMemoryVT(), LD->getMemOperand());
  8154. // Replace all uses of the output chain of the original load with the
  8155. // output chain of the new load.
  8156. DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
  8157. LdSplt.getValue(1));
  8158. return LdSplt;
  8159. }
  8160. }
  8161. // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
  8162. // 32-bits can be lowered to VSX instructions under certain conditions.
  8163. // Without VSX, there is no pattern more efficient than expanding the node.
  8164. if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
  8165. haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
  8166. Subtarget.hasP8Vector()))
  8167. return Op;
  8168. return SDValue();
  8169. }
  8170. uint64_t SplatBits = APSplatBits.getZExtValue();
  8171. uint64_t SplatUndef = APSplatUndef.getZExtValue();
  8172. unsigned SplatSize = SplatBitSize / 8;
  8173. // First, handle single instruction cases.
  8174. // All zeros?
  8175. if (SplatBits == 0) {
  8176. // Canonicalize all zero vectors to be v4i32.
  8177. if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
  8178. SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
  8179. Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
  8180. }
  8181. return Op;
  8182. }
  8183. // We have XXSPLTIW for constant splats four bytes wide.
  8184. // Given vector length is a multiple of 4, 2-byte splats can be replaced
  8185. // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
  8186. // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
  8187. // turned into a 4-byte splat of 0xABABABAB.
  8188. if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
  8189. return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
  8190. Op.getValueType(), DAG, dl);
  8191. if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
  8192. return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
  8193. dl);
  8194. // We have XXSPLTIB for constant splats one byte wide.
  8195. if (Subtarget.hasP9Vector() && SplatSize == 1)
  8196. return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
  8197. dl);
  8198. // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
  8199. int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
  8200. (32-SplatBitSize));
  8201. if (SextVal >= -16 && SextVal <= 15)
  8202. return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
  8203. dl);
  8204. // Two instruction sequences.
  8205. // If this value is in the range [-32,30] and is even, use:
  8206. // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
  8207. // If this value is in the range [17,31] and is odd, use:
  8208. // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
  8209. // If this value is in the range [-31,-17] and is odd, use:
  8210. // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
  8211. // Note the last two are three-instruction sequences.
  8212. if (SextVal >= -32 && SextVal <= 31) {
  8213. // To avoid having these optimizations undone by constant folding,
  8214. // we convert to a pseudo that will be expanded later into one of
  8215. // the above forms.
  8216. SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
  8217. EVT VT = (SplatSize == 1 ? MVT::v16i8 :
  8218. (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
  8219. SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
  8220. SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
  8221. if (VT == Op.getValueType())
  8222. return RetVal;
  8223. else
  8224. return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
  8225. }
  8226. // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
  8227. // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
  8228. // for fneg/fabs.
  8229. if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
  8230. // Make -1 and vspltisw -1:
  8231. SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
  8232. // Make the VSLW intrinsic, computing 0x8000_0000.
  8233. SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
  8234. OnesV, DAG, dl);
  8235. // xor by OnesV to invert it.
  8236. Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
  8237. return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
  8238. }
  8239. // Check to see if this is a wide variety of vsplti*, binop self cases.
  8240. static const signed char SplatCsts[] = {
  8241. -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
  8242. -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
  8243. };
  8244. for (unsigned idx = 0; idx < std::size(SplatCsts); ++idx) {
  8245. // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
  8246. // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
  8247. int i = SplatCsts[idx];
  8248. // Figure out what shift amount will be used by altivec if shifted by i in
  8249. // this splat size.
  8250. unsigned TypeShiftAmt = i & (SplatBitSize-1);
  8251. // vsplti + shl self.
  8252. if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
  8253. SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
  8254. static const unsigned IIDs[] = { // Intrinsic to use for each size.
  8255. Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
  8256. Intrinsic::ppc_altivec_vslw
  8257. };
  8258. Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
  8259. return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
  8260. }
  8261. // vsplti + srl self.
  8262. if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
  8263. SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
  8264. static const unsigned IIDs[] = { // Intrinsic to use for each size.
  8265. Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
  8266. Intrinsic::ppc_altivec_vsrw
  8267. };
  8268. Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
  8269. return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
  8270. }
  8271. // vsplti + rol self.
  8272. if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
  8273. ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
  8274. SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
  8275. static const unsigned IIDs[] = { // Intrinsic to use for each size.
  8276. Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
  8277. Intrinsic::ppc_altivec_vrlw
  8278. };
  8279. Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
  8280. return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
  8281. }
  8282. // t = vsplti c, result = vsldoi t, t, 1
  8283. if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
  8284. SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
  8285. unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
  8286. return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
  8287. }
  8288. // t = vsplti c, result = vsldoi t, t, 2
  8289. if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
  8290. SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
  8291. unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
  8292. return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
  8293. }
  8294. // t = vsplti c, result = vsldoi t, t, 3
  8295. if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
  8296. SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
  8297. unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
  8298. return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
  8299. }
  8300. }
  8301. return SDValue();
  8302. }
  8303. /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
  8304. /// the specified operations to build the shuffle.
  8305. static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
  8306. SDValue RHS, SelectionDAG &DAG,
  8307. const SDLoc &dl) {
  8308. unsigned OpNum = (PFEntry >> 26) & 0x0F;
  8309. unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
  8310. unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
  8311. enum {
  8312. OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
  8313. OP_VMRGHW,
  8314. OP_VMRGLW,
  8315. OP_VSPLTISW0,
  8316. OP_VSPLTISW1,
  8317. OP_VSPLTISW2,
  8318. OP_VSPLTISW3,
  8319. OP_VSLDOI4,
  8320. OP_VSLDOI8,
  8321. OP_VSLDOI12
  8322. };
  8323. if (OpNum == OP_COPY) {
  8324. if (LHSID == (1*9+2)*9+3) return LHS;
  8325. assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
  8326. return RHS;
  8327. }
  8328. SDValue OpLHS, OpRHS;
  8329. OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
  8330. OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
  8331. int ShufIdxs[16];
  8332. switch (OpNum) {
  8333. default: llvm_unreachable("Unknown i32 permute!");
  8334. case OP_VMRGHW:
  8335. ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
  8336. ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
  8337. ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
  8338. ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
  8339. break;
  8340. case OP_VMRGLW:
  8341. ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
  8342. ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
  8343. ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
  8344. ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
  8345. break;
  8346. case OP_VSPLTISW0:
  8347. for (unsigned i = 0; i != 16; ++i)
  8348. ShufIdxs[i] = (i&3)+0;
  8349. break;
  8350. case OP_VSPLTISW1:
  8351. for (unsigned i = 0; i != 16; ++i)
  8352. ShufIdxs[i] = (i&3)+4;
  8353. break;
  8354. case OP_VSPLTISW2:
  8355. for (unsigned i = 0; i != 16; ++i)
  8356. ShufIdxs[i] = (i&3)+8;
  8357. break;
  8358. case OP_VSPLTISW3:
  8359. for (unsigned i = 0; i != 16; ++i)
  8360. ShufIdxs[i] = (i&3)+12;
  8361. break;
  8362. case OP_VSLDOI4:
  8363. return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
  8364. case OP_VSLDOI8:
  8365. return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
  8366. case OP_VSLDOI12:
  8367. return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
  8368. }
  8369. EVT VT = OpLHS.getValueType();
  8370. OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
  8371. OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
  8372. SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
  8373. return DAG.getNode(ISD::BITCAST, dl, VT, T);
  8374. }
  8375. /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
  8376. /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
  8377. /// SDValue.
  8378. SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
  8379. SelectionDAG &DAG) const {
  8380. const unsigned BytesInVector = 16;
  8381. bool IsLE = Subtarget.isLittleEndian();
  8382. SDLoc dl(N);
  8383. SDValue V1 = N->getOperand(0);
  8384. SDValue V2 = N->getOperand(1);
  8385. unsigned ShiftElts = 0, InsertAtByte = 0;
  8386. bool Swap = false;
  8387. // Shifts required to get the byte we want at element 7.
  8388. unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1,
  8389. 0, 15, 14, 13, 12, 11, 10, 9};
  8390. unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
  8391. 1, 2, 3, 4, 5, 6, 7, 8};
  8392. ArrayRef<int> Mask = N->getMask();
  8393. int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
  8394. // For each mask element, find out if we're just inserting something
  8395. // from V2 into V1 or vice versa.
  8396. // Possible permutations inserting an element from V2 into V1:
  8397. // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
  8398. // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
  8399. // ...
  8400. // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
  8401. // Inserting from V1 into V2 will be similar, except mask range will be
  8402. // [16,31].
  8403. bool FoundCandidate = false;
  8404. // If both vector operands for the shuffle are the same vector, the mask
  8405. // will contain only elements from the first one and the second one will be
  8406. // undef.
  8407. unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
  8408. // Go through the mask of half-words to find an element that's being moved
  8409. // from one vector to the other.
  8410. for (unsigned i = 0; i < BytesInVector; ++i) {
  8411. unsigned CurrentElement = Mask[i];
  8412. // If 2nd operand is undefined, we should only look for element 7 in the
  8413. // Mask.
  8414. if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
  8415. continue;
  8416. bool OtherElementsInOrder = true;
  8417. // Examine the other elements in the Mask to see if they're in original
  8418. // order.
  8419. for (unsigned j = 0; j < BytesInVector; ++j) {
  8420. if (j == i)
  8421. continue;
  8422. // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
  8423. // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined,
  8424. // in which we always assume we're always picking from the 1st operand.
  8425. int MaskOffset =
  8426. (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
  8427. if (Mask[j] != OriginalOrder[j] + MaskOffset) {
  8428. OtherElementsInOrder = false;
  8429. break;
  8430. }
  8431. }
  8432. // If other elements are in original order, we record the number of shifts
  8433. // we need to get the element we want into element 7. Also record which byte
  8434. // in the vector we should insert into.
  8435. if (OtherElementsInOrder) {
  8436. // If 2nd operand is undefined, we assume no shifts and no swapping.
  8437. if (V2.isUndef()) {
  8438. ShiftElts = 0;
  8439. Swap = false;
  8440. } else {
  8441. // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
  8442. ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
  8443. : BigEndianShifts[CurrentElement & 0xF];
  8444. Swap = CurrentElement < BytesInVector;
  8445. }
  8446. InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
  8447. FoundCandidate = true;
  8448. break;
  8449. }
  8450. }
  8451. if (!FoundCandidate)
  8452. return SDValue();
  8453. // Candidate found, construct the proper SDAG sequence with VINSERTB,
  8454. // optionally with VECSHL if shift is required.
  8455. if (Swap)
  8456. std::swap(V1, V2);
  8457. if (V2.isUndef())
  8458. V2 = V1;
  8459. if (ShiftElts) {
  8460. SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
  8461. DAG.getConstant(ShiftElts, dl, MVT::i32));
  8462. return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
  8463. DAG.getConstant(InsertAtByte, dl, MVT::i32));
  8464. }
  8465. return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
  8466. DAG.getConstant(InsertAtByte, dl, MVT::i32));
  8467. }
  8468. /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
  8469. /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
  8470. /// SDValue.
  8471. SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
  8472. SelectionDAG &DAG) const {
  8473. const unsigned NumHalfWords = 8;
  8474. const unsigned BytesInVector = NumHalfWords * 2;
  8475. // Check that the shuffle is on half-words.
  8476. if (!isNByteElemShuffleMask(N, 2, 1))
  8477. return SDValue();
  8478. bool IsLE = Subtarget.isLittleEndian();
  8479. SDLoc dl(N);
  8480. SDValue V1 = N->getOperand(0);
  8481. SDValue V2 = N->getOperand(1);
  8482. unsigned ShiftElts = 0, InsertAtByte = 0;
  8483. bool Swap = false;
  8484. // Shifts required to get the half-word we want at element 3.
  8485. unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
  8486. unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
  8487. uint32_t Mask = 0;
  8488. uint32_t OriginalOrderLow = 0x1234567;
  8489. uint32_t OriginalOrderHigh = 0x89ABCDEF;
  8490. // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a
  8491. // 32-bit space, only need 4-bit nibbles per element.
  8492. for (unsigned i = 0; i < NumHalfWords; ++i) {
  8493. unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
  8494. Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
  8495. }
  8496. // For each mask element, find out if we're just inserting something
  8497. // from V2 into V1 or vice versa. Possible permutations inserting an element
  8498. // from V2 into V1:
  8499. // X, 1, 2, 3, 4, 5, 6, 7
  8500. // 0, X, 2, 3, 4, 5, 6, 7
  8501. // 0, 1, X, 3, 4, 5, 6, 7
  8502. // 0, 1, 2, X, 4, 5, 6, 7
  8503. // 0, 1, 2, 3, X, 5, 6, 7
  8504. // 0, 1, 2, 3, 4, X, 6, 7
  8505. // 0, 1, 2, 3, 4, 5, X, 7
  8506. // 0, 1, 2, 3, 4, 5, 6, X
  8507. // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
  8508. bool FoundCandidate = false;
  8509. // Go through the mask of half-words to find an element that's being moved
  8510. // from one vector to the other.
  8511. for (unsigned i = 0; i < NumHalfWords; ++i) {
  8512. unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
  8513. uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
  8514. uint32_t MaskOtherElts = ~(0xF << MaskShift);
  8515. uint32_t TargetOrder = 0x0;
  8516. // If both vector operands for the shuffle are the same vector, the mask
  8517. // will contain only elements from the first one and the second one will be
  8518. // undef.
  8519. if (V2.isUndef()) {
  8520. ShiftElts = 0;
  8521. unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
  8522. TargetOrder = OriginalOrderLow;
  8523. Swap = false;
  8524. // Skip if not the correct element or mask of other elements don't equal
  8525. // to our expected order.
  8526. if (MaskOneElt == VINSERTHSrcElem &&
  8527. (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
  8528. InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
  8529. FoundCandidate = true;
  8530. break;
  8531. }
  8532. } else { // If both operands are defined.
  8533. // Target order is [8,15] if the current mask is between [0,7].
  8534. TargetOrder =
  8535. (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
  8536. // Skip if mask of other elements don't equal our expected order.
  8537. if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
  8538. // We only need the last 3 bits for the number of shifts.
  8539. ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
  8540. : BigEndianShifts[MaskOneElt & 0x7];
  8541. InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
  8542. Swap = MaskOneElt < NumHalfWords;
  8543. FoundCandidate = true;
  8544. break;
  8545. }
  8546. }
  8547. }
  8548. if (!FoundCandidate)
  8549. return SDValue();
  8550. // Candidate found, construct the proper SDAG sequence with VINSERTH,
  8551. // optionally with VECSHL if shift is required.
  8552. if (Swap)
  8553. std::swap(V1, V2);
  8554. if (V2.isUndef())
  8555. V2 = V1;
  8556. SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
  8557. if (ShiftElts) {
  8558. // Double ShiftElts because we're left shifting on v16i8 type.
  8559. SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
  8560. DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
  8561. SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
  8562. SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
  8563. DAG.getConstant(InsertAtByte, dl, MVT::i32));
  8564. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
  8565. }
  8566. SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
  8567. SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
  8568. DAG.getConstant(InsertAtByte, dl, MVT::i32));
  8569. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
  8570. }
  8571. /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
  8572. /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
  8573. /// return the default SDValue.
  8574. SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
  8575. SelectionDAG &DAG) const {
  8576. // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
  8577. // to v16i8. Peek through the bitcasts to get the actual operands.
  8578. SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
  8579. SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
  8580. auto ShuffleMask = SVN->getMask();
  8581. SDValue VecShuffle(SVN, 0);
  8582. SDLoc DL(SVN);
  8583. // Check that we have a four byte shuffle.
  8584. if (!isNByteElemShuffleMask(SVN, 4, 1))
  8585. return SDValue();
  8586. // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
  8587. if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
  8588. std::swap(LHS, RHS);
  8589. VecShuffle = peekThroughBitcasts(DAG.getCommutedVectorShuffle(*SVN));
  8590. ShuffleVectorSDNode *CommutedSV = dyn_cast<ShuffleVectorSDNode>(VecShuffle);
  8591. if (!CommutedSV)
  8592. return SDValue();
  8593. ShuffleMask = CommutedSV->getMask();
  8594. }
  8595. // Ensure that the RHS is a vector of constants.
  8596. BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
  8597. if (!BVN)
  8598. return SDValue();
  8599. // Check if RHS is a splat of 4-bytes (or smaller).
  8600. APInt APSplatValue, APSplatUndef;
  8601. unsigned SplatBitSize;
  8602. bool HasAnyUndefs;
  8603. if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
  8604. HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
  8605. SplatBitSize > 32)
  8606. return SDValue();
  8607. // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
  8608. // The instruction splats a constant C into two words of the source vector
  8609. // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
  8610. // Thus we check that the shuffle mask is the equivalent of
  8611. // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
  8612. // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
  8613. // within each word are consecutive, so we only need to check the first byte.
  8614. SDValue Index;
  8615. bool IsLE = Subtarget.isLittleEndian();
  8616. if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
  8617. (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
  8618. ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
  8619. Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
  8620. else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
  8621. (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
  8622. ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
  8623. Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
  8624. else
  8625. return SDValue();
  8626. // If the splat is narrower than 32-bits, we need to get the 32-bit value
  8627. // for XXSPLTI32DX.
  8628. unsigned SplatVal = APSplatValue.getZExtValue();
  8629. for (; SplatBitSize < 32; SplatBitSize <<= 1)
  8630. SplatVal |= (SplatVal << SplatBitSize);
  8631. SDValue SplatNode = DAG.getNode(
  8632. PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
  8633. Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
  8634. return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
  8635. }
  8636. /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
  8637. /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
  8638. /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
  8639. /// i.e (or (shl x, C1), (srl x, 128-C1)).
  8640. SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
  8641. assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
  8642. assert(Op.getValueType() == MVT::v1i128 &&
  8643. "Only set v1i128 as custom, other type shouldn't reach here!");
  8644. SDLoc dl(Op);
  8645. SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
  8646. SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
  8647. unsigned SHLAmt = N1.getConstantOperandVal(0);
  8648. if (SHLAmt % 8 == 0) {
  8649. std::array<int, 16> Mask;
  8650. std::iota(Mask.begin(), Mask.end(), 0);
  8651. std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
  8652. if (SDValue Shuffle =
  8653. DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
  8654. DAG.getUNDEF(MVT::v16i8), Mask))
  8655. return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
  8656. }
  8657. SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
  8658. SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
  8659. DAG.getConstant(SHLAmt, dl, MVT::i32));
  8660. SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
  8661. DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
  8662. SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
  8663. return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
  8664. }
  8665. /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
  8666. /// is a shuffle we can handle in a single instruction, return it. Otherwise,
  8667. /// return the code it can be lowered into. Worst case, it can always be
  8668. /// lowered into a vperm.
  8669. SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
  8670. SelectionDAG &DAG) const {
  8671. SDLoc dl(Op);
  8672. SDValue V1 = Op.getOperand(0);
  8673. SDValue V2 = Op.getOperand(1);
  8674. ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
  8675. // Any nodes that were combined in the target-independent combiner prior
  8676. // to vector legalization will not be sent to the target combine. Try to
  8677. // combine it here.
  8678. if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
  8679. if (!isa<ShuffleVectorSDNode>(NewShuffle))
  8680. return NewShuffle;
  8681. Op = NewShuffle;
  8682. SVOp = cast<ShuffleVectorSDNode>(Op);
  8683. V1 = Op.getOperand(0);
  8684. V2 = Op.getOperand(1);
  8685. }
  8686. EVT VT = Op.getValueType();
  8687. bool isLittleEndian = Subtarget.isLittleEndian();
  8688. unsigned ShiftElts, InsertAtByte;
  8689. bool Swap = false;
  8690. // If this is a load-and-splat, we can do that with a single instruction
  8691. // in some cases. However if the load has multiple uses, we don't want to
  8692. // combine it because that will just produce multiple loads.
  8693. bool IsPermutedLoad = false;
  8694. const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
  8695. if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
  8696. (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
  8697. InputLoad->hasOneUse()) {
  8698. bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
  8699. int SplatIdx =
  8700. PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
  8701. // The splat index for permuted loads will be in the left half of the vector
  8702. // which is strictly wider than the loaded value by 8 bytes. So we need to
  8703. // adjust the splat index to point to the correct address in memory.
  8704. if (IsPermutedLoad) {
  8705. assert((isLittleEndian || IsFourByte) &&
  8706. "Unexpected size for permuted load on big endian target");
  8707. SplatIdx += IsFourByte ? 2 : 1;
  8708. assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
  8709. "Splat of a value outside of the loaded memory");
  8710. }
  8711. LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
  8712. // For 4-byte load-and-splat, we need Power9.
  8713. if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
  8714. uint64_t Offset = 0;
  8715. if (IsFourByte)
  8716. Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
  8717. else
  8718. Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
  8719. // If the width of the load is the same as the width of the splat,
  8720. // loading with an offset would load the wrong memory.
  8721. if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64))
  8722. Offset = 0;
  8723. SDValue BasePtr = LD->getBasePtr();
  8724. if (Offset != 0)
  8725. BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
  8726. BasePtr, DAG.getIntPtrConstant(Offset, dl));
  8727. SDValue Ops[] = {
  8728. LD->getChain(), // Chain
  8729. BasePtr, // BasePtr
  8730. DAG.getValueType(Op.getValueType()) // VT
  8731. };
  8732. SDVTList VTL =
  8733. DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
  8734. SDValue LdSplt =
  8735. DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
  8736. Ops, LD->getMemoryVT(), LD->getMemOperand());
  8737. DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
  8738. if (LdSplt.getValueType() != SVOp->getValueType(0))
  8739. LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
  8740. return LdSplt;
  8741. }
  8742. }
  8743. // All v2i64 and v2f64 shuffles are legal
  8744. if (VT == MVT::v2i64 || VT == MVT::v2f64)
  8745. return Op;
  8746. if (Subtarget.hasP9Vector() &&
  8747. PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
  8748. isLittleEndian)) {
  8749. if (Swap)
  8750. std::swap(V1, V2);
  8751. SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
  8752. SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
  8753. if (ShiftElts) {
  8754. SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
  8755. DAG.getConstant(ShiftElts, dl, MVT::i32));
  8756. SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
  8757. DAG.getConstant(InsertAtByte, dl, MVT::i32));
  8758. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
  8759. }
  8760. SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
  8761. DAG.getConstant(InsertAtByte, dl, MVT::i32));
  8762. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
  8763. }
  8764. if (Subtarget.hasPrefixInstrs()) {
  8765. SDValue SplatInsertNode;
  8766. if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
  8767. return SplatInsertNode;
  8768. }
  8769. if (Subtarget.hasP9Altivec()) {
  8770. SDValue NewISDNode;
  8771. if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
  8772. return NewISDNode;
  8773. if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
  8774. return NewISDNode;
  8775. }
  8776. if (Subtarget.hasVSX() &&
  8777. PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
  8778. if (Swap)
  8779. std::swap(V1, V2);
  8780. SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
  8781. SDValue Conv2 =
  8782. DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
  8783. SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
  8784. DAG.getConstant(ShiftElts, dl, MVT::i32));
  8785. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
  8786. }
  8787. if (Subtarget.hasVSX() &&
  8788. PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
  8789. if (Swap)
  8790. std::swap(V1, V2);
  8791. SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
  8792. SDValue Conv2 =
  8793. DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
  8794. SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
  8795. DAG.getConstant(ShiftElts, dl, MVT::i32));
  8796. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
  8797. }
  8798. if (Subtarget.hasP9Vector()) {
  8799. if (PPC::isXXBRHShuffleMask(SVOp)) {
  8800. SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
  8801. SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
  8802. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
  8803. } else if (PPC::isXXBRWShuffleMask(SVOp)) {
  8804. SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
  8805. SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
  8806. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
  8807. } else if (PPC::isXXBRDShuffleMask(SVOp)) {
  8808. SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
  8809. SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
  8810. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
  8811. } else if (PPC::isXXBRQShuffleMask(SVOp)) {
  8812. SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
  8813. SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
  8814. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
  8815. }
  8816. }
  8817. if (Subtarget.hasVSX()) {
  8818. if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
  8819. int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
  8820. SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
  8821. SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
  8822. DAG.getConstant(SplatIdx, dl, MVT::i32));
  8823. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
  8824. }
  8825. // Left shifts of 8 bytes are actually swaps. Convert accordingly.
  8826. if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
  8827. SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
  8828. SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
  8829. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
  8830. }
  8831. }
  8832. // Cases that are handled by instructions that take permute immediates
  8833. // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
  8834. // selected by the instruction selector.
  8835. if (V2.isUndef()) {
  8836. if (PPC::isSplatShuffleMask(SVOp, 1) ||
  8837. PPC::isSplatShuffleMask(SVOp, 2) ||
  8838. PPC::isSplatShuffleMask(SVOp, 4) ||
  8839. PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
  8840. PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
  8841. PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
  8842. PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
  8843. PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
  8844. PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
  8845. PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
  8846. PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
  8847. PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
  8848. (Subtarget.hasP8Altivec() && (
  8849. PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
  8850. PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
  8851. PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
  8852. return Op;
  8853. }
  8854. }
  8855. // Altivec has a variety of "shuffle immediates" that take two vector inputs
  8856. // and produce a fixed permutation. If any of these match, do not lower to
  8857. // VPERM.
  8858. unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
  8859. if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
  8860. PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
  8861. PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
  8862. PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
  8863. PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
  8864. PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
  8865. PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
  8866. PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
  8867. PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
  8868. (Subtarget.hasP8Altivec() && (
  8869. PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
  8870. PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
  8871. PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
  8872. return Op;
  8873. // Check to see if this is a shuffle of 4-byte values. If so, we can use our
  8874. // perfect shuffle table to emit an optimal matching sequence.
  8875. ArrayRef<int> PermMask = SVOp->getMask();
  8876. if (!DisablePerfectShuffle && !isLittleEndian) {
  8877. unsigned PFIndexes[4];
  8878. bool isFourElementShuffle = true;
  8879. for (unsigned i = 0; i != 4 && isFourElementShuffle;
  8880. ++i) { // Element number
  8881. unsigned EltNo = 8; // Start out undef.
  8882. for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
  8883. if (PermMask[i * 4 + j] < 0)
  8884. continue; // Undef, ignore it.
  8885. unsigned ByteSource = PermMask[i * 4 + j];
  8886. if ((ByteSource & 3) != j) {
  8887. isFourElementShuffle = false;
  8888. break;
  8889. }
  8890. if (EltNo == 8) {
  8891. EltNo = ByteSource / 4;
  8892. } else if (EltNo != ByteSource / 4) {
  8893. isFourElementShuffle = false;
  8894. break;
  8895. }
  8896. }
  8897. PFIndexes[i] = EltNo;
  8898. }
  8899. // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
  8900. // perfect shuffle vector to determine if it is cost effective to do this as
  8901. // discrete instructions, or whether we should use a vperm.
  8902. // For now, we skip this for little endian until such time as we have a
  8903. // little-endian perfect shuffle table.
  8904. if (isFourElementShuffle) {
  8905. // Compute the index in the perfect shuffle table.
  8906. unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
  8907. PFIndexes[2] * 9 + PFIndexes[3];
  8908. unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
  8909. unsigned Cost = (PFEntry >> 30);
  8910. // Determining when to avoid vperm is tricky. Many things affect the cost
  8911. // of vperm, particularly how many times the perm mask needs to be
  8912. // computed. For example, if the perm mask can be hoisted out of a loop or
  8913. // is already used (perhaps because there are multiple permutes with the
  8914. // same shuffle mask?) the vperm has a cost of 1. OTOH, hoisting the
  8915. // permute mask out of the loop requires an extra register.
  8916. //
  8917. // As a compromise, we only emit discrete instructions if the shuffle can
  8918. // be generated in 3 or fewer operations. When we have loop information
  8919. // available, if this block is within a loop, we should avoid using vperm
  8920. // for 3-operation perms and use a constant pool load instead.
  8921. if (Cost < 3)
  8922. return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
  8923. }
  8924. }
  8925. // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
  8926. // vector that will get spilled to the constant pool.
  8927. if (V2.isUndef()) V2 = V1;
  8928. return LowerVPERM(Op, DAG, PermMask, VT, V1, V2);
  8929. }
  8930. SDValue PPCTargetLowering::LowerVPERM(SDValue Op, SelectionDAG &DAG,
  8931. ArrayRef<int> PermMask, EVT VT,
  8932. SDValue V1, SDValue V2) const {
  8933. unsigned Opcode = PPCISD::VPERM;
  8934. EVT ValType = V1.getValueType();
  8935. SDLoc dl(Op);
  8936. bool NeedSwap = false;
  8937. bool isLittleEndian = Subtarget.isLittleEndian();
  8938. bool isPPC64 = Subtarget.isPPC64();
  8939. // Only need to place items backwards in LE,
  8940. // the mask will be properly calculated.
  8941. if (isLittleEndian)
  8942. std::swap(V1, V2);
  8943. if (Subtarget.isISA3_0() && (V1->hasOneUse() || V2->hasOneUse())) {
  8944. LLVM_DEBUG(dbgs() << "At least one of two input vectors are dead - using "
  8945. "XXPERM instead\n");
  8946. Opcode = PPCISD::XXPERM;
  8947. // if V2 is dead, then we swap V1 and V2 so we can
  8948. // use V2 as the destination instead.
  8949. if (!V1->hasOneUse() && V2->hasOneUse()) {
  8950. std::swap(V1, V2);
  8951. NeedSwap = !NeedSwap;
  8952. }
  8953. }
  8954. // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
  8955. // that it is in input element units, not in bytes. Convert now.
  8956. // For little endian, the order of the input vectors is reversed, and
  8957. // the permutation mask is complemented with respect to 31. This is
  8958. // necessary to produce proper semantics with the big-endian-based vperm
  8959. // instruction.
  8960. EVT EltVT = V1.getValueType().getVectorElementType();
  8961. unsigned BytesPerElement = EltVT.getSizeInBits() / 8;
  8962. bool V1HasXXSWAPD = V1->getOperand(0)->getOpcode() == PPCISD::XXSWAPD;
  8963. bool V2HasXXSWAPD = V2->getOperand(0)->getOpcode() == PPCISD::XXSWAPD;
  8964. /*
  8965. Vectors will be appended like so: [ V1 | v2 ]
  8966. XXSWAPD on V1:
  8967. [ A | B | C | D ] -> [ C | D | A | B ]
  8968. 0-3 4-7 8-11 12-15 0-3 4-7 8-11 12-15
  8969. i.e. index of A, B += 8, and index of C, D -= 8.
  8970. XXSWAPD on V2:
  8971. [ E | F | G | H ] -> [ G | H | E | F ]
  8972. 16-19 20-23 24-27 28-31 16-19 20-23 24-27 28-31
  8973. i.e. index of E, F += 8, index of G, H -= 8
  8974. Swap V1 and V2:
  8975. [ V1 | V2 ] -> [ V2 | V1 ]
  8976. 0-15 16-31 0-15 16-31
  8977. i.e. index of V1 += 16, index of V2 -= 16
  8978. */
  8979. SmallVector<SDValue, 16> ResultMask;
  8980. for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
  8981. unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
  8982. if (Opcode == PPCISD::XXPERM) {
  8983. if (V1HasXXSWAPD) {
  8984. if (SrcElt < 8)
  8985. SrcElt += 8;
  8986. else if (SrcElt < 16)
  8987. SrcElt -= 8;
  8988. }
  8989. if (V2HasXXSWAPD) {
  8990. if (SrcElt > 23)
  8991. SrcElt -= 8;
  8992. else if (SrcElt > 15)
  8993. SrcElt += 8;
  8994. }
  8995. if (NeedSwap) {
  8996. if (SrcElt < 16)
  8997. SrcElt += 16;
  8998. else
  8999. SrcElt -= 16;
  9000. }
  9001. }
  9002. for (unsigned j = 0; j != BytesPerElement; ++j)
  9003. if (isLittleEndian)
  9004. ResultMask.push_back(
  9005. DAG.getConstant(31 - (SrcElt * BytesPerElement + j), dl, MVT::i32));
  9006. else
  9007. ResultMask.push_back(
  9008. DAG.getConstant(SrcElt * BytesPerElement + j, dl, MVT::i32));
  9009. }
  9010. if (Opcode == PPCISD::XXPERM && (V1HasXXSWAPD || V2HasXXSWAPD)) {
  9011. if (V1HasXXSWAPD) {
  9012. dl = SDLoc(V1->getOperand(0));
  9013. V1 = V1->getOperand(0)->getOperand(1);
  9014. }
  9015. if (V2HasXXSWAPD) {
  9016. dl = SDLoc(V2->getOperand(0));
  9017. V2 = V2->getOperand(0)->getOperand(1);
  9018. }
  9019. if (isPPC64 && ValType != MVT::v2f64)
  9020. V1 = DAG.getBitcast(MVT::v2f64, V1);
  9021. if (isPPC64 && V2.getValueType() != MVT::v2f64)
  9022. V2 = DAG.getBitcast(MVT::v2f64, V2);
  9023. }
  9024. ShufflesHandledWithVPERM++;
  9025. SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
  9026. LLVM_DEBUG({
  9027. ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
  9028. if (Opcode == PPCISD::XXPERM) {
  9029. dbgs() << "Emitting a XXPERM for the following shuffle:\n";
  9030. } else {
  9031. dbgs() << "Emitting a VPERM for the following shuffle:\n";
  9032. }
  9033. SVOp->dump();
  9034. dbgs() << "With the following permute control vector:\n";
  9035. VPermMask.dump();
  9036. });
  9037. if (Opcode == PPCISD::XXPERM)
  9038. VPermMask = DAG.getBitcast(MVT::v4i32, VPermMask);
  9039. SDValue VPERMNode =
  9040. DAG.getNode(Opcode, dl, V1.getValueType(), V1, V2, VPermMask);
  9041. VPERMNode = DAG.getBitcast(ValType, VPERMNode);
  9042. return VPERMNode;
  9043. }
  9044. /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
  9045. /// vector comparison. If it is, return true and fill in Opc/isDot with
  9046. /// information about the intrinsic.
  9047. static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
  9048. bool &isDot, const PPCSubtarget &Subtarget) {
  9049. unsigned IntrinsicID =
  9050. cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
  9051. CompareOpc = -1;
  9052. isDot = false;
  9053. switch (IntrinsicID) {
  9054. default:
  9055. return false;
  9056. // Comparison predicates.
  9057. case Intrinsic::ppc_altivec_vcmpbfp_p:
  9058. CompareOpc = 966;
  9059. isDot = true;
  9060. break;
  9061. case Intrinsic::ppc_altivec_vcmpeqfp_p:
  9062. CompareOpc = 198;
  9063. isDot = true;
  9064. break;
  9065. case Intrinsic::ppc_altivec_vcmpequb_p:
  9066. CompareOpc = 6;
  9067. isDot = true;
  9068. break;
  9069. case Intrinsic::ppc_altivec_vcmpequh_p:
  9070. CompareOpc = 70;
  9071. isDot = true;
  9072. break;
  9073. case Intrinsic::ppc_altivec_vcmpequw_p:
  9074. CompareOpc = 134;
  9075. isDot = true;
  9076. break;
  9077. case Intrinsic::ppc_altivec_vcmpequd_p:
  9078. if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
  9079. CompareOpc = 199;
  9080. isDot = true;
  9081. } else
  9082. return false;
  9083. break;
  9084. case Intrinsic::ppc_altivec_vcmpneb_p:
  9085. case Intrinsic::ppc_altivec_vcmpneh_p:
  9086. case Intrinsic::ppc_altivec_vcmpnew_p:
  9087. case Intrinsic::ppc_altivec_vcmpnezb_p:
  9088. case Intrinsic::ppc_altivec_vcmpnezh_p:
  9089. case Intrinsic::ppc_altivec_vcmpnezw_p:
  9090. if (Subtarget.hasP9Altivec()) {
  9091. switch (IntrinsicID) {
  9092. default:
  9093. llvm_unreachable("Unknown comparison intrinsic.");
  9094. case Intrinsic::ppc_altivec_vcmpneb_p:
  9095. CompareOpc = 7;
  9096. break;
  9097. case Intrinsic::ppc_altivec_vcmpneh_p:
  9098. CompareOpc = 71;
  9099. break;
  9100. case Intrinsic::ppc_altivec_vcmpnew_p:
  9101. CompareOpc = 135;
  9102. break;
  9103. case Intrinsic::ppc_altivec_vcmpnezb_p:
  9104. CompareOpc = 263;
  9105. break;
  9106. case Intrinsic::ppc_altivec_vcmpnezh_p:
  9107. CompareOpc = 327;
  9108. break;
  9109. case Intrinsic::ppc_altivec_vcmpnezw_p:
  9110. CompareOpc = 391;
  9111. break;
  9112. }
  9113. isDot = true;
  9114. } else
  9115. return false;
  9116. break;
  9117. case Intrinsic::ppc_altivec_vcmpgefp_p:
  9118. CompareOpc = 454;
  9119. isDot = true;
  9120. break;
  9121. case Intrinsic::ppc_altivec_vcmpgtfp_p:
  9122. CompareOpc = 710;
  9123. isDot = true;
  9124. break;
  9125. case Intrinsic::ppc_altivec_vcmpgtsb_p:
  9126. CompareOpc = 774;
  9127. isDot = true;
  9128. break;
  9129. case Intrinsic::ppc_altivec_vcmpgtsh_p:
  9130. CompareOpc = 838;
  9131. isDot = true;
  9132. break;
  9133. case Intrinsic::ppc_altivec_vcmpgtsw_p:
  9134. CompareOpc = 902;
  9135. isDot = true;
  9136. break;
  9137. case Intrinsic::ppc_altivec_vcmpgtsd_p:
  9138. if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
  9139. CompareOpc = 967;
  9140. isDot = true;
  9141. } else
  9142. return false;
  9143. break;
  9144. case Intrinsic::ppc_altivec_vcmpgtub_p:
  9145. CompareOpc = 518;
  9146. isDot = true;
  9147. break;
  9148. case Intrinsic::ppc_altivec_vcmpgtuh_p:
  9149. CompareOpc = 582;
  9150. isDot = true;
  9151. break;
  9152. case Intrinsic::ppc_altivec_vcmpgtuw_p:
  9153. CompareOpc = 646;
  9154. isDot = true;
  9155. break;
  9156. case Intrinsic::ppc_altivec_vcmpgtud_p:
  9157. if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
  9158. CompareOpc = 711;
  9159. isDot = true;
  9160. } else
  9161. return false;
  9162. break;
  9163. case Intrinsic::ppc_altivec_vcmpequq:
  9164. case Intrinsic::ppc_altivec_vcmpgtsq:
  9165. case Intrinsic::ppc_altivec_vcmpgtuq:
  9166. if (!Subtarget.isISA3_1())
  9167. return false;
  9168. switch (IntrinsicID) {
  9169. default:
  9170. llvm_unreachable("Unknown comparison intrinsic.");
  9171. case Intrinsic::ppc_altivec_vcmpequq:
  9172. CompareOpc = 455;
  9173. break;
  9174. case Intrinsic::ppc_altivec_vcmpgtsq:
  9175. CompareOpc = 903;
  9176. break;
  9177. case Intrinsic::ppc_altivec_vcmpgtuq:
  9178. CompareOpc = 647;
  9179. break;
  9180. }
  9181. break;
  9182. // VSX predicate comparisons use the same infrastructure
  9183. case Intrinsic::ppc_vsx_xvcmpeqdp_p:
  9184. case Intrinsic::ppc_vsx_xvcmpgedp_p:
  9185. case Intrinsic::ppc_vsx_xvcmpgtdp_p:
  9186. case Intrinsic::ppc_vsx_xvcmpeqsp_p:
  9187. case Intrinsic::ppc_vsx_xvcmpgesp_p:
  9188. case Intrinsic::ppc_vsx_xvcmpgtsp_p:
  9189. if (Subtarget.hasVSX()) {
  9190. switch (IntrinsicID) {
  9191. case Intrinsic::ppc_vsx_xvcmpeqdp_p:
  9192. CompareOpc = 99;
  9193. break;
  9194. case Intrinsic::ppc_vsx_xvcmpgedp_p:
  9195. CompareOpc = 115;
  9196. break;
  9197. case Intrinsic::ppc_vsx_xvcmpgtdp_p:
  9198. CompareOpc = 107;
  9199. break;
  9200. case Intrinsic::ppc_vsx_xvcmpeqsp_p:
  9201. CompareOpc = 67;
  9202. break;
  9203. case Intrinsic::ppc_vsx_xvcmpgesp_p:
  9204. CompareOpc = 83;
  9205. break;
  9206. case Intrinsic::ppc_vsx_xvcmpgtsp_p:
  9207. CompareOpc = 75;
  9208. break;
  9209. }
  9210. isDot = true;
  9211. } else
  9212. return false;
  9213. break;
  9214. // Normal Comparisons.
  9215. case Intrinsic::ppc_altivec_vcmpbfp:
  9216. CompareOpc = 966;
  9217. break;
  9218. case Intrinsic::ppc_altivec_vcmpeqfp:
  9219. CompareOpc = 198;
  9220. break;
  9221. case Intrinsic::ppc_altivec_vcmpequb:
  9222. CompareOpc = 6;
  9223. break;
  9224. case Intrinsic::ppc_altivec_vcmpequh:
  9225. CompareOpc = 70;
  9226. break;
  9227. case Intrinsic::ppc_altivec_vcmpequw:
  9228. CompareOpc = 134;
  9229. break;
  9230. case Intrinsic::ppc_altivec_vcmpequd:
  9231. if (Subtarget.hasP8Altivec())
  9232. CompareOpc = 199;
  9233. else
  9234. return false;
  9235. break;
  9236. case Intrinsic::ppc_altivec_vcmpneb:
  9237. case Intrinsic::ppc_altivec_vcmpneh:
  9238. case Intrinsic::ppc_altivec_vcmpnew:
  9239. case Intrinsic::ppc_altivec_vcmpnezb:
  9240. case Intrinsic::ppc_altivec_vcmpnezh:
  9241. case Intrinsic::ppc_altivec_vcmpnezw:
  9242. if (Subtarget.hasP9Altivec())
  9243. switch (IntrinsicID) {
  9244. default:
  9245. llvm_unreachable("Unknown comparison intrinsic.");
  9246. case Intrinsic::ppc_altivec_vcmpneb:
  9247. CompareOpc = 7;
  9248. break;
  9249. case Intrinsic::ppc_altivec_vcmpneh:
  9250. CompareOpc = 71;
  9251. break;
  9252. case Intrinsic::ppc_altivec_vcmpnew:
  9253. CompareOpc = 135;
  9254. break;
  9255. case Intrinsic::ppc_altivec_vcmpnezb:
  9256. CompareOpc = 263;
  9257. break;
  9258. case Intrinsic::ppc_altivec_vcmpnezh:
  9259. CompareOpc = 327;
  9260. break;
  9261. case Intrinsic::ppc_altivec_vcmpnezw:
  9262. CompareOpc = 391;
  9263. break;
  9264. }
  9265. else
  9266. return false;
  9267. break;
  9268. case Intrinsic::ppc_altivec_vcmpgefp:
  9269. CompareOpc = 454;
  9270. break;
  9271. case Intrinsic::ppc_altivec_vcmpgtfp:
  9272. CompareOpc = 710;
  9273. break;
  9274. case Intrinsic::ppc_altivec_vcmpgtsb:
  9275. CompareOpc = 774;
  9276. break;
  9277. case Intrinsic::ppc_altivec_vcmpgtsh:
  9278. CompareOpc = 838;
  9279. break;
  9280. case Intrinsic::ppc_altivec_vcmpgtsw:
  9281. CompareOpc = 902;
  9282. break;
  9283. case Intrinsic::ppc_altivec_vcmpgtsd:
  9284. if (Subtarget.hasP8Altivec())
  9285. CompareOpc = 967;
  9286. else
  9287. return false;
  9288. break;
  9289. case Intrinsic::ppc_altivec_vcmpgtub:
  9290. CompareOpc = 518;
  9291. break;
  9292. case Intrinsic::ppc_altivec_vcmpgtuh:
  9293. CompareOpc = 582;
  9294. break;
  9295. case Intrinsic::ppc_altivec_vcmpgtuw:
  9296. CompareOpc = 646;
  9297. break;
  9298. case Intrinsic::ppc_altivec_vcmpgtud:
  9299. if (Subtarget.hasP8Altivec())
  9300. CompareOpc = 711;
  9301. else
  9302. return false;
  9303. break;
  9304. case Intrinsic::ppc_altivec_vcmpequq_p:
  9305. case Intrinsic::ppc_altivec_vcmpgtsq_p:
  9306. case Intrinsic::ppc_altivec_vcmpgtuq_p:
  9307. if (!Subtarget.isISA3_1())
  9308. return false;
  9309. switch (IntrinsicID) {
  9310. default:
  9311. llvm_unreachable("Unknown comparison intrinsic.");
  9312. case Intrinsic::ppc_altivec_vcmpequq_p:
  9313. CompareOpc = 455;
  9314. break;
  9315. case Intrinsic::ppc_altivec_vcmpgtsq_p:
  9316. CompareOpc = 903;
  9317. break;
  9318. case Intrinsic::ppc_altivec_vcmpgtuq_p:
  9319. CompareOpc = 647;
  9320. break;
  9321. }
  9322. isDot = true;
  9323. break;
  9324. }
  9325. return true;
  9326. }
  9327. /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
  9328. /// lower, do it, otherwise return null.
  9329. SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
  9330. SelectionDAG &DAG) const {
  9331. unsigned IntrinsicID =
  9332. cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
  9333. SDLoc dl(Op);
  9334. switch (IntrinsicID) {
  9335. case Intrinsic::thread_pointer:
  9336. // Reads the thread pointer register, used for __builtin_thread_pointer.
  9337. if (Subtarget.isPPC64())
  9338. return DAG.getRegister(PPC::X13, MVT::i64);
  9339. return DAG.getRegister(PPC::R2, MVT::i32);
  9340. case Intrinsic::ppc_mma_disassemble_acc: {
  9341. if (Subtarget.isISAFuture()) {
  9342. EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1};
  9343. SDValue WideVec = SDValue(DAG.getMachineNode(PPC::DMXXEXTFDMR512, dl,
  9344. ArrayRef(ReturnTypes, 2),
  9345. Op.getOperand(1)),
  9346. 0);
  9347. SmallVector<SDValue, 4> RetOps;
  9348. SDValue Value = SDValue(WideVec.getNode(), 0);
  9349. SDValue Value2 = SDValue(WideVec.getNode(), 1);
  9350. SDValue Extract;
  9351. Extract = DAG.getNode(
  9352. PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
  9353. Subtarget.isLittleEndian() ? Value2 : Value,
  9354. DAG.getConstant(Subtarget.isLittleEndian() ? 1 : 0,
  9355. dl, getPointerTy(DAG.getDataLayout())));
  9356. RetOps.push_back(Extract);
  9357. Extract = DAG.getNode(
  9358. PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
  9359. Subtarget.isLittleEndian() ? Value2 : Value,
  9360. DAG.getConstant(Subtarget.isLittleEndian() ? 0 : 1,
  9361. dl, getPointerTy(DAG.getDataLayout())));
  9362. RetOps.push_back(Extract);
  9363. Extract = DAG.getNode(
  9364. PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
  9365. Subtarget.isLittleEndian() ? Value : Value2,
  9366. DAG.getConstant(Subtarget.isLittleEndian() ? 1 : 0,
  9367. dl, getPointerTy(DAG.getDataLayout())));
  9368. RetOps.push_back(Extract);
  9369. Extract = DAG.getNode(
  9370. PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
  9371. Subtarget.isLittleEndian() ? Value : Value2,
  9372. DAG.getConstant(Subtarget.isLittleEndian() ? 0 : 1,
  9373. dl, getPointerTy(DAG.getDataLayout())));
  9374. RetOps.push_back(Extract);
  9375. return DAG.getMergeValues(RetOps, dl);
  9376. }
  9377. LLVM_FALLTHROUGH;
  9378. }
  9379. case Intrinsic::ppc_vsx_disassemble_pair: {
  9380. int NumVecs = 2;
  9381. SDValue WideVec = Op.getOperand(1);
  9382. if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
  9383. NumVecs = 4;
  9384. WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
  9385. }
  9386. SmallVector<SDValue, 4> RetOps;
  9387. for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
  9388. SDValue Extract = DAG.getNode(
  9389. PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
  9390. DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
  9391. : VecNo,
  9392. dl, getPointerTy(DAG.getDataLayout())));
  9393. RetOps.push_back(Extract);
  9394. }
  9395. return DAG.getMergeValues(RetOps, dl);
  9396. }
  9397. case Intrinsic::ppc_unpack_longdouble: {
  9398. auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
  9399. assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
  9400. "Argument of long double unpack must be 0 or 1!");
  9401. return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1),
  9402. DAG.getConstant(!!(Idx->getSExtValue()), dl,
  9403. Idx->getValueType(0)));
  9404. }
  9405. case Intrinsic::ppc_compare_exp_lt:
  9406. case Intrinsic::ppc_compare_exp_gt:
  9407. case Intrinsic::ppc_compare_exp_eq:
  9408. case Intrinsic::ppc_compare_exp_uo: {
  9409. unsigned Pred;
  9410. switch (IntrinsicID) {
  9411. case Intrinsic::ppc_compare_exp_lt:
  9412. Pred = PPC::PRED_LT;
  9413. break;
  9414. case Intrinsic::ppc_compare_exp_gt:
  9415. Pred = PPC::PRED_GT;
  9416. break;
  9417. case Intrinsic::ppc_compare_exp_eq:
  9418. Pred = PPC::PRED_EQ;
  9419. break;
  9420. case Intrinsic::ppc_compare_exp_uo:
  9421. Pred = PPC::PRED_UN;
  9422. break;
  9423. }
  9424. return SDValue(
  9425. DAG.getMachineNode(
  9426. PPC::SELECT_CC_I4, dl, MVT::i32,
  9427. {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32,
  9428. Op.getOperand(1), Op.getOperand(2)),
  9429. 0),
  9430. DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
  9431. DAG.getTargetConstant(Pred, dl, MVT::i32)}),
  9432. 0);
  9433. }
  9434. case Intrinsic::ppc_test_data_class: {
  9435. EVT OpVT = Op.getOperand(1).getValueType();
  9436. unsigned CmprOpc = OpVT == MVT::f128 ? PPC::XSTSTDCQP
  9437. : (OpVT == MVT::f64 ? PPC::XSTSTDCDP
  9438. : PPC::XSTSTDCSP);
  9439. return SDValue(
  9440. DAG.getMachineNode(
  9441. PPC::SELECT_CC_I4, dl, MVT::i32,
  9442. {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2),
  9443. Op.getOperand(1)),
  9444. 0),
  9445. DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
  9446. DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}),
  9447. 0);
  9448. }
  9449. case Intrinsic::ppc_fnmsub: {
  9450. EVT VT = Op.getOperand(1).getValueType();
  9451. if (!Subtarget.hasVSX() || (!Subtarget.hasFloat128() && VT == MVT::f128))
  9452. return DAG.getNode(
  9453. ISD::FNEG, dl, VT,
  9454. DAG.getNode(ISD::FMA, dl, VT, Op.getOperand(1), Op.getOperand(2),
  9455. DAG.getNode(ISD::FNEG, dl, VT, Op.getOperand(3))));
  9456. return DAG.getNode(PPCISD::FNMSUB, dl, VT, Op.getOperand(1),
  9457. Op.getOperand(2), Op.getOperand(3));
  9458. }
  9459. case Intrinsic::ppc_convert_f128_to_ppcf128:
  9460. case Intrinsic::ppc_convert_ppcf128_to_f128: {
  9461. RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128
  9462. ? RTLIB::CONVERT_PPCF128_F128
  9463. : RTLIB::CONVERT_F128_PPCF128;
  9464. MakeLibCallOptions CallOptions;
  9465. std::pair<SDValue, SDValue> Result =
  9466. makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions,
  9467. dl, SDValue());
  9468. return Result.first;
  9469. }
  9470. case Intrinsic::ppc_maxfe:
  9471. case Intrinsic::ppc_maxfl:
  9472. case Intrinsic::ppc_maxfs:
  9473. case Intrinsic::ppc_minfe:
  9474. case Intrinsic::ppc_minfl:
  9475. case Intrinsic::ppc_minfs: {
  9476. EVT VT = Op.getValueType();
  9477. assert(
  9478. all_of(Op->ops().drop_front(4),
  9479. [VT](const SDUse &Use) { return Use.getValueType() == VT; }) &&
  9480. "ppc_[max|min]f[e|l|s] must have uniform type arguments");
  9481. (void)VT;
  9482. ISD::CondCode CC = ISD::SETGT;
  9483. if (IntrinsicID == Intrinsic::ppc_minfe ||
  9484. IntrinsicID == Intrinsic::ppc_minfl ||
  9485. IntrinsicID == Intrinsic::ppc_minfs)
  9486. CC = ISD::SETLT;
  9487. unsigned I = Op.getNumOperands() - 2, Cnt = I;
  9488. SDValue Res = Op.getOperand(I);
  9489. for (--I; Cnt != 0; --Cnt, I = (--I == 0 ? (Op.getNumOperands() - 1) : I)) {
  9490. Res =
  9491. DAG.getSelectCC(dl, Res, Op.getOperand(I), Res, Op.getOperand(I), CC);
  9492. }
  9493. return Res;
  9494. }
  9495. }
  9496. // If this is a lowered altivec predicate compare, CompareOpc is set to the
  9497. // opcode number of the comparison.
  9498. int CompareOpc;
  9499. bool isDot;
  9500. if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
  9501. return SDValue(); // Don't custom lower most intrinsics.
  9502. // If this is a non-dot comparison, make the VCMP node and we are done.
  9503. if (!isDot) {
  9504. SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
  9505. Op.getOperand(1), Op.getOperand(2),
  9506. DAG.getConstant(CompareOpc, dl, MVT::i32));
  9507. return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
  9508. }
  9509. // Create the PPCISD altivec 'dot' comparison node.
  9510. SDValue Ops[] = {
  9511. Op.getOperand(2), // LHS
  9512. Op.getOperand(3), // RHS
  9513. DAG.getConstant(CompareOpc, dl, MVT::i32)
  9514. };
  9515. EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
  9516. SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
  9517. // Now that we have the comparison, emit a copy from the CR to a GPR.
  9518. // This is flagged to the above dot comparison.
  9519. SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
  9520. DAG.getRegister(PPC::CR6, MVT::i32),
  9521. CompNode.getValue(1));
  9522. // Unpack the result based on how the target uses it.
  9523. unsigned BitNo; // Bit # of CR6.
  9524. bool InvertBit; // Invert result?
  9525. switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
  9526. default: // Can't happen, don't crash on invalid number though.
  9527. case 0: // Return the value of the EQ bit of CR6.
  9528. BitNo = 0; InvertBit = false;
  9529. break;
  9530. case 1: // Return the inverted value of the EQ bit of CR6.
  9531. BitNo = 0; InvertBit = true;
  9532. break;
  9533. case 2: // Return the value of the LT bit of CR6.
  9534. BitNo = 2; InvertBit = false;
  9535. break;
  9536. case 3: // Return the inverted value of the LT bit of CR6.
  9537. BitNo = 2; InvertBit = true;
  9538. break;
  9539. }
  9540. // Shift the bit into the low position.
  9541. Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
  9542. DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
  9543. // Isolate the bit.
  9544. Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
  9545. DAG.getConstant(1, dl, MVT::i32));
  9546. // If we are supposed to, toggle the bit.
  9547. if (InvertBit)
  9548. Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
  9549. DAG.getConstant(1, dl, MVT::i32));
  9550. return Flags;
  9551. }
  9552. SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
  9553. SelectionDAG &DAG) const {
  9554. // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
  9555. // the beginning of the argument list.
  9556. int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
  9557. SDLoc DL(Op);
  9558. switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
  9559. case Intrinsic::ppc_cfence: {
  9560. assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
  9561. assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
  9562. SDValue Val = Op.getOperand(ArgStart + 1);
  9563. EVT Ty = Val.getValueType();
  9564. if (Ty == MVT::i128) {
  9565. // FIXME: Testing one of two paired registers is sufficient to guarantee
  9566. // ordering?
  9567. Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val);
  9568. }
  9569. return SDValue(
  9570. DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
  9571. DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val),
  9572. Op.getOperand(0)),
  9573. 0);
  9574. }
  9575. default:
  9576. break;
  9577. }
  9578. return SDValue();
  9579. }
  9580. // Lower scalar BSWAP64 to xxbrd.
  9581. SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
  9582. SDLoc dl(Op);
  9583. if (!Subtarget.isPPC64())
  9584. return Op;
  9585. // MTVSRDD
  9586. Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
  9587. Op.getOperand(0));
  9588. // XXBRD
  9589. Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
  9590. // MFVSRD
  9591. int VectorIndex = 0;
  9592. if (Subtarget.isLittleEndian())
  9593. VectorIndex = 1;
  9594. Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
  9595. DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
  9596. return Op;
  9597. }
  9598. // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
  9599. // compared to a value that is atomically loaded (atomic loads zero-extend).
  9600. SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
  9601. SelectionDAG &DAG) const {
  9602. assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
  9603. "Expecting an atomic compare-and-swap here.");
  9604. SDLoc dl(Op);
  9605. auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
  9606. EVT MemVT = AtomicNode->getMemoryVT();
  9607. if (MemVT.getSizeInBits() >= 32)
  9608. return Op;
  9609. SDValue CmpOp = Op.getOperand(2);
  9610. // If this is already correctly zero-extended, leave it alone.
  9611. auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
  9612. if (DAG.MaskedValueIsZero(CmpOp, HighBits))
  9613. return Op;
  9614. // Clear the high bits of the compare operand.
  9615. unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
  9616. SDValue NewCmpOp =
  9617. DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
  9618. DAG.getConstant(MaskVal, dl, MVT::i32));
  9619. // Replace the existing compare operand with the properly zero-extended one.
  9620. SmallVector<SDValue, 4> Ops;
  9621. for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
  9622. Ops.push_back(AtomicNode->getOperand(i));
  9623. Ops[2] = NewCmpOp;
  9624. MachineMemOperand *MMO = AtomicNode->getMemOperand();
  9625. SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
  9626. auto NodeTy =
  9627. (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
  9628. return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
  9629. }
  9630. SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op,
  9631. SelectionDAG &DAG) const {
  9632. AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode());
  9633. EVT MemVT = N->getMemoryVT();
  9634. assert(MemVT.getSimpleVT() == MVT::i128 &&
  9635. "Expect quadword atomic operations");
  9636. SDLoc dl(N);
  9637. unsigned Opc = N->getOpcode();
  9638. switch (Opc) {
  9639. case ISD::ATOMIC_LOAD: {
  9640. // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be
  9641. // lowered to ppc instructions by pattern matching instruction selector.
  9642. SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
  9643. SmallVector<SDValue, 4> Ops{
  9644. N->getOperand(0),
  9645. DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)};
  9646. for (int I = 1, E = N->getNumOperands(); I < E; ++I)
  9647. Ops.push_back(N->getOperand(I));
  9648. SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys,
  9649. Ops, MemVT, N->getMemOperand());
  9650. SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal);
  9651. SDValue ValHi =
  9652. DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1));
  9653. ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi,
  9654. DAG.getConstant(64, dl, MVT::i32));
  9655. SDValue Val =
  9656. DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi});
  9657. return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other},
  9658. {Val, LoadedVal.getValue(2)});
  9659. }
  9660. case ISD::ATOMIC_STORE: {
  9661. // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be
  9662. // lowered to ppc instructions by pattern matching instruction selector.
  9663. SDVTList Tys = DAG.getVTList(MVT::Other);
  9664. SmallVector<SDValue, 4> Ops{
  9665. N->getOperand(0),
  9666. DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)};
  9667. SDValue Val = N->getOperand(2);
  9668. SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val);
  9669. SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val,
  9670. DAG.getConstant(64, dl, MVT::i32));
  9671. ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi);
  9672. Ops.push_back(ValLo);
  9673. Ops.push_back(ValHi);
  9674. Ops.push_back(N->getOperand(1));
  9675. return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT,
  9676. N->getMemOperand());
  9677. }
  9678. default:
  9679. llvm_unreachable("Unexpected atomic opcode");
  9680. }
  9681. }
  9682. SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
  9683. SelectionDAG &DAG) const {
  9684. SDLoc dl(Op);
  9685. // Create a stack slot that is 16-byte aligned.
  9686. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  9687. int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
  9688. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  9689. SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
  9690. // Store the input value into Value#0 of the stack slot.
  9691. SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
  9692. MachinePointerInfo());
  9693. // Load it out.
  9694. return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
  9695. }
  9696. SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
  9697. SelectionDAG &DAG) const {
  9698. assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
  9699. "Should only be called for ISD::INSERT_VECTOR_ELT");
  9700. ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
  9701. EVT VT = Op.getValueType();
  9702. SDLoc dl(Op);
  9703. SDValue V1 = Op.getOperand(0);
  9704. SDValue V2 = Op.getOperand(1);
  9705. if (VT == MVT::v2f64 && C)
  9706. return Op;
  9707. if (Subtarget.hasP9Vector()) {
  9708. // A f32 load feeding into a v4f32 insert_vector_elt is handled in this way
  9709. // because on P10, it allows this specific insert_vector_elt load pattern to
  9710. // utilize the refactored load and store infrastructure in order to exploit
  9711. // prefixed loads.
  9712. // On targets with inexpensive direct moves (Power9 and up), a
  9713. // (insert_vector_elt v4f32:$vec, (f32 load)) is always better as an integer
  9714. // load since a single precision load will involve conversion to double
  9715. // precision on the load followed by another conversion to single precision.
  9716. if ((VT == MVT::v4f32) && (V2.getValueType() == MVT::f32) &&
  9717. (isa<LoadSDNode>(V2))) {
  9718. SDValue BitcastVector = DAG.getBitcast(MVT::v4i32, V1);
  9719. SDValue BitcastLoad = DAG.getBitcast(MVT::i32, V2);
  9720. SDValue InsVecElt =
  9721. DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4i32, BitcastVector,
  9722. BitcastLoad, Op.getOperand(2));
  9723. return DAG.getBitcast(MVT::v4f32, InsVecElt);
  9724. }
  9725. }
  9726. if (Subtarget.isISA3_1()) {
  9727. if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64())
  9728. return SDValue();
  9729. // On P10, we have legal lowering for constant and variable indices for
  9730. // all vectors.
  9731. if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
  9732. VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
  9733. return Op;
  9734. }
  9735. // Before P10, we have legal lowering for constant indices but not for
  9736. // variable ones.
  9737. if (!C)
  9738. return SDValue();
  9739. // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
  9740. if (VT == MVT::v8i16 || VT == MVT::v16i8) {
  9741. SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
  9742. unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
  9743. unsigned InsertAtElement = C->getZExtValue();
  9744. unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
  9745. if (Subtarget.isLittleEndian()) {
  9746. InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
  9747. }
  9748. return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
  9749. DAG.getConstant(InsertAtByte, dl, MVT::i32));
  9750. }
  9751. return Op;
  9752. }
  9753. SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
  9754. SelectionDAG &DAG) const {
  9755. SDLoc dl(Op);
  9756. LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
  9757. SDValue LoadChain = LN->getChain();
  9758. SDValue BasePtr = LN->getBasePtr();
  9759. EVT VT = Op.getValueType();
  9760. if (VT != MVT::v256i1 && VT != MVT::v512i1)
  9761. return Op;
  9762. // Type v256i1 is used for pairs and v512i1 is used for accumulators.
  9763. // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
  9764. // 2 or 4 vsx registers.
  9765. assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
  9766. "Type unsupported without MMA");
  9767. assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
  9768. "Type unsupported without paired vector support");
  9769. Align Alignment = LN->getAlign();
  9770. SmallVector<SDValue, 4> Loads;
  9771. SmallVector<SDValue, 4> LoadChains;
  9772. unsigned NumVecs = VT.getSizeInBits() / 128;
  9773. for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
  9774. SDValue Load =
  9775. DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
  9776. LN->getPointerInfo().getWithOffset(Idx * 16),
  9777. commonAlignment(Alignment, Idx * 16),
  9778. LN->getMemOperand()->getFlags(), LN->getAAInfo());
  9779. BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
  9780. DAG.getConstant(16, dl, BasePtr.getValueType()));
  9781. Loads.push_back(Load);
  9782. LoadChains.push_back(Load.getValue(1));
  9783. }
  9784. if (Subtarget.isLittleEndian()) {
  9785. std::reverse(Loads.begin(), Loads.end());
  9786. std::reverse(LoadChains.begin(), LoadChains.end());
  9787. }
  9788. SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
  9789. SDValue Value =
  9790. DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
  9791. dl, VT, Loads);
  9792. SDValue RetOps[] = {Value, TF};
  9793. return DAG.getMergeValues(RetOps, dl);
  9794. }
  9795. SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
  9796. SelectionDAG &DAG) const {
  9797. SDLoc dl(Op);
  9798. StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
  9799. SDValue StoreChain = SN->getChain();
  9800. SDValue BasePtr = SN->getBasePtr();
  9801. SDValue Value = SN->getValue();
  9802. SDValue Value2 = SN->getValue();
  9803. EVT StoreVT = Value.getValueType();
  9804. if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
  9805. return Op;
  9806. // Type v256i1 is used for pairs and v512i1 is used for accumulators.
  9807. // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
  9808. // underlying registers individually.
  9809. assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
  9810. "Type unsupported without MMA");
  9811. assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
  9812. "Type unsupported without paired vector support");
  9813. Align Alignment = SN->getAlign();
  9814. SmallVector<SDValue, 4> Stores;
  9815. unsigned NumVecs = 2;
  9816. if (StoreVT == MVT::v512i1) {
  9817. if (Subtarget.isISAFuture()) {
  9818. EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1};
  9819. MachineSDNode *ExtNode = DAG.getMachineNode(
  9820. PPC::DMXXEXTFDMR512, dl, ArrayRef(ReturnTypes, 2), Op.getOperand(1));
  9821. Value = SDValue(ExtNode, 0);
  9822. Value2 = SDValue(ExtNode, 1);
  9823. } else
  9824. Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
  9825. NumVecs = 4;
  9826. }
  9827. for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
  9828. unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
  9829. SDValue Elt;
  9830. if (Subtarget.isISAFuture()) {
  9831. VecNum = Subtarget.isLittleEndian() ? 1 - (Idx % 2) : (Idx % 2);
  9832. Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
  9833. Idx > 1 ? Value2 : Value,
  9834. DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
  9835. } else
  9836. Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
  9837. DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
  9838. SDValue Store =
  9839. DAG.getStore(StoreChain, dl, Elt, BasePtr,
  9840. SN->getPointerInfo().getWithOffset(Idx * 16),
  9841. commonAlignment(Alignment, Idx * 16),
  9842. SN->getMemOperand()->getFlags(), SN->getAAInfo());
  9843. BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
  9844. DAG.getConstant(16, dl, BasePtr.getValueType()));
  9845. Stores.push_back(Store);
  9846. }
  9847. SDValue TF = DAG.getTokenFactor(dl, Stores);
  9848. return TF;
  9849. }
  9850. SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
  9851. SDLoc dl(Op);
  9852. if (Op.getValueType() == MVT::v4i32) {
  9853. SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
  9854. SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
  9855. // +16 as shift amt.
  9856. SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
  9857. SDValue RHSSwap = // = vrlw RHS, 16
  9858. BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
  9859. // Shrinkify inputs to v8i16.
  9860. LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
  9861. RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
  9862. RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
  9863. // Low parts multiplied together, generating 32-bit results (we ignore the
  9864. // top parts).
  9865. SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
  9866. LHS, RHS, DAG, dl, MVT::v4i32);
  9867. SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
  9868. LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
  9869. // Shift the high parts up 16 bits.
  9870. HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
  9871. Neg16, DAG, dl);
  9872. return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
  9873. } else if (Op.getValueType() == MVT::v16i8) {
  9874. SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
  9875. bool isLittleEndian = Subtarget.isLittleEndian();
  9876. // Multiply the even 8-bit parts, producing 16-bit sums.
  9877. SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
  9878. LHS, RHS, DAG, dl, MVT::v8i16);
  9879. EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
  9880. // Multiply the odd 8-bit parts, producing 16-bit sums.
  9881. SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
  9882. LHS, RHS, DAG, dl, MVT::v8i16);
  9883. OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
  9884. // Merge the results together. Because vmuleub and vmuloub are
  9885. // instructions with a big-endian bias, we must reverse the
  9886. // element numbering and reverse the meaning of "odd" and "even"
  9887. // when generating little endian code.
  9888. int Ops[16];
  9889. for (unsigned i = 0; i != 8; ++i) {
  9890. if (isLittleEndian) {
  9891. Ops[i*2 ] = 2*i;
  9892. Ops[i*2+1] = 2*i+16;
  9893. } else {
  9894. Ops[i*2 ] = 2*i+1;
  9895. Ops[i*2+1] = 2*i+1+16;
  9896. }
  9897. }
  9898. if (isLittleEndian)
  9899. return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
  9900. else
  9901. return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
  9902. } else {
  9903. llvm_unreachable("Unknown mul to lower!");
  9904. }
  9905. }
  9906. SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
  9907. bool IsStrict = Op->isStrictFPOpcode();
  9908. if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
  9909. !Subtarget.hasP9Vector())
  9910. return SDValue();
  9911. return Op;
  9912. }
  9913. // Custom lowering for fpext vf32 to v2f64
  9914. SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
  9915. assert(Op.getOpcode() == ISD::FP_EXTEND &&
  9916. "Should only be called for ISD::FP_EXTEND");
  9917. // FIXME: handle extends from half precision float vectors on P9.
  9918. // We only want to custom lower an extend from v2f32 to v2f64.
  9919. if (Op.getValueType() != MVT::v2f64 ||
  9920. Op.getOperand(0).getValueType() != MVT::v2f32)
  9921. return SDValue();
  9922. SDLoc dl(Op);
  9923. SDValue Op0 = Op.getOperand(0);
  9924. switch (Op0.getOpcode()) {
  9925. default:
  9926. return SDValue();
  9927. case ISD::EXTRACT_SUBVECTOR: {
  9928. assert(Op0.getNumOperands() == 2 &&
  9929. isa<ConstantSDNode>(Op0->getOperand(1)) &&
  9930. "Node should have 2 operands with second one being a constant!");
  9931. if (Op0.getOperand(0).getValueType() != MVT::v4f32)
  9932. return SDValue();
  9933. // Custom lower is only done for high or low doubleword.
  9934. int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
  9935. if (Idx % 2 != 0)
  9936. return SDValue();
  9937. // Since input is v4f32, at this point Idx is either 0 or 2.
  9938. // Shift to get the doubleword position we want.
  9939. int DWord = Idx >> 1;
  9940. // High and low word positions are different on little endian.
  9941. if (Subtarget.isLittleEndian())
  9942. DWord ^= 0x1;
  9943. return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
  9944. Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
  9945. }
  9946. case ISD::FADD:
  9947. case ISD::FMUL:
  9948. case ISD::FSUB: {
  9949. SDValue NewLoad[2];
  9950. for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
  9951. // Ensure both input are loads.
  9952. SDValue LdOp = Op0.getOperand(i);
  9953. if (LdOp.getOpcode() != ISD::LOAD)
  9954. return SDValue();
  9955. // Generate new load node.
  9956. LoadSDNode *LD = cast<LoadSDNode>(LdOp);
  9957. SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
  9958. NewLoad[i] = DAG.getMemIntrinsicNode(
  9959. PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
  9960. LD->getMemoryVT(), LD->getMemOperand());
  9961. }
  9962. SDValue NewOp =
  9963. DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
  9964. NewLoad[1], Op0.getNode()->getFlags());
  9965. return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
  9966. DAG.getConstant(0, dl, MVT::i32));
  9967. }
  9968. case ISD::LOAD: {
  9969. LoadSDNode *LD = cast<LoadSDNode>(Op0);
  9970. SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
  9971. SDValue NewLd = DAG.getMemIntrinsicNode(
  9972. PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
  9973. LD->getMemoryVT(), LD->getMemOperand());
  9974. return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
  9975. DAG.getConstant(0, dl, MVT::i32));
  9976. }
  9977. }
  9978. llvm_unreachable("ERROR:Should return for all cases within swtich.");
  9979. }
  9980. /// LowerOperation - Provide custom lowering hooks for some operations.
  9981. ///
  9982. SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  9983. switch (Op.getOpcode()) {
  9984. default: llvm_unreachable("Wasn't expecting to be able to lower this!");
  9985. case ISD::FPOW: return lowerPow(Op, DAG);
  9986. case ISD::FSIN: return lowerSin(Op, DAG);
  9987. case ISD::FCOS: return lowerCos(Op, DAG);
  9988. case ISD::FLOG: return lowerLog(Op, DAG);
  9989. case ISD::FLOG10: return lowerLog10(Op, DAG);
  9990. case ISD::FEXP: return lowerExp(Op, DAG);
  9991. case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
  9992. case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
  9993. case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
  9994. case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
  9995. case ISD::JumpTable: return LowerJumpTable(Op, DAG);
  9996. case ISD::STRICT_FSETCC:
  9997. case ISD::STRICT_FSETCCS:
  9998. case ISD::SETCC: return LowerSETCC(Op, DAG);
  9999. case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
  10000. case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
  10001. case ISD::INLINEASM:
  10002. case ISD::INLINEASM_BR: return LowerINLINEASM(Op, DAG);
  10003. // Variable argument lowering.
  10004. case ISD::VASTART: return LowerVASTART(Op, DAG);
  10005. case ISD::VAARG: return LowerVAARG(Op, DAG);
  10006. case ISD::VACOPY: return LowerVACOPY(Op, DAG);
  10007. case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG);
  10008. case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
  10009. case ISD::GET_DYNAMIC_AREA_OFFSET:
  10010. return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
  10011. // Exception handling lowering.
  10012. case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG);
  10013. case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
  10014. case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
  10015. case ISD::LOAD: return LowerLOAD(Op, DAG);
  10016. case ISD::STORE: return LowerSTORE(Op, DAG);
  10017. case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
  10018. case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
  10019. case ISD::STRICT_FP_TO_UINT:
  10020. case ISD::STRICT_FP_TO_SINT:
  10021. case ISD::FP_TO_UINT:
  10022. case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
  10023. case ISD::STRICT_UINT_TO_FP:
  10024. case ISD::STRICT_SINT_TO_FP:
  10025. case ISD::UINT_TO_FP:
  10026. case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
  10027. case ISD::GET_ROUNDING: return LowerGET_ROUNDING(Op, DAG);
  10028. // Lower 64-bit shifts.
  10029. case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
  10030. case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
  10031. case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
  10032. case ISD::FSHL: return LowerFunnelShift(Op, DAG);
  10033. case ISD::FSHR: return LowerFunnelShift(Op, DAG);
  10034. // Vector-related lowering.
  10035. case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
  10036. case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
  10037. case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
  10038. case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
  10039. case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
  10040. case ISD::MUL: return LowerMUL(Op, DAG);
  10041. case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
  10042. case ISD::STRICT_FP_ROUND:
  10043. case ISD::FP_ROUND:
  10044. return LowerFP_ROUND(Op, DAG);
  10045. case ISD::ROTL: return LowerROTL(Op, DAG);
  10046. // For counter-based loop handling.
  10047. case ISD::INTRINSIC_W_CHAIN: return SDValue();
  10048. case ISD::BITCAST: return LowerBITCAST(Op, DAG);
  10049. // Frame & Return address.
  10050. case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
  10051. case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
  10052. case ISD::INTRINSIC_VOID:
  10053. return LowerINTRINSIC_VOID(Op, DAG);
  10054. case ISD::BSWAP:
  10055. return LowerBSWAP(Op, DAG);
  10056. case ISD::ATOMIC_CMP_SWAP:
  10057. return LowerATOMIC_CMP_SWAP(Op, DAG);
  10058. case ISD::ATOMIC_STORE:
  10059. return LowerATOMIC_LOAD_STORE(Op, DAG);
  10060. }
  10061. }
  10062. void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
  10063. SmallVectorImpl<SDValue>&Results,
  10064. SelectionDAG &DAG) const {
  10065. SDLoc dl(N);
  10066. switch (N->getOpcode()) {
  10067. default:
  10068. llvm_unreachable("Do not know how to custom type legalize this operation!");
  10069. case ISD::ATOMIC_LOAD: {
  10070. SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG);
  10071. Results.push_back(Res);
  10072. Results.push_back(Res.getValue(1));
  10073. break;
  10074. }
  10075. case ISD::READCYCLECOUNTER: {
  10076. SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
  10077. SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
  10078. Results.push_back(
  10079. DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
  10080. Results.push_back(RTB.getValue(2));
  10081. break;
  10082. }
  10083. case ISD::INTRINSIC_W_CHAIN: {
  10084. if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
  10085. Intrinsic::loop_decrement)
  10086. break;
  10087. assert(N->getValueType(0) == MVT::i1 &&
  10088. "Unexpected result type for CTR decrement intrinsic");
  10089. EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  10090. N->getValueType(0));
  10091. SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
  10092. SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
  10093. N->getOperand(1));
  10094. Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
  10095. Results.push_back(NewInt.getValue(1));
  10096. break;
  10097. }
  10098. case ISD::INTRINSIC_WO_CHAIN: {
  10099. switch (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()) {
  10100. case Intrinsic::ppc_pack_longdouble:
  10101. Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
  10102. N->getOperand(2), N->getOperand(1)));
  10103. break;
  10104. case Intrinsic::ppc_maxfe:
  10105. case Intrinsic::ppc_minfe:
  10106. case Intrinsic::ppc_fnmsub:
  10107. case Intrinsic::ppc_convert_f128_to_ppcf128:
  10108. Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG));
  10109. break;
  10110. }
  10111. break;
  10112. }
  10113. case ISD::VAARG: {
  10114. if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
  10115. return;
  10116. EVT VT = N->getValueType(0);
  10117. if (VT == MVT::i64) {
  10118. SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
  10119. Results.push_back(NewNode);
  10120. Results.push_back(NewNode.getValue(1));
  10121. }
  10122. return;
  10123. }
  10124. case ISD::STRICT_FP_TO_SINT:
  10125. case ISD::STRICT_FP_TO_UINT:
  10126. case ISD::FP_TO_SINT:
  10127. case ISD::FP_TO_UINT: {
  10128. // LowerFP_TO_INT() can only handle f32 and f64.
  10129. if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
  10130. MVT::ppcf128)
  10131. return;
  10132. SDValue LoweredValue = LowerFP_TO_INT(SDValue(N, 0), DAG, dl);
  10133. Results.push_back(LoweredValue);
  10134. if (N->isStrictFPOpcode())
  10135. Results.push_back(LoweredValue.getValue(1));
  10136. return;
  10137. }
  10138. case ISD::TRUNCATE: {
  10139. if (!N->getValueType(0).isVector())
  10140. return;
  10141. SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
  10142. if (Lowered)
  10143. Results.push_back(Lowered);
  10144. return;
  10145. }
  10146. case ISD::FSHL:
  10147. case ISD::FSHR:
  10148. // Don't handle funnel shifts here.
  10149. return;
  10150. case ISD::BITCAST:
  10151. // Don't handle bitcast here.
  10152. return;
  10153. case ISD::FP_EXTEND:
  10154. SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
  10155. if (Lowered)
  10156. Results.push_back(Lowered);
  10157. return;
  10158. }
  10159. }
  10160. //===----------------------------------------------------------------------===//
  10161. // Other Lowering Code
  10162. //===----------------------------------------------------------------------===//
  10163. static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) {
  10164. Module *M = Builder.GetInsertBlock()->getParent()->getParent();
  10165. Function *Func = Intrinsic::getDeclaration(M, Id);
  10166. return Builder.CreateCall(Func, {});
  10167. }
  10168. // The mappings for emitLeading/TrailingFence is taken from
  10169. // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
  10170. Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
  10171. Instruction *Inst,
  10172. AtomicOrdering Ord) const {
  10173. if (Ord == AtomicOrdering::SequentiallyConsistent)
  10174. return callIntrinsic(Builder, Intrinsic::ppc_sync);
  10175. if (isReleaseOrStronger(Ord))
  10176. return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
  10177. return nullptr;
  10178. }
  10179. Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
  10180. Instruction *Inst,
  10181. AtomicOrdering Ord) const {
  10182. if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
  10183. // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
  10184. // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
  10185. // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
  10186. if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
  10187. return Builder.CreateCall(
  10188. Intrinsic::getDeclaration(
  10189. Builder.GetInsertBlock()->getParent()->getParent(),
  10190. Intrinsic::ppc_cfence, {Inst->getType()}),
  10191. {Inst});
  10192. // FIXME: Can use isync for rmw operation.
  10193. return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
  10194. }
  10195. return nullptr;
  10196. }
  10197. MachineBasicBlock *
  10198. PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
  10199. unsigned AtomicSize,
  10200. unsigned BinOpcode,
  10201. unsigned CmpOpcode,
  10202. unsigned CmpPred) const {
  10203. // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
  10204. const TargetInstrInfo *TII = Subtarget.getInstrInfo();
  10205. auto LoadMnemonic = PPC::LDARX;
  10206. auto StoreMnemonic = PPC::STDCX;
  10207. switch (AtomicSize) {
  10208. default:
  10209. llvm_unreachable("Unexpected size of atomic entity");
  10210. case 1:
  10211. LoadMnemonic = PPC::LBARX;
  10212. StoreMnemonic = PPC::STBCX;
  10213. assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
  10214. break;
  10215. case 2:
  10216. LoadMnemonic = PPC::LHARX;
  10217. StoreMnemonic = PPC::STHCX;
  10218. assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
  10219. break;
  10220. case 4:
  10221. LoadMnemonic = PPC::LWARX;
  10222. StoreMnemonic = PPC::STWCX;
  10223. break;
  10224. case 8:
  10225. LoadMnemonic = PPC::LDARX;
  10226. StoreMnemonic = PPC::STDCX;
  10227. break;
  10228. }
  10229. const BasicBlock *LLVM_BB = BB->getBasicBlock();
  10230. MachineFunction *F = BB->getParent();
  10231. MachineFunction::iterator It = ++BB->getIterator();
  10232. Register dest = MI.getOperand(0).getReg();
  10233. Register ptrA = MI.getOperand(1).getReg();
  10234. Register ptrB = MI.getOperand(2).getReg();
  10235. Register incr = MI.getOperand(3).getReg();
  10236. DebugLoc dl = MI.getDebugLoc();
  10237. MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
  10238. MachineBasicBlock *loop2MBB =
  10239. CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
  10240. MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
  10241. F->insert(It, loopMBB);
  10242. if (CmpOpcode)
  10243. F->insert(It, loop2MBB);
  10244. F->insert(It, exitMBB);
  10245. exitMBB->splice(exitMBB->begin(), BB,
  10246. std::next(MachineBasicBlock::iterator(MI)), BB->end());
  10247. exitMBB->transferSuccessorsAndUpdatePHIs(BB);
  10248. MachineRegisterInfo &RegInfo = F->getRegInfo();
  10249. Register TmpReg = (!BinOpcode) ? incr :
  10250. RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
  10251. : &PPC::GPRCRegClass);
  10252. // thisMBB:
  10253. // ...
  10254. // fallthrough --> loopMBB
  10255. BB->addSuccessor(loopMBB);
  10256. // loopMBB:
  10257. // l[wd]arx dest, ptr
  10258. // add r0, dest, incr
  10259. // st[wd]cx. r0, ptr
  10260. // bne- loopMBB
  10261. // fallthrough --> exitMBB
  10262. // For max/min...
  10263. // loopMBB:
  10264. // l[wd]arx dest, ptr
  10265. // cmpl?[wd] dest, incr
  10266. // bgt exitMBB
  10267. // loop2MBB:
  10268. // st[wd]cx. dest, ptr
  10269. // bne- loopMBB
  10270. // fallthrough --> exitMBB
  10271. BB = loopMBB;
  10272. BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
  10273. .addReg(ptrA).addReg(ptrB);
  10274. if (BinOpcode)
  10275. BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
  10276. if (CmpOpcode) {
  10277. Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
  10278. // Signed comparisons of byte or halfword values must be sign-extended.
  10279. if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
  10280. Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
  10281. BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
  10282. ExtReg).addReg(dest);
  10283. BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(ExtReg).addReg(incr);
  10284. } else
  10285. BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(dest).addReg(incr);
  10286. BuildMI(BB, dl, TII->get(PPC::BCC))
  10287. .addImm(CmpPred)
  10288. .addReg(CrReg)
  10289. .addMBB(exitMBB);
  10290. BB->addSuccessor(loop2MBB);
  10291. BB->addSuccessor(exitMBB);
  10292. BB = loop2MBB;
  10293. }
  10294. BuildMI(BB, dl, TII->get(StoreMnemonic))
  10295. .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
  10296. BuildMI(BB, dl, TII->get(PPC::BCC))
  10297. .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
  10298. BB->addSuccessor(loopMBB);
  10299. BB->addSuccessor(exitMBB);
  10300. // exitMBB:
  10301. // ...
  10302. BB = exitMBB;
  10303. return BB;
  10304. }
  10305. static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) {
  10306. switch(MI.getOpcode()) {
  10307. default:
  10308. return false;
  10309. case PPC::COPY:
  10310. return TII->isSignExtended(MI.getOperand(1).getReg(),
  10311. &MI.getMF()->getRegInfo());
  10312. case PPC::LHA:
  10313. case PPC::LHA8:
  10314. case PPC::LHAU:
  10315. case PPC::LHAU8:
  10316. case PPC::LHAUX:
  10317. case PPC::LHAUX8:
  10318. case PPC::LHAX:
  10319. case PPC::LHAX8:
  10320. case PPC::LWA:
  10321. case PPC::LWAUX:
  10322. case PPC::LWAX:
  10323. case PPC::LWAX_32:
  10324. case PPC::LWA_32:
  10325. case PPC::PLHA:
  10326. case PPC::PLHA8:
  10327. case PPC::PLHA8pc:
  10328. case PPC::PLHApc:
  10329. case PPC::PLWA:
  10330. case PPC::PLWA8:
  10331. case PPC::PLWA8pc:
  10332. case PPC::PLWApc:
  10333. case PPC::EXTSB:
  10334. case PPC::EXTSB8:
  10335. case PPC::EXTSB8_32_64:
  10336. case PPC::EXTSB8_rec:
  10337. case PPC::EXTSB_rec:
  10338. case PPC::EXTSH:
  10339. case PPC::EXTSH8:
  10340. case PPC::EXTSH8_32_64:
  10341. case PPC::EXTSH8_rec:
  10342. case PPC::EXTSH_rec:
  10343. case PPC::EXTSW:
  10344. case PPC::EXTSWSLI:
  10345. case PPC::EXTSWSLI_32_64:
  10346. case PPC::EXTSWSLI_32_64_rec:
  10347. case PPC::EXTSWSLI_rec:
  10348. case PPC::EXTSW_32:
  10349. case PPC::EXTSW_32_64:
  10350. case PPC::EXTSW_32_64_rec:
  10351. case PPC::EXTSW_rec:
  10352. case PPC::SRAW:
  10353. case PPC::SRAWI:
  10354. case PPC::SRAWI_rec:
  10355. case PPC::SRAW_rec:
  10356. return true;
  10357. }
  10358. return false;
  10359. }
  10360. MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
  10361. MachineInstr &MI, MachineBasicBlock *BB,
  10362. bool is8bit, // operation
  10363. unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
  10364. // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
  10365. const PPCInstrInfo *TII = Subtarget.getInstrInfo();
  10366. // If this is a signed comparison and the value being compared is not known
  10367. // to be sign extended, sign extend it here.
  10368. DebugLoc dl = MI.getDebugLoc();
  10369. MachineFunction *F = BB->getParent();
  10370. MachineRegisterInfo &RegInfo = F->getRegInfo();
  10371. Register incr = MI.getOperand(3).getReg();
  10372. bool IsSignExtended =
  10373. incr.isVirtual() && isSignExtended(*RegInfo.getVRegDef(incr), TII);
  10374. if (CmpOpcode == PPC::CMPW && !IsSignExtended) {
  10375. Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
  10376. BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg)
  10377. .addReg(MI.getOperand(3).getReg());
  10378. MI.getOperand(3).setReg(ValueReg);
  10379. }
  10380. // If we support part-word atomic mnemonics, just use them
  10381. if (Subtarget.hasPartwordAtomics())
  10382. return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
  10383. CmpPred);
  10384. // In 64 bit mode we have to use 64 bits for addresses, even though the
  10385. // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
  10386. // registers without caring whether they're 32 or 64, but here we're
  10387. // doing actual arithmetic on the addresses.
  10388. bool is64bit = Subtarget.isPPC64();
  10389. bool isLittleEndian = Subtarget.isLittleEndian();
  10390. unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
  10391. const BasicBlock *LLVM_BB = BB->getBasicBlock();
  10392. MachineFunction::iterator It = ++BB->getIterator();
  10393. Register dest = MI.getOperand(0).getReg();
  10394. Register ptrA = MI.getOperand(1).getReg();
  10395. Register ptrB = MI.getOperand(2).getReg();
  10396. MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
  10397. MachineBasicBlock *loop2MBB =
  10398. CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
  10399. MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
  10400. F->insert(It, loopMBB);
  10401. if (CmpOpcode)
  10402. F->insert(It, loop2MBB);
  10403. F->insert(It, exitMBB);
  10404. exitMBB->splice(exitMBB->begin(), BB,
  10405. std::next(MachineBasicBlock::iterator(MI)), BB->end());
  10406. exitMBB->transferSuccessorsAndUpdatePHIs(BB);
  10407. const TargetRegisterClass *RC =
  10408. is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
  10409. const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
  10410. Register PtrReg = RegInfo.createVirtualRegister(RC);
  10411. Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
  10412. Register ShiftReg =
  10413. isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
  10414. Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
  10415. Register MaskReg = RegInfo.createVirtualRegister(GPRC);
  10416. Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
  10417. Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
  10418. Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
  10419. Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
  10420. Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
  10421. Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
  10422. Register SrwDestReg = RegInfo.createVirtualRegister(GPRC);
  10423. Register Ptr1Reg;
  10424. Register TmpReg =
  10425. (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
  10426. // thisMBB:
  10427. // ...
  10428. // fallthrough --> loopMBB
  10429. BB->addSuccessor(loopMBB);
  10430. // The 4-byte load must be aligned, while a char or short may be
  10431. // anywhere in the word. Hence all this nasty bookkeeping code.
  10432. // add ptr1, ptrA, ptrB [copy if ptrA==0]
  10433. // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
  10434. // xori shift, shift1, 24 [16]
  10435. // rlwinm ptr, ptr1, 0, 0, 29
  10436. // slw incr2, incr, shift
  10437. // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
  10438. // slw mask, mask2, shift
  10439. // loopMBB:
  10440. // lwarx tmpDest, ptr
  10441. // add tmp, tmpDest, incr2
  10442. // andc tmp2, tmpDest, mask
  10443. // and tmp3, tmp, mask
  10444. // or tmp4, tmp3, tmp2
  10445. // stwcx. tmp4, ptr
  10446. // bne- loopMBB
  10447. // fallthrough --> exitMBB
  10448. // srw SrwDest, tmpDest, shift
  10449. // rlwinm SrwDest, SrwDest, 0, 24 [16], 31
  10450. if (ptrA != ZeroReg) {
  10451. Ptr1Reg = RegInfo.createVirtualRegister(RC);
  10452. BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
  10453. .addReg(ptrA)
  10454. .addReg(ptrB);
  10455. } else {
  10456. Ptr1Reg = ptrB;
  10457. }
  10458. // We need use 32-bit subregister to avoid mismatch register class in 64-bit
  10459. // mode.
  10460. BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
  10461. .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
  10462. .addImm(3)
  10463. .addImm(27)
  10464. .addImm(is8bit ? 28 : 27);
  10465. if (!isLittleEndian)
  10466. BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
  10467. .addReg(Shift1Reg)
  10468. .addImm(is8bit ? 24 : 16);
  10469. if (is64bit)
  10470. BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
  10471. .addReg(Ptr1Reg)
  10472. .addImm(0)
  10473. .addImm(61);
  10474. else
  10475. BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
  10476. .addReg(Ptr1Reg)
  10477. .addImm(0)
  10478. .addImm(0)
  10479. .addImm(29);
  10480. BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
  10481. if (is8bit)
  10482. BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
  10483. else {
  10484. BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
  10485. BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
  10486. .addReg(Mask3Reg)
  10487. .addImm(65535);
  10488. }
  10489. BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
  10490. .addReg(Mask2Reg)
  10491. .addReg(ShiftReg);
  10492. BB = loopMBB;
  10493. BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
  10494. .addReg(ZeroReg)
  10495. .addReg(PtrReg);
  10496. if (BinOpcode)
  10497. BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
  10498. .addReg(Incr2Reg)
  10499. .addReg(TmpDestReg);
  10500. BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
  10501. .addReg(TmpDestReg)
  10502. .addReg(MaskReg);
  10503. BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
  10504. if (CmpOpcode) {
  10505. // For unsigned comparisons, we can directly compare the shifted values.
  10506. // For signed comparisons we shift and sign extend.
  10507. Register SReg = RegInfo.createVirtualRegister(GPRC);
  10508. Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
  10509. BuildMI(BB, dl, TII->get(PPC::AND), SReg)
  10510. .addReg(TmpDestReg)
  10511. .addReg(MaskReg);
  10512. unsigned ValueReg = SReg;
  10513. unsigned CmpReg = Incr2Reg;
  10514. if (CmpOpcode == PPC::CMPW) {
  10515. ValueReg = RegInfo.createVirtualRegister(GPRC);
  10516. BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
  10517. .addReg(SReg)
  10518. .addReg(ShiftReg);
  10519. Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
  10520. BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
  10521. .addReg(ValueReg);
  10522. ValueReg = ValueSReg;
  10523. CmpReg = incr;
  10524. }
  10525. BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(ValueReg).addReg(CmpReg);
  10526. BuildMI(BB, dl, TII->get(PPC::BCC))
  10527. .addImm(CmpPred)
  10528. .addReg(CrReg)
  10529. .addMBB(exitMBB);
  10530. BB->addSuccessor(loop2MBB);
  10531. BB->addSuccessor(exitMBB);
  10532. BB = loop2MBB;
  10533. }
  10534. BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
  10535. BuildMI(BB, dl, TII->get(PPC::STWCX))
  10536. .addReg(Tmp4Reg)
  10537. .addReg(ZeroReg)
  10538. .addReg(PtrReg);
  10539. BuildMI(BB, dl, TII->get(PPC::BCC))
  10540. .addImm(PPC::PRED_NE)
  10541. .addReg(PPC::CR0)
  10542. .addMBB(loopMBB);
  10543. BB->addSuccessor(loopMBB);
  10544. BB->addSuccessor(exitMBB);
  10545. // exitMBB:
  10546. // ...
  10547. BB = exitMBB;
  10548. // Since the shift amount is not a constant, we need to clear
  10549. // the upper bits with a separate RLWINM.
  10550. BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest)
  10551. .addReg(SrwDestReg)
  10552. .addImm(0)
  10553. .addImm(is8bit ? 24 : 16)
  10554. .addImm(31);
  10555. BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg)
  10556. .addReg(TmpDestReg)
  10557. .addReg(ShiftReg);
  10558. return BB;
  10559. }
  10560. llvm::MachineBasicBlock *
  10561. PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
  10562. MachineBasicBlock *MBB) const {
  10563. DebugLoc DL = MI.getDebugLoc();
  10564. const TargetInstrInfo *TII = Subtarget.getInstrInfo();
  10565. const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
  10566. MachineFunction *MF = MBB->getParent();
  10567. MachineRegisterInfo &MRI = MF->getRegInfo();
  10568. const BasicBlock *BB = MBB->getBasicBlock();
  10569. MachineFunction::iterator I = ++MBB->getIterator();
  10570. Register DstReg = MI.getOperand(0).getReg();
  10571. const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
  10572. assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
  10573. Register mainDstReg = MRI.createVirtualRegister(RC);
  10574. Register restoreDstReg = MRI.createVirtualRegister(RC);
  10575. MVT PVT = getPointerTy(MF->getDataLayout());
  10576. assert((PVT == MVT::i64 || PVT == MVT::i32) &&
  10577. "Invalid Pointer Size!");
  10578. // For v = setjmp(buf), we generate
  10579. //
  10580. // thisMBB:
  10581. // SjLjSetup mainMBB
  10582. // bl mainMBB
  10583. // v_restore = 1
  10584. // b sinkMBB
  10585. //
  10586. // mainMBB:
  10587. // buf[LabelOffset] = LR
  10588. // v_main = 0
  10589. //
  10590. // sinkMBB:
  10591. // v = phi(main, restore)
  10592. //
  10593. MachineBasicBlock *thisMBB = MBB;
  10594. MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
  10595. MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
  10596. MF->insert(I, mainMBB);
  10597. MF->insert(I, sinkMBB);
  10598. MachineInstrBuilder MIB;
  10599. // Transfer the remainder of BB and its successor edges to sinkMBB.
  10600. sinkMBB->splice(sinkMBB->begin(), MBB,
  10601. std::next(MachineBasicBlock::iterator(MI)), MBB->end());
  10602. sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
  10603. // Note that the structure of the jmp_buf used here is not compatible
  10604. // with that used by libc, and is not designed to be. Specifically, it
  10605. // stores only those 'reserved' registers that LLVM does not otherwise
  10606. // understand how to spill. Also, by convention, by the time this
  10607. // intrinsic is called, Clang has already stored the frame address in the
  10608. // first slot of the buffer and stack address in the third. Following the
  10609. // X86 target code, we'll store the jump address in the second slot. We also
  10610. // need to save the TOC pointer (R2) to handle jumps between shared
  10611. // libraries, and that will be stored in the fourth slot. The thread
  10612. // identifier (R13) is not affected.
  10613. // thisMBB:
  10614. const int64_t LabelOffset = 1 * PVT.getStoreSize();
  10615. const int64_t TOCOffset = 3 * PVT.getStoreSize();
  10616. const int64_t BPOffset = 4 * PVT.getStoreSize();
  10617. // Prepare IP either in reg.
  10618. const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
  10619. Register LabelReg = MRI.createVirtualRegister(PtrRC);
  10620. Register BufReg = MI.getOperand(1).getReg();
  10621. if (Subtarget.is64BitELFABI()) {
  10622. setUsesTOCBasePtr(*MBB->getParent());
  10623. MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
  10624. .addReg(PPC::X2)
  10625. .addImm(TOCOffset)
  10626. .addReg(BufReg)
  10627. .cloneMemRefs(MI);
  10628. }
  10629. // Naked functions never have a base pointer, and so we use r1. For all
  10630. // other functions, this decision must be delayed until during PEI.
  10631. unsigned BaseReg;
  10632. if (MF->getFunction().hasFnAttribute(Attribute::Naked))
  10633. BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
  10634. else
  10635. BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
  10636. MIB = BuildMI(*thisMBB, MI, DL,
  10637. TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
  10638. .addReg(BaseReg)
  10639. .addImm(BPOffset)
  10640. .addReg(BufReg)
  10641. .cloneMemRefs(MI);
  10642. // Setup
  10643. MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
  10644. MIB.addRegMask(TRI->getNoPreservedMask());
  10645. BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
  10646. MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
  10647. .addMBB(mainMBB);
  10648. MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
  10649. thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
  10650. thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
  10651. // mainMBB:
  10652. // mainDstReg = 0
  10653. MIB =
  10654. BuildMI(mainMBB, DL,
  10655. TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
  10656. // Store IP
  10657. if (Subtarget.isPPC64()) {
  10658. MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
  10659. .addReg(LabelReg)
  10660. .addImm(LabelOffset)
  10661. .addReg(BufReg);
  10662. } else {
  10663. MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
  10664. .addReg(LabelReg)
  10665. .addImm(LabelOffset)
  10666. .addReg(BufReg);
  10667. }
  10668. MIB.cloneMemRefs(MI);
  10669. BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
  10670. mainMBB->addSuccessor(sinkMBB);
  10671. // sinkMBB:
  10672. BuildMI(*sinkMBB, sinkMBB->begin(), DL,
  10673. TII->get(PPC::PHI), DstReg)
  10674. .addReg(mainDstReg).addMBB(mainMBB)
  10675. .addReg(restoreDstReg).addMBB(thisMBB);
  10676. MI.eraseFromParent();
  10677. return sinkMBB;
  10678. }
  10679. MachineBasicBlock *
  10680. PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
  10681. MachineBasicBlock *MBB) const {
  10682. DebugLoc DL = MI.getDebugLoc();
  10683. const TargetInstrInfo *TII = Subtarget.getInstrInfo();
  10684. MachineFunction *MF = MBB->getParent();
  10685. MachineRegisterInfo &MRI = MF->getRegInfo();
  10686. MVT PVT = getPointerTy(MF->getDataLayout());
  10687. assert((PVT == MVT::i64 || PVT == MVT::i32) &&
  10688. "Invalid Pointer Size!");
  10689. const TargetRegisterClass *RC =
  10690. (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
  10691. Register Tmp = MRI.createVirtualRegister(RC);
  10692. // Since FP is only updated here but NOT referenced, it's treated as GPR.
  10693. unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
  10694. unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
  10695. unsigned BP =
  10696. (PVT == MVT::i64)
  10697. ? PPC::X30
  10698. : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
  10699. : PPC::R30);
  10700. MachineInstrBuilder MIB;
  10701. const int64_t LabelOffset = 1 * PVT.getStoreSize();
  10702. const int64_t SPOffset = 2 * PVT.getStoreSize();
  10703. const int64_t TOCOffset = 3 * PVT.getStoreSize();
  10704. const int64_t BPOffset = 4 * PVT.getStoreSize();
  10705. Register BufReg = MI.getOperand(0).getReg();
  10706. // Reload FP (the jumped-to function may not have had a
  10707. // frame pointer, and if so, then its r31 will be restored
  10708. // as necessary).
  10709. if (PVT == MVT::i64) {
  10710. MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
  10711. .addImm(0)
  10712. .addReg(BufReg);
  10713. } else {
  10714. MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
  10715. .addImm(0)
  10716. .addReg(BufReg);
  10717. }
  10718. MIB.cloneMemRefs(MI);
  10719. // Reload IP
  10720. if (PVT == MVT::i64) {
  10721. MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
  10722. .addImm(LabelOffset)
  10723. .addReg(BufReg);
  10724. } else {
  10725. MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
  10726. .addImm(LabelOffset)
  10727. .addReg(BufReg);
  10728. }
  10729. MIB.cloneMemRefs(MI);
  10730. // Reload SP
  10731. if (PVT == MVT::i64) {
  10732. MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
  10733. .addImm(SPOffset)
  10734. .addReg(BufReg);
  10735. } else {
  10736. MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
  10737. .addImm(SPOffset)
  10738. .addReg(BufReg);
  10739. }
  10740. MIB.cloneMemRefs(MI);
  10741. // Reload BP
  10742. if (PVT == MVT::i64) {
  10743. MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
  10744. .addImm(BPOffset)
  10745. .addReg(BufReg);
  10746. } else {
  10747. MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
  10748. .addImm(BPOffset)
  10749. .addReg(BufReg);
  10750. }
  10751. MIB.cloneMemRefs(MI);
  10752. // Reload TOC
  10753. if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
  10754. setUsesTOCBasePtr(*MBB->getParent());
  10755. MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
  10756. .addImm(TOCOffset)
  10757. .addReg(BufReg)
  10758. .cloneMemRefs(MI);
  10759. }
  10760. // Jump
  10761. BuildMI(*MBB, MI, DL,
  10762. TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
  10763. BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
  10764. MI.eraseFromParent();
  10765. return MBB;
  10766. }
  10767. bool PPCTargetLowering::hasInlineStackProbe(const MachineFunction &MF) const {
  10768. // If the function specifically requests inline stack probes, emit them.
  10769. if (MF.getFunction().hasFnAttribute("probe-stack"))
  10770. return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
  10771. "inline-asm";
  10772. return false;
  10773. }
  10774. unsigned PPCTargetLowering::getStackProbeSize(const MachineFunction &MF) const {
  10775. const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
  10776. unsigned StackAlign = TFI->getStackAlignment();
  10777. assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
  10778. "Unexpected stack alignment");
  10779. // The default stack probe size is 4096 if the function has no
  10780. // stack-probe-size attribute.
  10781. const Function &Fn = MF.getFunction();
  10782. unsigned StackProbeSize =
  10783. Fn.getFnAttributeAsParsedInteger("stack-probe-size", 4096);
  10784. // Round down to the stack alignment.
  10785. StackProbeSize &= ~(StackAlign - 1);
  10786. return StackProbeSize ? StackProbeSize : StackAlign;
  10787. }
  10788. // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
  10789. // into three phases. In the first phase, it uses pseudo instruction
  10790. // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
  10791. // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
  10792. // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
  10793. // MaxCallFrameSize so that it can calculate correct data area pointer.
  10794. MachineBasicBlock *
  10795. PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
  10796. MachineBasicBlock *MBB) const {
  10797. const bool isPPC64 = Subtarget.isPPC64();
  10798. MachineFunction *MF = MBB->getParent();
  10799. const TargetInstrInfo *TII = Subtarget.getInstrInfo();
  10800. DebugLoc DL = MI.getDebugLoc();
  10801. const unsigned ProbeSize = getStackProbeSize(*MF);
  10802. const BasicBlock *ProbedBB = MBB->getBasicBlock();
  10803. MachineRegisterInfo &MRI = MF->getRegInfo();
  10804. // The CFG of probing stack looks as
  10805. // +-----+
  10806. // | MBB |
  10807. // +--+--+
  10808. // |
  10809. // +----v----+
  10810. // +--->+ TestMBB +---+
  10811. // | +----+----+ |
  10812. // | | |
  10813. // | +-----v----+ |
  10814. // +---+ BlockMBB | |
  10815. // +----------+ |
  10816. // |
  10817. // +---------+ |
  10818. // | TailMBB +<--+
  10819. // +---------+
  10820. // In MBB, calculate previous frame pointer and final stack pointer.
  10821. // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
  10822. // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
  10823. // TailMBB is spliced via \p MI.
  10824. MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
  10825. MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
  10826. MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
  10827. MachineFunction::iterator MBBIter = ++MBB->getIterator();
  10828. MF->insert(MBBIter, TestMBB);
  10829. MF->insert(MBBIter, BlockMBB);
  10830. MF->insert(MBBIter, TailMBB);
  10831. const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
  10832. const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
  10833. Register DstReg = MI.getOperand(0).getReg();
  10834. Register NegSizeReg = MI.getOperand(1).getReg();
  10835. Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
  10836. Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
  10837. Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
  10838. Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
  10839. // Since value of NegSizeReg might be realigned in prologepilog, insert a
  10840. // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
  10841. // NegSize.
  10842. unsigned ProbeOpc;
  10843. if (!MRI.hasOneNonDBGUse(NegSizeReg))
  10844. ProbeOpc =
  10845. isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
  10846. else
  10847. // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
  10848. // and NegSizeReg will be allocated in the same phyreg to avoid
  10849. // redundant copy when NegSizeReg has only one use which is current MI and
  10850. // will be replaced by PREPARE_PROBED_ALLOCA then.
  10851. ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
  10852. : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
  10853. BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
  10854. .addDef(ActualNegSizeReg)
  10855. .addReg(NegSizeReg)
  10856. .add(MI.getOperand(2))
  10857. .add(MI.getOperand(3));
  10858. // Calculate final stack pointer, which equals to SP + ActualNegSize.
  10859. BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
  10860. FinalStackPtr)
  10861. .addReg(SPReg)
  10862. .addReg(ActualNegSizeReg);
  10863. // Materialize a scratch register for update.
  10864. int64_t NegProbeSize = -(int64_t)ProbeSize;
  10865. assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
  10866. Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
  10867. if (!isInt<16>(NegProbeSize)) {
  10868. Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
  10869. BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
  10870. .addImm(NegProbeSize >> 16);
  10871. BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
  10872. ScratchReg)
  10873. .addReg(TempReg)
  10874. .addImm(NegProbeSize & 0xFFFF);
  10875. } else
  10876. BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
  10877. .addImm(NegProbeSize);
  10878. {
  10879. // Probing leading residual part.
  10880. Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
  10881. BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
  10882. .addReg(ActualNegSizeReg)
  10883. .addReg(ScratchReg);
  10884. Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
  10885. BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
  10886. .addReg(Div)
  10887. .addReg(ScratchReg);
  10888. Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
  10889. BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
  10890. .addReg(Mul)
  10891. .addReg(ActualNegSizeReg);
  10892. BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
  10893. .addReg(FramePointer)
  10894. .addReg(SPReg)
  10895. .addReg(NegMod);
  10896. }
  10897. {
  10898. // Remaining part should be multiple of ProbeSize.
  10899. Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
  10900. BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
  10901. .addReg(SPReg)
  10902. .addReg(FinalStackPtr);
  10903. BuildMI(TestMBB, DL, TII->get(PPC::BCC))
  10904. .addImm(PPC::PRED_EQ)
  10905. .addReg(CmpResult)
  10906. .addMBB(TailMBB);
  10907. TestMBB->addSuccessor(BlockMBB);
  10908. TestMBB->addSuccessor(TailMBB);
  10909. }
  10910. {
  10911. // Touch the block.
  10912. // |P...|P...|P...
  10913. BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
  10914. .addReg(FramePointer)
  10915. .addReg(SPReg)
  10916. .addReg(ScratchReg);
  10917. BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
  10918. BlockMBB->addSuccessor(TestMBB);
  10919. }
  10920. // Calculation of MaxCallFrameSize is deferred to prologepilog, use
  10921. // DYNAREAOFFSET pseudo instruction to get the future result.
  10922. Register MaxCallFrameSizeReg =
  10923. MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
  10924. BuildMI(TailMBB, DL,
  10925. TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
  10926. MaxCallFrameSizeReg)
  10927. .add(MI.getOperand(2))
  10928. .add(MI.getOperand(3));
  10929. BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
  10930. .addReg(SPReg)
  10931. .addReg(MaxCallFrameSizeReg);
  10932. // Splice instructions after MI to TailMBB.
  10933. TailMBB->splice(TailMBB->end(), MBB,
  10934. std::next(MachineBasicBlock::iterator(MI)), MBB->end());
  10935. TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
  10936. MBB->addSuccessor(TestMBB);
  10937. // Delete the pseudo instruction.
  10938. MI.eraseFromParent();
  10939. ++NumDynamicAllocaProbed;
  10940. return TailMBB;
  10941. }
  10942. MachineBasicBlock *
  10943. PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
  10944. MachineBasicBlock *BB) const {
  10945. if (MI.getOpcode() == TargetOpcode::STACKMAP ||
  10946. MI.getOpcode() == TargetOpcode::PATCHPOINT) {
  10947. if (Subtarget.is64BitELFABI() &&
  10948. MI.getOpcode() == TargetOpcode::PATCHPOINT &&
  10949. !Subtarget.isUsingPCRelativeCalls()) {
  10950. // Call lowering should have added an r2 operand to indicate a dependence
  10951. // on the TOC base pointer value. It can't however, because there is no
  10952. // way to mark the dependence as implicit there, and so the stackmap code
  10953. // will confuse it with a regular operand. Instead, add the dependence
  10954. // here.
  10955. MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
  10956. }
  10957. return emitPatchPoint(MI, BB);
  10958. }
  10959. if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
  10960. MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
  10961. return emitEHSjLjSetJmp(MI, BB);
  10962. } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
  10963. MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
  10964. return emitEHSjLjLongJmp(MI, BB);
  10965. }
  10966. const TargetInstrInfo *TII = Subtarget.getInstrInfo();
  10967. // To "insert" these instructions we actually have to insert their
  10968. // control-flow patterns.
  10969. const BasicBlock *LLVM_BB = BB->getBasicBlock();
  10970. MachineFunction::iterator It = ++BB->getIterator();
  10971. MachineFunction *F = BB->getParent();
  10972. MachineRegisterInfo &MRI = F->getRegInfo();
  10973. if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
  10974. MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
  10975. MI.getOpcode() == PPC::SELECT_I8) {
  10976. SmallVector<MachineOperand, 2> Cond;
  10977. if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
  10978. MI.getOpcode() == PPC::SELECT_CC_I8)
  10979. Cond.push_back(MI.getOperand(4));
  10980. else
  10981. Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
  10982. Cond.push_back(MI.getOperand(1));
  10983. DebugLoc dl = MI.getDebugLoc();
  10984. TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
  10985. MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
  10986. } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
  10987. MI.getOpcode() == PPC::SELECT_CC_F8 ||
  10988. MI.getOpcode() == PPC::SELECT_CC_F16 ||
  10989. MI.getOpcode() == PPC::SELECT_CC_VRRC ||
  10990. MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
  10991. MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
  10992. MI.getOpcode() == PPC::SELECT_CC_VSRC ||
  10993. MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
  10994. MI.getOpcode() == PPC::SELECT_CC_SPE ||
  10995. MI.getOpcode() == PPC::SELECT_F4 ||
  10996. MI.getOpcode() == PPC::SELECT_F8 ||
  10997. MI.getOpcode() == PPC::SELECT_F16 ||
  10998. MI.getOpcode() == PPC::SELECT_SPE ||
  10999. MI.getOpcode() == PPC::SELECT_SPE4 ||
  11000. MI.getOpcode() == PPC::SELECT_VRRC ||
  11001. MI.getOpcode() == PPC::SELECT_VSFRC ||
  11002. MI.getOpcode() == PPC::SELECT_VSSRC ||
  11003. MI.getOpcode() == PPC::SELECT_VSRC) {
  11004. // The incoming instruction knows the destination vreg to set, the
  11005. // condition code register to branch on, the true/false values to
  11006. // select between, and a branch opcode to use.
  11007. // thisMBB:
  11008. // ...
  11009. // TrueVal = ...
  11010. // cmpTY ccX, r1, r2
  11011. // bCC copy1MBB
  11012. // fallthrough --> copy0MBB
  11013. MachineBasicBlock *thisMBB = BB;
  11014. MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
  11015. MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
  11016. DebugLoc dl = MI.getDebugLoc();
  11017. F->insert(It, copy0MBB);
  11018. F->insert(It, sinkMBB);
  11019. // Transfer the remainder of BB and its successor edges to sinkMBB.
  11020. sinkMBB->splice(sinkMBB->begin(), BB,
  11021. std::next(MachineBasicBlock::iterator(MI)), BB->end());
  11022. sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
  11023. // Next, add the true and fallthrough blocks as its successors.
  11024. BB->addSuccessor(copy0MBB);
  11025. BB->addSuccessor(sinkMBB);
  11026. if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
  11027. MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
  11028. MI.getOpcode() == PPC::SELECT_F16 ||
  11029. MI.getOpcode() == PPC::SELECT_SPE4 ||
  11030. MI.getOpcode() == PPC::SELECT_SPE ||
  11031. MI.getOpcode() == PPC::SELECT_VRRC ||
  11032. MI.getOpcode() == PPC::SELECT_VSFRC ||
  11033. MI.getOpcode() == PPC::SELECT_VSSRC ||
  11034. MI.getOpcode() == PPC::SELECT_VSRC) {
  11035. BuildMI(BB, dl, TII->get(PPC::BC))
  11036. .addReg(MI.getOperand(1).getReg())
  11037. .addMBB(sinkMBB);
  11038. } else {
  11039. unsigned SelectPred = MI.getOperand(4).getImm();
  11040. BuildMI(BB, dl, TII->get(PPC::BCC))
  11041. .addImm(SelectPred)
  11042. .addReg(MI.getOperand(1).getReg())
  11043. .addMBB(sinkMBB);
  11044. }
  11045. // copy0MBB:
  11046. // %FalseValue = ...
  11047. // # fallthrough to sinkMBB
  11048. BB = copy0MBB;
  11049. // Update machine-CFG edges
  11050. BB->addSuccessor(sinkMBB);
  11051. // sinkMBB:
  11052. // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
  11053. // ...
  11054. BB = sinkMBB;
  11055. BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
  11056. .addReg(MI.getOperand(3).getReg())
  11057. .addMBB(copy0MBB)
  11058. .addReg(MI.getOperand(2).getReg())
  11059. .addMBB(thisMBB);
  11060. } else if (MI.getOpcode() == PPC::ReadTB) {
  11061. // To read the 64-bit time-base register on a 32-bit target, we read the
  11062. // two halves. Should the counter have wrapped while it was being read, we
  11063. // need to try again.
  11064. // ...
  11065. // readLoop:
  11066. // mfspr Rx,TBU # load from TBU
  11067. // mfspr Ry,TB # load from TB
  11068. // mfspr Rz,TBU # load from TBU
  11069. // cmpw crX,Rx,Rz # check if 'old'='new'
  11070. // bne readLoop # branch if they're not equal
  11071. // ...
  11072. MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
  11073. MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
  11074. DebugLoc dl = MI.getDebugLoc();
  11075. F->insert(It, readMBB);
  11076. F->insert(It, sinkMBB);
  11077. // Transfer the remainder of BB and its successor edges to sinkMBB.
  11078. sinkMBB->splice(sinkMBB->begin(), BB,
  11079. std::next(MachineBasicBlock::iterator(MI)), BB->end());
  11080. sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
  11081. BB->addSuccessor(readMBB);
  11082. BB = readMBB;
  11083. MachineRegisterInfo &RegInfo = F->getRegInfo();
  11084. Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
  11085. Register LoReg = MI.getOperand(0).getReg();
  11086. Register HiReg = MI.getOperand(1).getReg();
  11087. BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
  11088. BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
  11089. BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
  11090. Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
  11091. BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
  11092. .addReg(HiReg)
  11093. .addReg(ReadAgainReg);
  11094. BuildMI(BB, dl, TII->get(PPC::BCC))
  11095. .addImm(PPC::PRED_NE)
  11096. .addReg(CmpReg)
  11097. .addMBB(readMBB);
  11098. BB->addSuccessor(readMBB);
  11099. BB->addSuccessor(sinkMBB);
  11100. } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
  11101. BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
  11102. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
  11103. BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
  11104. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
  11105. BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
  11106. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
  11107. BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
  11108. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
  11109. BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
  11110. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
  11111. BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
  11112. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
  11113. BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
  11114. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
  11115. BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
  11116. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
  11117. BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
  11118. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
  11119. BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
  11120. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
  11121. BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
  11122. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
  11123. BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
  11124. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
  11125. BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
  11126. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
  11127. BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
  11128. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
  11129. BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
  11130. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
  11131. BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
  11132. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
  11133. BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
  11134. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
  11135. BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
  11136. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
  11137. BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
  11138. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
  11139. BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
  11140. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
  11141. BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
  11142. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
  11143. BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
  11144. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
  11145. BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
  11146. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
  11147. BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
  11148. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
  11149. BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LT);
  11150. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
  11151. BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LT);
  11152. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
  11153. BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LT);
  11154. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
  11155. BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LT);
  11156. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
  11157. BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GT);
  11158. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
  11159. BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GT);
  11160. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
  11161. BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GT);
  11162. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
  11163. BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GT);
  11164. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
  11165. BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LT);
  11166. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
  11167. BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LT);
  11168. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
  11169. BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LT);
  11170. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
  11171. BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LT);
  11172. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
  11173. BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GT);
  11174. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
  11175. BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GT);
  11176. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
  11177. BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GT);
  11178. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
  11179. BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GT);
  11180. else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
  11181. BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
  11182. else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
  11183. BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
  11184. else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
  11185. BB = EmitAtomicBinary(MI, BB, 4, 0);
  11186. else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
  11187. BB = EmitAtomicBinary(MI, BB, 8, 0);
  11188. else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
  11189. MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
  11190. (Subtarget.hasPartwordAtomics() &&
  11191. MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
  11192. (Subtarget.hasPartwordAtomics() &&
  11193. MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
  11194. bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
  11195. auto LoadMnemonic = PPC::LDARX;
  11196. auto StoreMnemonic = PPC::STDCX;
  11197. switch (MI.getOpcode()) {
  11198. default:
  11199. llvm_unreachable("Compare and swap of unknown size");
  11200. case PPC::ATOMIC_CMP_SWAP_I8:
  11201. LoadMnemonic = PPC::LBARX;
  11202. StoreMnemonic = PPC::STBCX;
  11203. assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
  11204. break;
  11205. case PPC::ATOMIC_CMP_SWAP_I16:
  11206. LoadMnemonic = PPC::LHARX;
  11207. StoreMnemonic = PPC::STHCX;
  11208. assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
  11209. break;
  11210. case PPC::ATOMIC_CMP_SWAP_I32:
  11211. LoadMnemonic = PPC::LWARX;
  11212. StoreMnemonic = PPC::STWCX;
  11213. break;
  11214. case PPC::ATOMIC_CMP_SWAP_I64:
  11215. LoadMnemonic = PPC::LDARX;
  11216. StoreMnemonic = PPC::STDCX;
  11217. break;
  11218. }
  11219. MachineRegisterInfo &RegInfo = F->getRegInfo();
  11220. Register dest = MI.getOperand(0).getReg();
  11221. Register ptrA = MI.getOperand(1).getReg();
  11222. Register ptrB = MI.getOperand(2).getReg();
  11223. Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
  11224. Register oldval = MI.getOperand(3).getReg();
  11225. Register newval = MI.getOperand(4).getReg();
  11226. DebugLoc dl = MI.getDebugLoc();
  11227. MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
  11228. MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
  11229. MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
  11230. F->insert(It, loop1MBB);
  11231. F->insert(It, loop2MBB);
  11232. F->insert(It, exitMBB);
  11233. exitMBB->splice(exitMBB->begin(), BB,
  11234. std::next(MachineBasicBlock::iterator(MI)), BB->end());
  11235. exitMBB->transferSuccessorsAndUpdatePHIs(BB);
  11236. // thisMBB:
  11237. // ...
  11238. // fallthrough --> loopMBB
  11239. BB->addSuccessor(loop1MBB);
  11240. // loop1MBB:
  11241. // l[bhwd]arx dest, ptr
  11242. // cmp[wd] dest, oldval
  11243. // bne- exitBB
  11244. // loop2MBB:
  11245. // st[bhwd]cx. newval, ptr
  11246. // bne- loopMBB
  11247. // b exitBB
  11248. // exitBB:
  11249. BB = loop1MBB;
  11250. BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
  11251. BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), CrReg)
  11252. .addReg(dest)
  11253. .addReg(oldval);
  11254. BuildMI(BB, dl, TII->get(PPC::BCC))
  11255. .addImm(PPC::PRED_NE)
  11256. .addReg(CrReg)
  11257. .addMBB(exitMBB);
  11258. BB->addSuccessor(loop2MBB);
  11259. BB->addSuccessor(exitMBB);
  11260. BB = loop2MBB;
  11261. BuildMI(BB, dl, TII->get(StoreMnemonic))
  11262. .addReg(newval)
  11263. .addReg(ptrA)
  11264. .addReg(ptrB);
  11265. BuildMI(BB, dl, TII->get(PPC::BCC))
  11266. .addImm(PPC::PRED_NE)
  11267. .addReg(PPC::CR0)
  11268. .addMBB(loop1MBB);
  11269. BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
  11270. BB->addSuccessor(loop1MBB);
  11271. BB->addSuccessor(exitMBB);
  11272. // exitMBB:
  11273. // ...
  11274. BB = exitMBB;
  11275. } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
  11276. MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
  11277. // We must use 64-bit registers for addresses when targeting 64-bit,
  11278. // since we're actually doing arithmetic on them. Other registers
  11279. // can be 32-bit.
  11280. bool is64bit = Subtarget.isPPC64();
  11281. bool isLittleEndian = Subtarget.isLittleEndian();
  11282. bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
  11283. Register dest = MI.getOperand(0).getReg();
  11284. Register ptrA = MI.getOperand(1).getReg();
  11285. Register ptrB = MI.getOperand(2).getReg();
  11286. Register oldval = MI.getOperand(3).getReg();
  11287. Register newval = MI.getOperand(4).getReg();
  11288. DebugLoc dl = MI.getDebugLoc();
  11289. MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
  11290. MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
  11291. MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
  11292. F->insert(It, loop1MBB);
  11293. F->insert(It, loop2MBB);
  11294. F->insert(It, exitMBB);
  11295. exitMBB->splice(exitMBB->begin(), BB,
  11296. std::next(MachineBasicBlock::iterator(MI)), BB->end());
  11297. exitMBB->transferSuccessorsAndUpdatePHIs(BB);
  11298. MachineRegisterInfo &RegInfo = F->getRegInfo();
  11299. const TargetRegisterClass *RC =
  11300. is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
  11301. const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
  11302. Register PtrReg = RegInfo.createVirtualRegister(RC);
  11303. Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
  11304. Register ShiftReg =
  11305. isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
  11306. Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
  11307. Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
  11308. Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
  11309. Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
  11310. Register MaskReg = RegInfo.createVirtualRegister(GPRC);
  11311. Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
  11312. Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
  11313. Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
  11314. Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
  11315. Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
  11316. Register Ptr1Reg;
  11317. Register TmpReg = RegInfo.createVirtualRegister(GPRC);
  11318. Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
  11319. Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
  11320. // thisMBB:
  11321. // ...
  11322. // fallthrough --> loopMBB
  11323. BB->addSuccessor(loop1MBB);
  11324. // The 4-byte load must be aligned, while a char or short may be
  11325. // anywhere in the word. Hence all this nasty bookkeeping code.
  11326. // add ptr1, ptrA, ptrB [copy if ptrA==0]
  11327. // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
  11328. // xori shift, shift1, 24 [16]
  11329. // rlwinm ptr, ptr1, 0, 0, 29
  11330. // slw newval2, newval, shift
  11331. // slw oldval2, oldval,shift
  11332. // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
  11333. // slw mask, mask2, shift
  11334. // and newval3, newval2, mask
  11335. // and oldval3, oldval2, mask
  11336. // loop1MBB:
  11337. // lwarx tmpDest, ptr
  11338. // and tmp, tmpDest, mask
  11339. // cmpw tmp, oldval3
  11340. // bne- exitBB
  11341. // loop2MBB:
  11342. // andc tmp2, tmpDest, mask
  11343. // or tmp4, tmp2, newval3
  11344. // stwcx. tmp4, ptr
  11345. // bne- loop1MBB
  11346. // b exitBB
  11347. // exitBB:
  11348. // srw dest, tmpDest, shift
  11349. if (ptrA != ZeroReg) {
  11350. Ptr1Reg = RegInfo.createVirtualRegister(RC);
  11351. BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
  11352. .addReg(ptrA)
  11353. .addReg(ptrB);
  11354. } else {
  11355. Ptr1Reg = ptrB;
  11356. }
  11357. // We need use 32-bit subregister to avoid mismatch register class in 64-bit
  11358. // mode.
  11359. BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
  11360. .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
  11361. .addImm(3)
  11362. .addImm(27)
  11363. .addImm(is8bit ? 28 : 27);
  11364. if (!isLittleEndian)
  11365. BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
  11366. .addReg(Shift1Reg)
  11367. .addImm(is8bit ? 24 : 16);
  11368. if (is64bit)
  11369. BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
  11370. .addReg(Ptr1Reg)
  11371. .addImm(0)
  11372. .addImm(61);
  11373. else
  11374. BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
  11375. .addReg(Ptr1Reg)
  11376. .addImm(0)
  11377. .addImm(0)
  11378. .addImm(29);
  11379. BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
  11380. .addReg(newval)
  11381. .addReg(ShiftReg);
  11382. BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
  11383. .addReg(oldval)
  11384. .addReg(ShiftReg);
  11385. if (is8bit)
  11386. BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
  11387. else {
  11388. BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
  11389. BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
  11390. .addReg(Mask3Reg)
  11391. .addImm(65535);
  11392. }
  11393. BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
  11394. .addReg(Mask2Reg)
  11395. .addReg(ShiftReg);
  11396. BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
  11397. .addReg(NewVal2Reg)
  11398. .addReg(MaskReg);
  11399. BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
  11400. .addReg(OldVal2Reg)
  11401. .addReg(MaskReg);
  11402. BB = loop1MBB;
  11403. BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
  11404. .addReg(ZeroReg)
  11405. .addReg(PtrReg);
  11406. BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
  11407. .addReg(TmpDestReg)
  11408. .addReg(MaskReg);
  11409. BuildMI(BB, dl, TII->get(PPC::CMPW), CrReg)
  11410. .addReg(TmpReg)
  11411. .addReg(OldVal3Reg);
  11412. BuildMI(BB, dl, TII->get(PPC::BCC))
  11413. .addImm(PPC::PRED_NE)
  11414. .addReg(CrReg)
  11415. .addMBB(exitMBB);
  11416. BB->addSuccessor(loop2MBB);
  11417. BB->addSuccessor(exitMBB);
  11418. BB = loop2MBB;
  11419. BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
  11420. .addReg(TmpDestReg)
  11421. .addReg(MaskReg);
  11422. BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
  11423. .addReg(Tmp2Reg)
  11424. .addReg(NewVal3Reg);
  11425. BuildMI(BB, dl, TII->get(PPC::STWCX))
  11426. .addReg(Tmp4Reg)
  11427. .addReg(ZeroReg)
  11428. .addReg(PtrReg);
  11429. BuildMI(BB, dl, TII->get(PPC::BCC))
  11430. .addImm(PPC::PRED_NE)
  11431. .addReg(PPC::CR0)
  11432. .addMBB(loop1MBB);
  11433. BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
  11434. BB->addSuccessor(loop1MBB);
  11435. BB->addSuccessor(exitMBB);
  11436. // exitMBB:
  11437. // ...
  11438. BB = exitMBB;
  11439. BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
  11440. .addReg(TmpReg)
  11441. .addReg(ShiftReg);
  11442. } else if (MI.getOpcode() == PPC::FADDrtz) {
  11443. // This pseudo performs an FADD with rounding mode temporarily forced
  11444. // to round-to-zero. We emit this via custom inserter since the FPSCR
  11445. // is not modeled at the SelectionDAG level.
  11446. Register Dest = MI.getOperand(0).getReg();
  11447. Register Src1 = MI.getOperand(1).getReg();
  11448. Register Src2 = MI.getOperand(2).getReg();
  11449. DebugLoc dl = MI.getDebugLoc();
  11450. MachineRegisterInfo &RegInfo = F->getRegInfo();
  11451. Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
  11452. // Save FPSCR value.
  11453. BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
  11454. // Set rounding mode to round-to-zero.
  11455. BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
  11456. .addImm(31)
  11457. .addReg(PPC::RM, RegState::ImplicitDefine);
  11458. BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
  11459. .addImm(30)
  11460. .addReg(PPC::RM, RegState::ImplicitDefine);
  11461. // Perform addition.
  11462. auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
  11463. .addReg(Src1)
  11464. .addReg(Src2);
  11465. if (MI.getFlag(MachineInstr::NoFPExcept))
  11466. MIB.setMIFlag(MachineInstr::NoFPExcept);
  11467. // Restore FPSCR value.
  11468. BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
  11469. } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
  11470. MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
  11471. MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
  11472. MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
  11473. unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
  11474. MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
  11475. ? PPC::ANDI8_rec
  11476. : PPC::ANDI_rec;
  11477. bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
  11478. MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
  11479. MachineRegisterInfo &RegInfo = F->getRegInfo();
  11480. Register Dest = RegInfo.createVirtualRegister(
  11481. Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
  11482. DebugLoc Dl = MI.getDebugLoc();
  11483. BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
  11484. .addReg(MI.getOperand(1).getReg())
  11485. .addImm(1);
  11486. BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
  11487. MI.getOperand(0).getReg())
  11488. .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
  11489. } else if (MI.getOpcode() == PPC::TCHECK_RET) {
  11490. DebugLoc Dl = MI.getDebugLoc();
  11491. MachineRegisterInfo &RegInfo = F->getRegInfo();
  11492. Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
  11493. BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
  11494. BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
  11495. MI.getOperand(0).getReg())
  11496. .addReg(CRReg);
  11497. } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
  11498. DebugLoc Dl = MI.getDebugLoc();
  11499. unsigned Imm = MI.getOperand(1).getImm();
  11500. BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
  11501. BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
  11502. MI.getOperand(0).getReg())
  11503. .addReg(PPC::CR0EQ);
  11504. } else if (MI.getOpcode() == PPC::SETRNDi) {
  11505. DebugLoc dl = MI.getDebugLoc();
  11506. Register OldFPSCRReg = MI.getOperand(0).getReg();
  11507. // Save FPSCR value.
  11508. if (MRI.use_empty(OldFPSCRReg))
  11509. BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
  11510. else
  11511. BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
  11512. // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
  11513. // the following settings:
  11514. // 00 Round to nearest
  11515. // 01 Round to 0
  11516. // 10 Round to +inf
  11517. // 11 Round to -inf
  11518. // When the operand is immediate, using the two least significant bits of
  11519. // the immediate to set the bits 62:63 of FPSCR.
  11520. unsigned Mode = MI.getOperand(1).getImm();
  11521. BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
  11522. .addImm(31)
  11523. .addReg(PPC::RM, RegState::ImplicitDefine);
  11524. BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
  11525. .addImm(30)
  11526. .addReg(PPC::RM, RegState::ImplicitDefine);
  11527. } else if (MI.getOpcode() == PPC::SETRND) {
  11528. DebugLoc dl = MI.getDebugLoc();
  11529. // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
  11530. // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
  11531. // If the target doesn't have DirectMove, we should use stack to do the
  11532. // conversion, because the target doesn't have the instructions like mtvsrd
  11533. // or mfvsrd to do this conversion directly.
  11534. auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
  11535. if (Subtarget.hasDirectMove()) {
  11536. BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
  11537. .addReg(SrcReg);
  11538. } else {
  11539. // Use stack to do the register copy.
  11540. unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
  11541. MachineRegisterInfo &RegInfo = F->getRegInfo();
  11542. const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
  11543. if (RC == &PPC::F8RCRegClass) {
  11544. // Copy register from F8RCRegClass to G8RCRegclass.
  11545. assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
  11546. "Unsupported RegClass.");
  11547. StoreOp = PPC::STFD;
  11548. LoadOp = PPC::LD;
  11549. } else {
  11550. // Copy register from G8RCRegClass to F8RCRegclass.
  11551. assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
  11552. (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
  11553. "Unsupported RegClass.");
  11554. }
  11555. MachineFrameInfo &MFI = F->getFrameInfo();
  11556. int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
  11557. MachineMemOperand *MMOStore = F->getMachineMemOperand(
  11558. MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
  11559. MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
  11560. MFI.getObjectAlign(FrameIdx));
  11561. // Store the SrcReg into the stack.
  11562. BuildMI(*BB, MI, dl, TII->get(StoreOp))
  11563. .addReg(SrcReg)
  11564. .addImm(0)
  11565. .addFrameIndex(FrameIdx)
  11566. .addMemOperand(MMOStore);
  11567. MachineMemOperand *MMOLoad = F->getMachineMemOperand(
  11568. MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
  11569. MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
  11570. MFI.getObjectAlign(FrameIdx));
  11571. // Load from the stack where SrcReg is stored, and save to DestReg,
  11572. // so we have done the RegClass conversion from RegClass::SrcReg to
  11573. // RegClass::DestReg.
  11574. BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
  11575. .addImm(0)
  11576. .addFrameIndex(FrameIdx)
  11577. .addMemOperand(MMOLoad);
  11578. }
  11579. };
  11580. Register OldFPSCRReg = MI.getOperand(0).getReg();
  11581. // Save FPSCR value.
  11582. BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
  11583. // When the operand is gprc register, use two least significant bits of the
  11584. // register and mtfsf instruction to set the bits 62:63 of FPSCR.
  11585. //
  11586. // copy OldFPSCRTmpReg, OldFPSCRReg
  11587. // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
  11588. // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
  11589. // copy NewFPSCRReg, NewFPSCRTmpReg
  11590. // mtfsf 255, NewFPSCRReg
  11591. MachineOperand SrcOp = MI.getOperand(1);
  11592. MachineRegisterInfo &RegInfo = F->getRegInfo();
  11593. Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
  11594. copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
  11595. Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
  11596. Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
  11597. // The first operand of INSERT_SUBREG should be a register which has
  11598. // subregisters, we only care about its RegClass, so we should use an
  11599. // IMPLICIT_DEF register.
  11600. BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
  11601. BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
  11602. .addReg(ImDefReg)
  11603. .add(SrcOp)
  11604. .addImm(1);
  11605. Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
  11606. BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
  11607. .addReg(OldFPSCRTmpReg)
  11608. .addReg(ExtSrcReg)
  11609. .addImm(0)
  11610. .addImm(62);
  11611. Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
  11612. copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
  11613. // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
  11614. // bits of FPSCR.
  11615. BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
  11616. .addImm(255)
  11617. .addReg(NewFPSCRReg)
  11618. .addImm(0)
  11619. .addImm(0);
  11620. } else if (MI.getOpcode() == PPC::SETFLM) {
  11621. DebugLoc Dl = MI.getDebugLoc();
  11622. // Result of setflm is previous FPSCR content, so we need to save it first.
  11623. Register OldFPSCRReg = MI.getOperand(0).getReg();
  11624. if (MRI.use_empty(OldFPSCRReg))
  11625. BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
  11626. else
  11627. BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
  11628. // Put bits in 32:63 to FPSCR.
  11629. Register NewFPSCRReg = MI.getOperand(1).getReg();
  11630. BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
  11631. .addImm(255)
  11632. .addReg(NewFPSCRReg)
  11633. .addImm(0)
  11634. .addImm(0);
  11635. } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
  11636. MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
  11637. return emitProbedAlloca(MI, BB);
  11638. } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) {
  11639. DebugLoc DL = MI.getDebugLoc();
  11640. Register Src = MI.getOperand(2).getReg();
  11641. Register Lo = MI.getOperand(0).getReg();
  11642. Register Hi = MI.getOperand(1).getReg();
  11643. BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
  11644. .addDef(Lo)
  11645. .addUse(Src, 0, PPC::sub_gp8_x1);
  11646. BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
  11647. .addDef(Hi)
  11648. .addUse(Src, 0, PPC::sub_gp8_x0);
  11649. } else if (MI.getOpcode() == PPC::LQX_PSEUDO ||
  11650. MI.getOpcode() == PPC::STQX_PSEUDO) {
  11651. DebugLoc DL = MI.getDebugLoc();
  11652. // Ptr is used as the ptr_rc_no_r0 part
  11653. // of LQ/STQ's memory operand and adding result of RA and RB,
  11654. // so it has to be g8rc_and_g8rc_nox0.
  11655. Register Ptr =
  11656. F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
  11657. Register Val = MI.getOperand(0).getReg();
  11658. Register RA = MI.getOperand(1).getReg();
  11659. Register RB = MI.getOperand(2).getReg();
  11660. BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB);
  11661. BuildMI(*BB, MI, DL,
  11662. MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ)
  11663. : TII->get(PPC::STQ))
  11664. .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0)
  11665. .addImm(0)
  11666. .addReg(Ptr);
  11667. } else {
  11668. llvm_unreachable("Unexpected instr type to insert");
  11669. }
  11670. MI.eraseFromParent(); // The pseudo instruction is gone now.
  11671. return BB;
  11672. }
  11673. //===----------------------------------------------------------------------===//
  11674. // Target Optimization Hooks
  11675. //===----------------------------------------------------------------------===//
  11676. static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
  11677. // For the estimates, convergence is quadratic, so we essentially double the
  11678. // number of digits correct after every iteration. For both FRE and FRSQRTE,
  11679. // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
  11680. // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
  11681. int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
  11682. if (VT.getScalarType() == MVT::f64)
  11683. RefinementSteps++;
  11684. return RefinementSteps;
  11685. }
  11686. SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
  11687. const DenormalMode &Mode) const {
  11688. // We only have VSX Vector Test for software Square Root.
  11689. EVT VT = Op.getValueType();
  11690. if (!isTypeLegal(MVT::i1) ||
  11691. (VT != MVT::f64 &&
  11692. ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
  11693. return TargetLowering::getSqrtInputTest(Op, DAG, Mode);
  11694. SDLoc DL(Op);
  11695. // The output register of FTSQRT is CR field.
  11696. SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
  11697. // ftsqrt BF,FRB
  11698. // Let e_b be the unbiased exponent of the double-precision
  11699. // floating-point operand in register FRB.
  11700. // fe_flag is set to 1 if either of the following conditions occurs.
  11701. // - The double-precision floating-point operand in register FRB is a zero,
  11702. // a NaN, or an infinity, or a negative value.
  11703. // - e_b is less than or equal to -970.
  11704. // Otherwise fe_flag is set to 0.
  11705. // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
  11706. // not eligible for iteration. (zero/negative/infinity/nan or unbiased
  11707. // exponent is less than -970)
  11708. SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
  11709. return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
  11710. FTSQRT, SRIdxVal),
  11711. 0);
  11712. }
  11713. SDValue
  11714. PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
  11715. SelectionDAG &DAG) const {
  11716. // We only have VSX Vector Square Root.
  11717. EVT VT = Op.getValueType();
  11718. if (VT != MVT::f64 &&
  11719. ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
  11720. return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
  11721. return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
  11722. }
  11723. SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
  11724. int Enabled, int &RefinementSteps,
  11725. bool &UseOneConstNR,
  11726. bool Reciprocal) const {
  11727. EVT VT = Operand.getValueType();
  11728. if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
  11729. (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
  11730. (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
  11731. (VT == MVT::v2f64 && Subtarget.hasVSX())) {
  11732. if (RefinementSteps == ReciprocalEstimate::Unspecified)
  11733. RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
  11734. // The Newton-Raphson computation with a single constant does not provide
  11735. // enough accuracy on some CPUs.
  11736. UseOneConstNR = !Subtarget.needsTwoConstNR();
  11737. return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
  11738. }
  11739. return SDValue();
  11740. }
  11741. SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
  11742. int Enabled,
  11743. int &RefinementSteps) const {
  11744. EVT VT = Operand.getValueType();
  11745. if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
  11746. (VT == MVT::f64 && Subtarget.hasFRE()) ||
  11747. (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
  11748. (VT == MVT::v2f64 && Subtarget.hasVSX())) {
  11749. if (RefinementSteps == ReciprocalEstimate::Unspecified)
  11750. RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
  11751. return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
  11752. }
  11753. return SDValue();
  11754. }
  11755. unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
  11756. // Note: This functionality is used only when unsafe-fp-math is enabled, and
  11757. // on cores with reciprocal estimates (which are used when unsafe-fp-math is
  11758. // enabled for division), this functionality is redundant with the default
  11759. // combiner logic (once the division -> reciprocal/multiply transformation
  11760. // has taken place). As a result, this matters more for older cores than for
  11761. // newer ones.
  11762. // Combine multiple FDIVs with the same divisor into multiple FMULs by the
  11763. // reciprocal if there are two or more FDIVs (for embedded cores with only
  11764. // one FP pipeline) for three or more FDIVs (for generic OOO cores).
  11765. switch (Subtarget.getCPUDirective()) {
  11766. default:
  11767. return 3;
  11768. case PPC::DIR_440:
  11769. case PPC::DIR_A2:
  11770. case PPC::DIR_E500:
  11771. case PPC::DIR_E500mc:
  11772. case PPC::DIR_E5500:
  11773. return 2;
  11774. }
  11775. }
  11776. // isConsecutiveLSLoc needs to work even if all adds have not yet been
  11777. // collapsed, and so we need to look through chains of them.
  11778. static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
  11779. int64_t& Offset, SelectionDAG &DAG) {
  11780. if (DAG.isBaseWithConstantOffset(Loc)) {
  11781. Base = Loc.getOperand(0);
  11782. Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
  11783. // The base might itself be a base plus an offset, and if so, accumulate
  11784. // that as well.
  11785. getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
  11786. }
  11787. }
  11788. static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
  11789. unsigned Bytes, int Dist,
  11790. SelectionDAG &DAG) {
  11791. if (VT.getSizeInBits() / 8 != Bytes)
  11792. return false;
  11793. SDValue BaseLoc = Base->getBasePtr();
  11794. if (Loc.getOpcode() == ISD::FrameIndex) {
  11795. if (BaseLoc.getOpcode() != ISD::FrameIndex)
  11796. return false;
  11797. const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  11798. int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
  11799. int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
  11800. int FS = MFI.getObjectSize(FI);
  11801. int BFS = MFI.getObjectSize(BFI);
  11802. if (FS != BFS || FS != (int)Bytes) return false;
  11803. return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
  11804. }
  11805. SDValue Base1 = Loc, Base2 = BaseLoc;
  11806. int64_t Offset1 = 0, Offset2 = 0;
  11807. getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
  11808. getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
  11809. if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
  11810. return true;
  11811. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  11812. const GlobalValue *GV1 = nullptr;
  11813. const GlobalValue *GV2 = nullptr;
  11814. Offset1 = 0;
  11815. Offset2 = 0;
  11816. bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
  11817. bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
  11818. if (isGA1 && isGA2 && GV1 == GV2)
  11819. return Offset1 == (Offset2 + Dist*Bytes);
  11820. return false;
  11821. }
  11822. // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
  11823. // not enforce equality of the chain operands.
  11824. static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
  11825. unsigned Bytes, int Dist,
  11826. SelectionDAG &DAG) {
  11827. if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
  11828. EVT VT = LS->getMemoryVT();
  11829. SDValue Loc = LS->getBasePtr();
  11830. return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
  11831. }
  11832. if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
  11833. EVT VT;
  11834. switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
  11835. default: return false;
  11836. case Intrinsic::ppc_altivec_lvx:
  11837. case Intrinsic::ppc_altivec_lvxl:
  11838. case Intrinsic::ppc_vsx_lxvw4x:
  11839. case Intrinsic::ppc_vsx_lxvw4x_be:
  11840. VT = MVT::v4i32;
  11841. break;
  11842. case Intrinsic::ppc_vsx_lxvd2x:
  11843. case Intrinsic::ppc_vsx_lxvd2x_be:
  11844. VT = MVT::v2f64;
  11845. break;
  11846. case Intrinsic::ppc_altivec_lvebx:
  11847. VT = MVT::i8;
  11848. break;
  11849. case Intrinsic::ppc_altivec_lvehx:
  11850. VT = MVT::i16;
  11851. break;
  11852. case Intrinsic::ppc_altivec_lvewx:
  11853. VT = MVT::i32;
  11854. break;
  11855. }
  11856. return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
  11857. }
  11858. if (N->getOpcode() == ISD::INTRINSIC_VOID) {
  11859. EVT VT;
  11860. switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
  11861. default: return false;
  11862. case Intrinsic::ppc_altivec_stvx:
  11863. case Intrinsic::ppc_altivec_stvxl:
  11864. case Intrinsic::ppc_vsx_stxvw4x:
  11865. VT = MVT::v4i32;
  11866. break;
  11867. case Intrinsic::ppc_vsx_stxvd2x:
  11868. VT = MVT::v2f64;
  11869. break;
  11870. case Intrinsic::ppc_vsx_stxvw4x_be:
  11871. VT = MVT::v4i32;
  11872. break;
  11873. case Intrinsic::ppc_vsx_stxvd2x_be:
  11874. VT = MVT::v2f64;
  11875. break;
  11876. case Intrinsic::ppc_altivec_stvebx:
  11877. VT = MVT::i8;
  11878. break;
  11879. case Intrinsic::ppc_altivec_stvehx:
  11880. VT = MVT::i16;
  11881. break;
  11882. case Intrinsic::ppc_altivec_stvewx:
  11883. VT = MVT::i32;
  11884. break;
  11885. }
  11886. return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
  11887. }
  11888. return false;
  11889. }
  11890. // Return true is there is a nearyby consecutive load to the one provided
  11891. // (regardless of alignment). We search up and down the chain, looking though
  11892. // token factors and other loads (but nothing else). As a result, a true result
  11893. // indicates that it is safe to create a new consecutive load adjacent to the
  11894. // load provided.
  11895. static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
  11896. SDValue Chain = LD->getChain();
  11897. EVT VT = LD->getMemoryVT();
  11898. SmallSet<SDNode *, 16> LoadRoots;
  11899. SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
  11900. SmallSet<SDNode *, 16> Visited;
  11901. // First, search up the chain, branching to follow all token-factor operands.
  11902. // If we find a consecutive load, then we're done, otherwise, record all
  11903. // nodes just above the top-level loads and token factors.
  11904. while (!Queue.empty()) {
  11905. SDNode *ChainNext = Queue.pop_back_val();
  11906. if (!Visited.insert(ChainNext).second)
  11907. continue;
  11908. if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
  11909. if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
  11910. return true;
  11911. if (!Visited.count(ChainLD->getChain().getNode()))
  11912. Queue.push_back(ChainLD->getChain().getNode());
  11913. } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
  11914. for (const SDUse &O : ChainNext->ops())
  11915. if (!Visited.count(O.getNode()))
  11916. Queue.push_back(O.getNode());
  11917. } else
  11918. LoadRoots.insert(ChainNext);
  11919. }
  11920. // Second, search down the chain, starting from the top-level nodes recorded
  11921. // in the first phase. These top-level nodes are the nodes just above all
  11922. // loads and token factors. Starting with their uses, recursively look though
  11923. // all loads (just the chain uses) and token factors to find a consecutive
  11924. // load.
  11925. Visited.clear();
  11926. Queue.clear();
  11927. for (SDNode *I : LoadRoots) {
  11928. Queue.push_back(I);
  11929. while (!Queue.empty()) {
  11930. SDNode *LoadRoot = Queue.pop_back_val();
  11931. if (!Visited.insert(LoadRoot).second)
  11932. continue;
  11933. if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
  11934. if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
  11935. return true;
  11936. for (SDNode *U : LoadRoot->uses())
  11937. if (((isa<MemSDNode>(U) &&
  11938. cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) ||
  11939. U->getOpcode() == ISD::TokenFactor) &&
  11940. !Visited.count(U))
  11941. Queue.push_back(U);
  11942. }
  11943. }
  11944. return false;
  11945. }
  11946. /// This function is called when we have proved that a SETCC node can be replaced
  11947. /// by subtraction (and other supporting instructions) so that the result of
  11948. /// comparison is kept in a GPR instead of CR. This function is purely for
  11949. /// codegen purposes and has some flags to guide the codegen process.
  11950. static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
  11951. bool Swap, SDLoc &DL, SelectionDAG &DAG) {
  11952. assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
  11953. // Zero extend the operands to the largest legal integer. Originally, they
  11954. // must be of a strictly smaller size.
  11955. auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
  11956. DAG.getConstant(Size, DL, MVT::i32));
  11957. auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
  11958. DAG.getConstant(Size, DL, MVT::i32));
  11959. // Swap if needed. Depends on the condition code.
  11960. if (Swap)
  11961. std::swap(Op0, Op1);
  11962. // Subtract extended integers.
  11963. auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
  11964. // Move the sign bit to the least significant position and zero out the rest.
  11965. // Now the least significant bit carries the result of original comparison.
  11966. auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
  11967. DAG.getConstant(Size - 1, DL, MVT::i32));
  11968. auto Final = Shifted;
  11969. // Complement the result if needed. Based on the condition code.
  11970. if (Complement)
  11971. Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
  11972. DAG.getConstant(1, DL, MVT::i64));
  11973. return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
  11974. }
  11975. SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
  11976. DAGCombinerInfo &DCI) const {
  11977. assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
  11978. SelectionDAG &DAG = DCI.DAG;
  11979. SDLoc DL(N);
  11980. // Size of integers being compared has a critical role in the following
  11981. // analysis, so we prefer to do this when all types are legal.
  11982. if (!DCI.isAfterLegalizeDAG())
  11983. return SDValue();
  11984. // If all users of SETCC extend its value to a legal integer type
  11985. // then we replace SETCC with a subtraction
  11986. for (const SDNode *U : N->uses())
  11987. if (U->getOpcode() != ISD::ZERO_EXTEND)
  11988. return SDValue();
  11989. ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
  11990. auto OpSize = N->getOperand(0).getValueSizeInBits();
  11991. unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
  11992. if (OpSize < Size) {
  11993. switch (CC) {
  11994. default: break;
  11995. case ISD::SETULT:
  11996. return generateEquivalentSub(N, Size, false, false, DL, DAG);
  11997. case ISD::SETULE:
  11998. return generateEquivalentSub(N, Size, true, true, DL, DAG);
  11999. case ISD::SETUGT:
  12000. return generateEquivalentSub(N, Size, false, true, DL, DAG);
  12001. case ISD::SETUGE:
  12002. return generateEquivalentSub(N, Size, true, false, DL, DAG);
  12003. }
  12004. }
  12005. return SDValue();
  12006. }
  12007. SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
  12008. DAGCombinerInfo &DCI) const {
  12009. SelectionDAG &DAG = DCI.DAG;
  12010. SDLoc dl(N);
  12011. assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
  12012. // If we're tracking CR bits, we need to be careful that we don't have:
  12013. // trunc(binary-ops(zext(x), zext(y)))
  12014. // or
  12015. // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
  12016. // such that we're unnecessarily moving things into GPRs when it would be
  12017. // better to keep them in CR bits.
  12018. // Note that trunc here can be an actual i1 trunc, or can be the effective
  12019. // truncation that comes from a setcc or select_cc.
  12020. if (N->getOpcode() == ISD::TRUNCATE &&
  12021. N->getValueType(0) != MVT::i1)
  12022. return SDValue();
  12023. if (N->getOperand(0).getValueType() != MVT::i32 &&
  12024. N->getOperand(0).getValueType() != MVT::i64)
  12025. return SDValue();
  12026. if (N->getOpcode() == ISD::SETCC ||
  12027. N->getOpcode() == ISD::SELECT_CC) {
  12028. // If we're looking at a comparison, then we need to make sure that the
  12029. // high bits (all except for the first) don't matter the result.
  12030. ISD::CondCode CC =
  12031. cast<CondCodeSDNode>(N->getOperand(
  12032. N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
  12033. unsigned OpBits = N->getOperand(0).getValueSizeInBits();
  12034. if (ISD::isSignedIntSetCC(CC)) {
  12035. if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
  12036. DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
  12037. return SDValue();
  12038. } else if (ISD::isUnsignedIntSetCC(CC)) {
  12039. if (!DAG.MaskedValueIsZero(N->getOperand(0),
  12040. APInt::getHighBitsSet(OpBits, OpBits-1)) ||
  12041. !DAG.MaskedValueIsZero(N->getOperand(1),
  12042. APInt::getHighBitsSet(OpBits, OpBits-1)))
  12043. return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
  12044. : SDValue());
  12045. } else {
  12046. // This is neither a signed nor an unsigned comparison, just make sure
  12047. // that the high bits are equal.
  12048. KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
  12049. KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
  12050. // We don't really care about what is known about the first bit (if
  12051. // anything), so pretend that it is known zero for both to ensure they can
  12052. // be compared as constants.
  12053. Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
  12054. Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
  12055. if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
  12056. Op1Known.getConstant() != Op2Known.getConstant())
  12057. return SDValue();
  12058. }
  12059. }
  12060. // We now know that the higher-order bits are irrelevant, we just need to
  12061. // make sure that all of the intermediate operations are bit operations, and
  12062. // all inputs are extensions.
  12063. if (N->getOperand(0).getOpcode() != ISD::AND &&
  12064. N->getOperand(0).getOpcode() != ISD::OR &&
  12065. N->getOperand(0).getOpcode() != ISD::XOR &&
  12066. N->getOperand(0).getOpcode() != ISD::SELECT &&
  12067. N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
  12068. N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
  12069. N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
  12070. N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
  12071. N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
  12072. return SDValue();
  12073. if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
  12074. N->getOperand(1).getOpcode() != ISD::AND &&
  12075. N->getOperand(1).getOpcode() != ISD::OR &&
  12076. N->getOperand(1).getOpcode() != ISD::XOR &&
  12077. N->getOperand(1).getOpcode() != ISD::SELECT &&
  12078. N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
  12079. N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
  12080. N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
  12081. N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
  12082. N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
  12083. return SDValue();
  12084. SmallVector<SDValue, 4> Inputs;
  12085. SmallVector<SDValue, 8> BinOps, PromOps;
  12086. SmallPtrSet<SDNode *, 16> Visited;
  12087. for (unsigned i = 0; i < 2; ++i) {
  12088. if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
  12089. N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
  12090. N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
  12091. N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
  12092. isa<ConstantSDNode>(N->getOperand(i)))
  12093. Inputs.push_back(N->getOperand(i));
  12094. else
  12095. BinOps.push_back(N->getOperand(i));
  12096. if (N->getOpcode() == ISD::TRUNCATE)
  12097. break;
  12098. }
  12099. // Visit all inputs, collect all binary operations (and, or, xor and
  12100. // select) that are all fed by extensions.
  12101. while (!BinOps.empty()) {
  12102. SDValue BinOp = BinOps.pop_back_val();
  12103. if (!Visited.insert(BinOp.getNode()).second)
  12104. continue;
  12105. PromOps.push_back(BinOp);
  12106. for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
  12107. // The condition of the select is not promoted.
  12108. if (BinOp.getOpcode() == ISD::SELECT && i == 0)
  12109. continue;
  12110. if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
  12111. continue;
  12112. if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
  12113. BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
  12114. BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
  12115. BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
  12116. isa<ConstantSDNode>(BinOp.getOperand(i))) {
  12117. Inputs.push_back(BinOp.getOperand(i));
  12118. } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
  12119. BinOp.getOperand(i).getOpcode() == ISD::OR ||
  12120. BinOp.getOperand(i).getOpcode() == ISD::XOR ||
  12121. BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
  12122. BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
  12123. BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
  12124. BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
  12125. BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
  12126. BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
  12127. BinOps.push_back(BinOp.getOperand(i));
  12128. } else {
  12129. // We have an input that is not an extension or another binary
  12130. // operation; we'll abort this transformation.
  12131. return SDValue();
  12132. }
  12133. }
  12134. }
  12135. // Make sure that this is a self-contained cluster of operations (which
  12136. // is not quite the same thing as saying that everything has only one
  12137. // use).
  12138. for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
  12139. if (isa<ConstantSDNode>(Inputs[i]))
  12140. continue;
  12141. for (const SDNode *User : Inputs[i].getNode()->uses()) {
  12142. if (User != N && !Visited.count(User))
  12143. return SDValue();
  12144. // Make sure that we're not going to promote the non-output-value
  12145. // operand(s) or SELECT or SELECT_CC.
  12146. // FIXME: Although we could sometimes handle this, and it does occur in
  12147. // practice that one of the condition inputs to the select is also one of
  12148. // the outputs, we currently can't deal with this.
  12149. if (User->getOpcode() == ISD::SELECT) {
  12150. if (User->getOperand(0) == Inputs[i])
  12151. return SDValue();
  12152. } else if (User->getOpcode() == ISD::SELECT_CC) {
  12153. if (User->getOperand(0) == Inputs[i] ||
  12154. User->getOperand(1) == Inputs[i])
  12155. return SDValue();
  12156. }
  12157. }
  12158. }
  12159. for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
  12160. for (const SDNode *User : PromOps[i].getNode()->uses()) {
  12161. if (User != N && !Visited.count(User))
  12162. return SDValue();
  12163. // Make sure that we're not going to promote the non-output-value
  12164. // operand(s) or SELECT or SELECT_CC.
  12165. // FIXME: Although we could sometimes handle this, and it does occur in
  12166. // practice that one of the condition inputs to the select is also one of
  12167. // the outputs, we currently can't deal with this.
  12168. if (User->getOpcode() == ISD::SELECT) {
  12169. if (User->getOperand(0) == PromOps[i])
  12170. return SDValue();
  12171. } else if (User->getOpcode() == ISD::SELECT_CC) {
  12172. if (User->getOperand(0) == PromOps[i] ||
  12173. User->getOperand(1) == PromOps[i])
  12174. return SDValue();
  12175. }
  12176. }
  12177. }
  12178. // Replace all inputs with the extension operand.
  12179. for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
  12180. // Constants may have users outside the cluster of to-be-promoted nodes,
  12181. // and so we need to replace those as we do the promotions.
  12182. if (isa<ConstantSDNode>(Inputs[i]))
  12183. continue;
  12184. else
  12185. DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
  12186. }
  12187. std::list<HandleSDNode> PromOpHandles;
  12188. for (auto &PromOp : PromOps)
  12189. PromOpHandles.emplace_back(PromOp);
  12190. // Replace all operations (these are all the same, but have a different
  12191. // (i1) return type). DAG.getNode will validate that the types of
  12192. // a binary operator match, so go through the list in reverse so that
  12193. // we've likely promoted both operands first. Any intermediate truncations or
  12194. // extensions disappear.
  12195. while (!PromOpHandles.empty()) {
  12196. SDValue PromOp = PromOpHandles.back().getValue();
  12197. PromOpHandles.pop_back();
  12198. if (PromOp.getOpcode() == ISD::TRUNCATE ||
  12199. PromOp.getOpcode() == ISD::SIGN_EXTEND ||
  12200. PromOp.getOpcode() == ISD::ZERO_EXTEND ||
  12201. PromOp.getOpcode() == ISD::ANY_EXTEND) {
  12202. if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
  12203. PromOp.getOperand(0).getValueType() != MVT::i1) {
  12204. // The operand is not yet ready (see comment below).
  12205. PromOpHandles.emplace_front(PromOp);
  12206. continue;
  12207. }
  12208. SDValue RepValue = PromOp.getOperand(0);
  12209. if (isa<ConstantSDNode>(RepValue))
  12210. RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
  12211. DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
  12212. continue;
  12213. }
  12214. unsigned C;
  12215. switch (PromOp.getOpcode()) {
  12216. default: C = 0; break;
  12217. case ISD::SELECT: C = 1; break;
  12218. case ISD::SELECT_CC: C = 2; break;
  12219. }
  12220. if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
  12221. PromOp.getOperand(C).getValueType() != MVT::i1) ||
  12222. (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
  12223. PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
  12224. // The to-be-promoted operands of this node have not yet been
  12225. // promoted (this should be rare because we're going through the
  12226. // list backward, but if one of the operands has several users in
  12227. // this cluster of to-be-promoted nodes, it is possible).
  12228. PromOpHandles.emplace_front(PromOp);
  12229. continue;
  12230. }
  12231. SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
  12232. PromOp.getNode()->op_end());
  12233. // If there are any constant inputs, make sure they're replaced now.
  12234. for (unsigned i = 0; i < 2; ++i)
  12235. if (isa<ConstantSDNode>(Ops[C+i]))
  12236. Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
  12237. DAG.ReplaceAllUsesOfValueWith(PromOp,
  12238. DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
  12239. }
  12240. // Now we're left with the initial truncation itself.
  12241. if (N->getOpcode() == ISD::TRUNCATE)
  12242. return N->getOperand(0);
  12243. // Otherwise, this is a comparison. The operands to be compared have just
  12244. // changed type (to i1), but everything else is the same.
  12245. return SDValue(N, 0);
  12246. }
  12247. SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
  12248. DAGCombinerInfo &DCI) const {
  12249. SelectionDAG &DAG = DCI.DAG;
  12250. SDLoc dl(N);
  12251. // If we're tracking CR bits, we need to be careful that we don't have:
  12252. // zext(binary-ops(trunc(x), trunc(y)))
  12253. // or
  12254. // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
  12255. // such that we're unnecessarily moving things into CR bits that can more
  12256. // efficiently stay in GPRs. Note that if we're not certain that the high
  12257. // bits are set as required by the final extension, we still may need to do
  12258. // some masking to get the proper behavior.
  12259. // This same functionality is important on PPC64 when dealing with
  12260. // 32-to-64-bit extensions; these occur often when 32-bit values are used as
  12261. // the return values of functions. Because it is so similar, it is handled
  12262. // here as well.
  12263. if (N->getValueType(0) != MVT::i32 &&
  12264. N->getValueType(0) != MVT::i64)
  12265. return SDValue();
  12266. if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
  12267. (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
  12268. return SDValue();
  12269. if (N->getOperand(0).getOpcode() != ISD::AND &&
  12270. N->getOperand(0).getOpcode() != ISD::OR &&
  12271. N->getOperand(0).getOpcode() != ISD::XOR &&
  12272. N->getOperand(0).getOpcode() != ISD::SELECT &&
  12273. N->getOperand(0).getOpcode() != ISD::SELECT_CC)
  12274. return SDValue();
  12275. SmallVector<SDValue, 4> Inputs;
  12276. SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
  12277. SmallPtrSet<SDNode *, 16> Visited;
  12278. // Visit all inputs, collect all binary operations (and, or, xor and
  12279. // select) that are all fed by truncations.
  12280. while (!BinOps.empty()) {
  12281. SDValue BinOp = BinOps.pop_back_val();
  12282. if (!Visited.insert(BinOp.getNode()).second)
  12283. continue;
  12284. PromOps.push_back(BinOp);
  12285. for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
  12286. // The condition of the select is not promoted.
  12287. if (BinOp.getOpcode() == ISD::SELECT && i == 0)
  12288. continue;
  12289. if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
  12290. continue;
  12291. if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
  12292. isa<ConstantSDNode>(BinOp.getOperand(i))) {
  12293. Inputs.push_back(BinOp.getOperand(i));
  12294. } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
  12295. BinOp.getOperand(i).getOpcode() == ISD::OR ||
  12296. BinOp.getOperand(i).getOpcode() == ISD::XOR ||
  12297. BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
  12298. BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
  12299. BinOps.push_back(BinOp.getOperand(i));
  12300. } else {
  12301. // We have an input that is not a truncation or another binary
  12302. // operation; we'll abort this transformation.
  12303. return SDValue();
  12304. }
  12305. }
  12306. }
  12307. // The operands of a select that must be truncated when the select is
  12308. // promoted because the operand is actually part of the to-be-promoted set.
  12309. DenseMap<SDNode *, EVT> SelectTruncOp[2];
  12310. // Make sure that this is a self-contained cluster of operations (which
  12311. // is not quite the same thing as saying that everything has only one
  12312. // use).
  12313. for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
  12314. if (isa<ConstantSDNode>(Inputs[i]))
  12315. continue;
  12316. for (SDNode *User : Inputs[i].getNode()->uses()) {
  12317. if (User != N && !Visited.count(User))
  12318. return SDValue();
  12319. // If we're going to promote the non-output-value operand(s) or SELECT or
  12320. // SELECT_CC, record them for truncation.
  12321. if (User->getOpcode() == ISD::SELECT) {
  12322. if (User->getOperand(0) == Inputs[i])
  12323. SelectTruncOp[0].insert(std::make_pair(User,
  12324. User->getOperand(0).getValueType()));
  12325. } else if (User->getOpcode() == ISD::SELECT_CC) {
  12326. if (User->getOperand(0) == Inputs[i])
  12327. SelectTruncOp[0].insert(std::make_pair(User,
  12328. User->getOperand(0).getValueType()));
  12329. if (User->getOperand(1) == Inputs[i])
  12330. SelectTruncOp[1].insert(std::make_pair(User,
  12331. User->getOperand(1).getValueType()));
  12332. }
  12333. }
  12334. }
  12335. for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
  12336. for (SDNode *User : PromOps[i].getNode()->uses()) {
  12337. if (User != N && !Visited.count(User))
  12338. return SDValue();
  12339. // If we're going to promote the non-output-value operand(s) or SELECT or
  12340. // SELECT_CC, record them for truncation.
  12341. if (User->getOpcode() == ISD::SELECT) {
  12342. if (User->getOperand(0) == PromOps[i])
  12343. SelectTruncOp[0].insert(std::make_pair(User,
  12344. User->getOperand(0).getValueType()));
  12345. } else if (User->getOpcode() == ISD::SELECT_CC) {
  12346. if (User->getOperand(0) == PromOps[i])
  12347. SelectTruncOp[0].insert(std::make_pair(User,
  12348. User->getOperand(0).getValueType()));
  12349. if (User->getOperand(1) == PromOps[i])
  12350. SelectTruncOp[1].insert(std::make_pair(User,
  12351. User->getOperand(1).getValueType()));
  12352. }
  12353. }
  12354. }
  12355. unsigned PromBits = N->getOperand(0).getValueSizeInBits();
  12356. bool ReallyNeedsExt = false;
  12357. if (N->getOpcode() != ISD::ANY_EXTEND) {
  12358. // If all of the inputs are not already sign/zero extended, then
  12359. // we'll still need to do that at the end.
  12360. for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
  12361. if (isa<ConstantSDNode>(Inputs[i]))
  12362. continue;
  12363. unsigned OpBits =
  12364. Inputs[i].getOperand(0).getValueSizeInBits();
  12365. assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
  12366. if ((N->getOpcode() == ISD::ZERO_EXTEND &&
  12367. !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
  12368. APInt::getHighBitsSet(OpBits,
  12369. OpBits-PromBits))) ||
  12370. (N->getOpcode() == ISD::SIGN_EXTEND &&
  12371. DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
  12372. (OpBits-(PromBits-1)))) {
  12373. ReallyNeedsExt = true;
  12374. break;
  12375. }
  12376. }
  12377. }
  12378. // Replace all inputs, either with the truncation operand, or a
  12379. // truncation or extension to the final output type.
  12380. for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
  12381. // Constant inputs need to be replaced with the to-be-promoted nodes that
  12382. // use them because they might have users outside of the cluster of
  12383. // promoted nodes.
  12384. if (isa<ConstantSDNode>(Inputs[i]))
  12385. continue;
  12386. SDValue InSrc = Inputs[i].getOperand(0);
  12387. if (Inputs[i].getValueType() == N->getValueType(0))
  12388. DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
  12389. else if (N->getOpcode() == ISD::SIGN_EXTEND)
  12390. DAG.ReplaceAllUsesOfValueWith(Inputs[i],
  12391. DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
  12392. else if (N->getOpcode() == ISD::ZERO_EXTEND)
  12393. DAG.ReplaceAllUsesOfValueWith(Inputs[i],
  12394. DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
  12395. else
  12396. DAG.ReplaceAllUsesOfValueWith(Inputs[i],
  12397. DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
  12398. }
  12399. std::list<HandleSDNode> PromOpHandles;
  12400. for (auto &PromOp : PromOps)
  12401. PromOpHandles.emplace_back(PromOp);
  12402. // Replace all operations (these are all the same, but have a different
  12403. // (promoted) return type). DAG.getNode will validate that the types of
  12404. // a binary operator match, so go through the list in reverse so that
  12405. // we've likely promoted both operands first.
  12406. while (!PromOpHandles.empty()) {
  12407. SDValue PromOp = PromOpHandles.back().getValue();
  12408. PromOpHandles.pop_back();
  12409. unsigned C;
  12410. switch (PromOp.getOpcode()) {
  12411. default: C = 0; break;
  12412. case ISD::SELECT: C = 1; break;
  12413. case ISD::SELECT_CC: C = 2; break;
  12414. }
  12415. if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
  12416. PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
  12417. (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
  12418. PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
  12419. // The to-be-promoted operands of this node have not yet been
  12420. // promoted (this should be rare because we're going through the
  12421. // list backward, but if one of the operands has several users in
  12422. // this cluster of to-be-promoted nodes, it is possible).
  12423. PromOpHandles.emplace_front(PromOp);
  12424. continue;
  12425. }
  12426. // For SELECT and SELECT_CC nodes, we do a similar check for any
  12427. // to-be-promoted comparison inputs.
  12428. if (PromOp.getOpcode() == ISD::SELECT ||
  12429. PromOp.getOpcode() == ISD::SELECT_CC) {
  12430. if ((SelectTruncOp[0].count(PromOp.getNode()) &&
  12431. PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
  12432. (SelectTruncOp[1].count(PromOp.getNode()) &&
  12433. PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
  12434. PromOpHandles.emplace_front(PromOp);
  12435. continue;
  12436. }
  12437. }
  12438. SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
  12439. PromOp.getNode()->op_end());
  12440. // If this node has constant inputs, then they'll need to be promoted here.
  12441. for (unsigned i = 0; i < 2; ++i) {
  12442. if (!isa<ConstantSDNode>(Ops[C+i]))
  12443. continue;
  12444. if (Ops[C+i].getValueType() == N->getValueType(0))
  12445. continue;
  12446. if (N->getOpcode() == ISD::SIGN_EXTEND)
  12447. Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
  12448. else if (N->getOpcode() == ISD::ZERO_EXTEND)
  12449. Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
  12450. else
  12451. Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
  12452. }
  12453. // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
  12454. // truncate them again to the original value type.
  12455. if (PromOp.getOpcode() == ISD::SELECT ||
  12456. PromOp.getOpcode() == ISD::SELECT_CC) {
  12457. auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
  12458. if (SI0 != SelectTruncOp[0].end())
  12459. Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
  12460. auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
  12461. if (SI1 != SelectTruncOp[1].end())
  12462. Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
  12463. }
  12464. DAG.ReplaceAllUsesOfValueWith(PromOp,
  12465. DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
  12466. }
  12467. // Now we're left with the initial extension itself.
  12468. if (!ReallyNeedsExt)
  12469. return N->getOperand(0);
  12470. // To zero extend, just mask off everything except for the first bit (in the
  12471. // i1 case).
  12472. if (N->getOpcode() == ISD::ZERO_EXTEND)
  12473. return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
  12474. DAG.getConstant(APInt::getLowBitsSet(
  12475. N->getValueSizeInBits(0), PromBits),
  12476. dl, N->getValueType(0)));
  12477. assert(N->getOpcode() == ISD::SIGN_EXTEND &&
  12478. "Invalid extension type");
  12479. EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
  12480. SDValue ShiftCst =
  12481. DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
  12482. return DAG.getNode(
  12483. ISD::SRA, dl, N->getValueType(0),
  12484. DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
  12485. ShiftCst);
  12486. }
  12487. SDValue PPCTargetLowering::combineSetCC(SDNode *N,
  12488. DAGCombinerInfo &DCI) const {
  12489. assert(N->getOpcode() == ISD::SETCC &&
  12490. "Should be called with a SETCC node");
  12491. ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
  12492. if (CC == ISD::SETNE || CC == ISD::SETEQ) {
  12493. SDValue LHS = N->getOperand(0);
  12494. SDValue RHS = N->getOperand(1);
  12495. // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
  12496. if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
  12497. LHS.hasOneUse())
  12498. std::swap(LHS, RHS);
  12499. // x == 0-y --> x+y == 0
  12500. // x != 0-y --> x+y != 0
  12501. if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
  12502. RHS.hasOneUse()) {
  12503. SDLoc DL(N);
  12504. SelectionDAG &DAG = DCI.DAG;
  12505. EVT VT = N->getValueType(0);
  12506. EVT OpVT = LHS.getValueType();
  12507. SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
  12508. return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
  12509. }
  12510. }
  12511. return DAGCombineTruncBoolExt(N, DCI);
  12512. }
  12513. // Is this an extending load from an f32 to an f64?
  12514. static bool isFPExtLoad(SDValue Op) {
  12515. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
  12516. return LD->getExtensionType() == ISD::EXTLOAD &&
  12517. Op.getValueType() == MVT::f64;
  12518. return false;
  12519. }
  12520. /// Reduces the number of fp-to-int conversion when building a vector.
  12521. ///
  12522. /// If this vector is built out of floating to integer conversions,
  12523. /// transform it to a vector built out of floating point values followed by a
  12524. /// single floating to integer conversion of the vector.
  12525. /// Namely (build_vector (fptosi $A), (fptosi $B), ...)
  12526. /// becomes (fptosi (build_vector ($A, $B, ...)))
  12527. SDValue PPCTargetLowering::
  12528. combineElementTruncationToVectorTruncation(SDNode *N,
  12529. DAGCombinerInfo &DCI) const {
  12530. assert(N->getOpcode() == ISD::BUILD_VECTOR &&
  12531. "Should be called with a BUILD_VECTOR node");
  12532. SelectionDAG &DAG = DCI.DAG;
  12533. SDLoc dl(N);
  12534. SDValue FirstInput = N->getOperand(0);
  12535. assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
  12536. "The input operand must be an fp-to-int conversion.");
  12537. // This combine happens after legalization so the fp_to_[su]i nodes are
  12538. // already converted to PPCSISD nodes.
  12539. unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
  12540. if (FirstConversion == PPCISD::FCTIDZ ||
  12541. FirstConversion == PPCISD::FCTIDUZ ||
  12542. FirstConversion == PPCISD::FCTIWZ ||
  12543. FirstConversion == PPCISD::FCTIWUZ) {
  12544. bool IsSplat = true;
  12545. bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
  12546. FirstConversion == PPCISD::FCTIWUZ;
  12547. EVT SrcVT = FirstInput.getOperand(0).getValueType();
  12548. SmallVector<SDValue, 4> Ops;
  12549. EVT TargetVT = N->getValueType(0);
  12550. for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
  12551. SDValue NextOp = N->getOperand(i);
  12552. if (NextOp.getOpcode() != PPCISD::MFVSR)
  12553. return SDValue();
  12554. unsigned NextConversion = NextOp.getOperand(0).getOpcode();
  12555. if (NextConversion != FirstConversion)
  12556. return SDValue();
  12557. // If we are converting to 32-bit integers, we need to add an FP_ROUND.
  12558. // This is not valid if the input was originally double precision. It is
  12559. // also not profitable to do unless this is an extending load in which
  12560. // case doing this combine will allow us to combine consecutive loads.
  12561. if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
  12562. return SDValue();
  12563. if (N->getOperand(i) != FirstInput)
  12564. IsSplat = false;
  12565. }
  12566. // If this is a splat, we leave it as-is since there will be only a single
  12567. // fp-to-int conversion followed by a splat of the integer. This is better
  12568. // for 32-bit and smaller ints and neutral for 64-bit ints.
  12569. if (IsSplat)
  12570. return SDValue();
  12571. // Now that we know we have the right type of node, get its operands
  12572. for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
  12573. SDValue In = N->getOperand(i).getOperand(0);
  12574. if (Is32Bit) {
  12575. // For 32-bit values, we need to add an FP_ROUND node (if we made it
  12576. // here, we know that all inputs are extending loads so this is safe).
  12577. if (In.isUndef())
  12578. Ops.push_back(DAG.getUNDEF(SrcVT));
  12579. else {
  12580. SDValue Trunc =
  12581. DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, In.getOperand(0),
  12582. DAG.getIntPtrConstant(1, dl, /*isTarget=*/true));
  12583. Ops.push_back(Trunc);
  12584. }
  12585. } else
  12586. Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
  12587. }
  12588. unsigned Opcode;
  12589. if (FirstConversion == PPCISD::FCTIDZ ||
  12590. FirstConversion == PPCISD::FCTIWZ)
  12591. Opcode = ISD::FP_TO_SINT;
  12592. else
  12593. Opcode = ISD::FP_TO_UINT;
  12594. EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
  12595. SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
  12596. return DAG.getNode(Opcode, dl, TargetVT, BV);
  12597. }
  12598. return SDValue();
  12599. }
  12600. /// Reduce the number of loads when building a vector.
  12601. ///
  12602. /// Building a vector out of multiple loads can be converted to a load
  12603. /// of the vector type if the loads are consecutive. If the loads are
  12604. /// consecutive but in descending order, a shuffle is added at the end
  12605. /// to reorder the vector.
  12606. static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
  12607. assert(N->getOpcode() == ISD::BUILD_VECTOR &&
  12608. "Should be called with a BUILD_VECTOR node");
  12609. SDLoc dl(N);
  12610. // Return early for non byte-sized type, as they can't be consecutive.
  12611. if (!N->getValueType(0).getVectorElementType().isByteSized())
  12612. return SDValue();
  12613. bool InputsAreConsecutiveLoads = true;
  12614. bool InputsAreReverseConsecutive = true;
  12615. unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
  12616. SDValue FirstInput = N->getOperand(0);
  12617. bool IsRoundOfExtLoad = false;
  12618. LoadSDNode *FirstLoad = nullptr;
  12619. if (FirstInput.getOpcode() == ISD::FP_ROUND &&
  12620. FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
  12621. FirstLoad = cast<LoadSDNode>(FirstInput.getOperand(0));
  12622. IsRoundOfExtLoad = FirstLoad->getExtensionType() == ISD::EXTLOAD;
  12623. }
  12624. // Not a build vector of (possibly fp_rounded) loads.
  12625. if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
  12626. N->getNumOperands() == 1)
  12627. return SDValue();
  12628. if (!IsRoundOfExtLoad)
  12629. FirstLoad = cast<LoadSDNode>(FirstInput);
  12630. SmallVector<LoadSDNode *, 4> InputLoads;
  12631. InputLoads.push_back(FirstLoad);
  12632. for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
  12633. // If any inputs are fp_round(extload), they all must be.
  12634. if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
  12635. return SDValue();
  12636. SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
  12637. N->getOperand(i);
  12638. if (NextInput.getOpcode() != ISD::LOAD)
  12639. return SDValue();
  12640. SDValue PreviousInput =
  12641. IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
  12642. LoadSDNode *LD1 = cast<LoadSDNode>(PreviousInput);
  12643. LoadSDNode *LD2 = cast<LoadSDNode>(NextInput);
  12644. // If any inputs are fp_round(extload), they all must be.
  12645. if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
  12646. return SDValue();
  12647. // We only care about regular loads. The PPC-specific load intrinsics
  12648. // will not lead to a merge opportunity.
  12649. if (!DAG.areNonVolatileConsecutiveLoads(LD2, LD1, ElemSize, 1))
  12650. InputsAreConsecutiveLoads = false;
  12651. if (!DAG.areNonVolatileConsecutiveLoads(LD1, LD2, ElemSize, 1))
  12652. InputsAreReverseConsecutive = false;
  12653. // Exit early if the loads are neither consecutive nor reverse consecutive.
  12654. if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
  12655. return SDValue();
  12656. InputLoads.push_back(LD2);
  12657. }
  12658. assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
  12659. "The loads cannot be both consecutive and reverse consecutive.");
  12660. SDValue WideLoad;
  12661. SDValue ReturnSDVal;
  12662. if (InputsAreConsecutiveLoads) {
  12663. assert(FirstLoad && "Input needs to be a LoadSDNode.");
  12664. WideLoad = DAG.getLoad(N->getValueType(0), dl, FirstLoad->getChain(),
  12665. FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
  12666. FirstLoad->getAlign());
  12667. ReturnSDVal = WideLoad;
  12668. } else if (InputsAreReverseConsecutive) {
  12669. LoadSDNode *LastLoad = InputLoads.back();
  12670. assert(LastLoad && "Input needs to be a LoadSDNode.");
  12671. WideLoad = DAG.getLoad(N->getValueType(0), dl, LastLoad->getChain(),
  12672. LastLoad->getBasePtr(), LastLoad->getPointerInfo(),
  12673. LastLoad->getAlign());
  12674. SmallVector<int, 16> Ops;
  12675. for (int i = N->getNumOperands() - 1; i >= 0; i--)
  12676. Ops.push_back(i);
  12677. ReturnSDVal = DAG.getVectorShuffle(N->getValueType(0), dl, WideLoad,
  12678. DAG.getUNDEF(N->getValueType(0)), Ops);
  12679. } else
  12680. return SDValue();
  12681. for (auto *LD : InputLoads)
  12682. DAG.makeEquivalentMemoryOrdering(LD, WideLoad);
  12683. return ReturnSDVal;
  12684. }
  12685. // This function adds the required vector_shuffle needed to get
  12686. // the elements of the vector extract in the correct position
  12687. // as specified by the CorrectElems encoding.
  12688. static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
  12689. SDValue Input, uint64_t Elems,
  12690. uint64_t CorrectElems) {
  12691. SDLoc dl(N);
  12692. unsigned NumElems = Input.getValueType().getVectorNumElements();
  12693. SmallVector<int, 16> ShuffleMask(NumElems, -1);
  12694. // Knowing the element indices being extracted from the original
  12695. // vector and the order in which they're being inserted, just put
  12696. // them at element indices required for the instruction.
  12697. for (unsigned i = 0; i < N->getNumOperands(); i++) {
  12698. if (DAG.getDataLayout().isLittleEndian())
  12699. ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
  12700. else
  12701. ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
  12702. CorrectElems = CorrectElems >> 8;
  12703. Elems = Elems >> 8;
  12704. }
  12705. SDValue Shuffle =
  12706. DAG.getVectorShuffle(Input.getValueType(), dl, Input,
  12707. DAG.getUNDEF(Input.getValueType()), ShuffleMask);
  12708. EVT VT = N->getValueType(0);
  12709. SDValue Conv = DAG.getBitcast(VT, Shuffle);
  12710. EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
  12711. Input.getValueType().getVectorElementType(),
  12712. VT.getVectorNumElements());
  12713. return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
  12714. DAG.getValueType(ExtVT));
  12715. }
  12716. // Look for build vector patterns where input operands come from sign
  12717. // extended vector_extract elements of specific indices. If the correct indices
  12718. // aren't used, add a vector shuffle to fix up the indices and create
  12719. // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
  12720. // during instruction selection.
  12721. static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
  12722. // This array encodes the indices that the vector sign extend instructions
  12723. // extract from when extending from one type to another for both BE and LE.
  12724. // The right nibble of each byte corresponds to the LE incides.
  12725. // and the left nibble of each byte corresponds to the BE incides.
  12726. // For example: 0x3074B8FC byte->word
  12727. // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
  12728. // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
  12729. // For example: 0x000070F8 byte->double word
  12730. // For LE: the allowed indices are: 0x0,0x8
  12731. // For BE: the allowed indices are: 0x7,0xF
  12732. uint64_t TargetElems[] = {
  12733. 0x3074B8FC, // b->w
  12734. 0x000070F8, // b->d
  12735. 0x10325476, // h->w
  12736. 0x00003074, // h->d
  12737. 0x00001032, // w->d
  12738. };
  12739. uint64_t Elems = 0;
  12740. int Index;
  12741. SDValue Input;
  12742. auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
  12743. if (!Op)
  12744. return false;
  12745. if (Op.getOpcode() != ISD::SIGN_EXTEND &&
  12746. Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
  12747. return false;
  12748. // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
  12749. // of the right width.
  12750. SDValue Extract = Op.getOperand(0);
  12751. if (Extract.getOpcode() == ISD::ANY_EXTEND)
  12752. Extract = Extract.getOperand(0);
  12753. if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
  12754. return false;
  12755. ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
  12756. if (!ExtOp)
  12757. return false;
  12758. Index = ExtOp->getZExtValue();
  12759. if (Input && Input != Extract.getOperand(0))
  12760. return false;
  12761. if (!Input)
  12762. Input = Extract.getOperand(0);
  12763. Elems = Elems << 8;
  12764. Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
  12765. Elems |= Index;
  12766. return true;
  12767. };
  12768. // If the build vector operands aren't sign extended vector extracts,
  12769. // of the same input vector, then return.
  12770. for (unsigned i = 0; i < N->getNumOperands(); i++) {
  12771. if (!isSExtOfVecExtract(N->getOperand(i))) {
  12772. return SDValue();
  12773. }
  12774. }
  12775. // If the vector extract indicies are not correct, add the appropriate
  12776. // vector_shuffle.
  12777. int TgtElemArrayIdx;
  12778. int InputSize = Input.getValueType().getScalarSizeInBits();
  12779. int OutputSize = N->getValueType(0).getScalarSizeInBits();
  12780. if (InputSize + OutputSize == 40)
  12781. TgtElemArrayIdx = 0;
  12782. else if (InputSize + OutputSize == 72)
  12783. TgtElemArrayIdx = 1;
  12784. else if (InputSize + OutputSize == 48)
  12785. TgtElemArrayIdx = 2;
  12786. else if (InputSize + OutputSize == 80)
  12787. TgtElemArrayIdx = 3;
  12788. else if (InputSize + OutputSize == 96)
  12789. TgtElemArrayIdx = 4;
  12790. else
  12791. return SDValue();
  12792. uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
  12793. CorrectElems = DAG.getDataLayout().isLittleEndian()
  12794. ? CorrectElems & 0x0F0F0F0F0F0F0F0F
  12795. : CorrectElems & 0xF0F0F0F0F0F0F0F0;
  12796. if (Elems != CorrectElems) {
  12797. return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
  12798. }
  12799. // Regular lowering will catch cases where a shuffle is not needed.
  12800. return SDValue();
  12801. }
  12802. // Look for the pattern of a load from a narrow width to i128, feeding
  12803. // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
  12804. // (LXVRZX). This node represents a zero extending load that will be matched
  12805. // to the Load VSX Vector Rightmost instructions.
  12806. static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
  12807. SDLoc DL(N);
  12808. // This combine is only eligible for a BUILD_VECTOR of v1i128.
  12809. if (N->getValueType(0) != MVT::v1i128)
  12810. return SDValue();
  12811. SDValue Operand = N->getOperand(0);
  12812. // Proceed with the transformation if the operand to the BUILD_VECTOR
  12813. // is a load instruction.
  12814. if (Operand.getOpcode() != ISD::LOAD)
  12815. return SDValue();
  12816. auto *LD = cast<LoadSDNode>(Operand);
  12817. EVT MemoryType = LD->getMemoryVT();
  12818. // This transformation is only valid if the we are loading either a byte,
  12819. // halfword, word, or doubleword.
  12820. bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
  12821. MemoryType == MVT::i32 || MemoryType == MVT::i64;
  12822. // Ensure that the load from the narrow width is being zero extended to i128.
  12823. if (!ValidLDType ||
  12824. (LD->getExtensionType() != ISD::ZEXTLOAD &&
  12825. LD->getExtensionType() != ISD::EXTLOAD))
  12826. return SDValue();
  12827. SDValue LoadOps[] = {
  12828. LD->getChain(), LD->getBasePtr(),
  12829. DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
  12830. return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
  12831. DAG.getVTList(MVT::v1i128, MVT::Other),
  12832. LoadOps, MemoryType, LD->getMemOperand());
  12833. }
  12834. SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
  12835. DAGCombinerInfo &DCI) const {
  12836. assert(N->getOpcode() == ISD::BUILD_VECTOR &&
  12837. "Should be called with a BUILD_VECTOR node");
  12838. SelectionDAG &DAG = DCI.DAG;
  12839. SDLoc dl(N);
  12840. if (!Subtarget.hasVSX())
  12841. return SDValue();
  12842. // The target independent DAG combiner will leave a build_vector of
  12843. // float-to-int conversions intact. We can generate MUCH better code for
  12844. // a float-to-int conversion of a vector of floats.
  12845. SDValue FirstInput = N->getOperand(0);
  12846. if (FirstInput.getOpcode() == PPCISD::MFVSR) {
  12847. SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
  12848. if (Reduced)
  12849. return Reduced;
  12850. }
  12851. // If we're building a vector out of consecutive loads, just load that
  12852. // vector type.
  12853. SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
  12854. if (Reduced)
  12855. return Reduced;
  12856. // If we're building a vector out of extended elements from another vector
  12857. // we have P9 vector integer extend instructions. The code assumes legal
  12858. // input types (i.e. it can't handle things like v4i16) so do not run before
  12859. // legalization.
  12860. if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
  12861. Reduced = combineBVOfVecSExt(N, DAG);
  12862. if (Reduced)
  12863. return Reduced;
  12864. }
  12865. // On Power10, the Load VSX Vector Rightmost instructions can be utilized
  12866. // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
  12867. // is a load from <valid narrow width> to i128.
  12868. if (Subtarget.isISA3_1()) {
  12869. SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
  12870. if (BVOfZLoad)
  12871. return BVOfZLoad;
  12872. }
  12873. if (N->getValueType(0) != MVT::v2f64)
  12874. return SDValue();
  12875. // Looking for:
  12876. // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
  12877. if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
  12878. FirstInput.getOpcode() != ISD::UINT_TO_FP)
  12879. return SDValue();
  12880. if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
  12881. N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
  12882. return SDValue();
  12883. if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
  12884. return SDValue();
  12885. SDValue Ext1 = FirstInput.getOperand(0);
  12886. SDValue Ext2 = N->getOperand(1).getOperand(0);
  12887. if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  12888. Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
  12889. return SDValue();
  12890. ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
  12891. ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
  12892. if (!Ext1Op || !Ext2Op)
  12893. return SDValue();
  12894. if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
  12895. Ext1.getOperand(0) != Ext2.getOperand(0))
  12896. return SDValue();
  12897. int FirstElem = Ext1Op->getZExtValue();
  12898. int SecondElem = Ext2Op->getZExtValue();
  12899. int SubvecIdx;
  12900. if (FirstElem == 0 && SecondElem == 1)
  12901. SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
  12902. else if (FirstElem == 2 && SecondElem == 3)
  12903. SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
  12904. else
  12905. return SDValue();
  12906. SDValue SrcVec = Ext1.getOperand(0);
  12907. auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
  12908. PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
  12909. return DAG.getNode(NodeType, dl, MVT::v2f64,
  12910. SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
  12911. }
  12912. SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
  12913. DAGCombinerInfo &DCI) const {
  12914. assert((N->getOpcode() == ISD::SINT_TO_FP ||
  12915. N->getOpcode() == ISD::UINT_TO_FP) &&
  12916. "Need an int -> FP conversion node here");
  12917. if (useSoftFloat() || !Subtarget.has64BitSupport())
  12918. return SDValue();
  12919. SelectionDAG &DAG = DCI.DAG;
  12920. SDLoc dl(N);
  12921. SDValue Op(N, 0);
  12922. // Don't handle ppc_fp128 here or conversions that are out-of-range capable
  12923. // from the hardware.
  12924. if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
  12925. return SDValue();
  12926. if (!Op.getOperand(0).getValueType().isSimple())
  12927. return SDValue();
  12928. if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
  12929. Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
  12930. return SDValue();
  12931. SDValue FirstOperand(Op.getOperand(0));
  12932. bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
  12933. (FirstOperand.getValueType() == MVT::i8 ||
  12934. FirstOperand.getValueType() == MVT::i16);
  12935. if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
  12936. bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
  12937. bool DstDouble = Op.getValueType() == MVT::f64;
  12938. unsigned ConvOp = Signed ?
  12939. (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) :
  12940. (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
  12941. SDValue WidthConst =
  12942. DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
  12943. dl, false);
  12944. LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
  12945. SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
  12946. SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
  12947. DAG.getVTList(MVT::f64, MVT::Other),
  12948. Ops, MVT::i8, LDN->getMemOperand());
  12949. // For signed conversion, we need to sign-extend the value in the VSR
  12950. if (Signed) {
  12951. SDValue ExtOps[] = { Ld, WidthConst };
  12952. SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
  12953. return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
  12954. } else
  12955. return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
  12956. }
  12957. // For i32 intermediate values, unfortunately, the conversion functions
  12958. // leave the upper 32 bits of the value are undefined. Within the set of
  12959. // scalar instructions, we have no method for zero- or sign-extending the
  12960. // value. Thus, we cannot handle i32 intermediate values here.
  12961. if (Op.getOperand(0).getValueType() == MVT::i32)
  12962. return SDValue();
  12963. assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
  12964. "UINT_TO_FP is supported only with FPCVT");
  12965. // If we have FCFIDS, then use it when converting to single-precision.
  12966. // Otherwise, convert to double-precision and then round.
  12967. unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
  12968. ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
  12969. : PPCISD::FCFIDS)
  12970. : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
  12971. : PPCISD::FCFID);
  12972. MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
  12973. ? MVT::f32
  12974. : MVT::f64;
  12975. // If we're converting from a float, to an int, and back to a float again,
  12976. // then we don't need the store/load pair at all.
  12977. if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
  12978. Subtarget.hasFPCVT()) ||
  12979. (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
  12980. SDValue Src = Op.getOperand(0).getOperand(0);
  12981. if (Src.getValueType() == MVT::f32) {
  12982. Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
  12983. DCI.AddToWorklist(Src.getNode());
  12984. } else if (Src.getValueType() != MVT::f64) {
  12985. // Make sure that we don't pick up a ppc_fp128 source value.
  12986. return SDValue();
  12987. }
  12988. unsigned FCTOp =
  12989. Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
  12990. PPCISD::FCTIDUZ;
  12991. SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
  12992. SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
  12993. if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
  12994. FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
  12995. DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
  12996. DCI.AddToWorklist(FP.getNode());
  12997. }
  12998. return FP;
  12999. }
  13000. return SDValue();
  13001. }
  13002. // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
  13003. // builtins) into loads with swaps.
  13004. SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
  13005. DAGCombinerInfo &DCI) const {
  13006. // Delay VSX load for LE combine until after LegalizeOps to prioritize other
  13007. // load combines.
  13008. if (DCI.isBeforeLegalizeOps())
  13009. return SDValue();
  13010. SelectionDAG &DAG = DCI.DAG;
  13011. SDLoc dl(N);
  13012. SDValue Chain;
  13013. SDValue Base;
  13014. MachineMemOperand *MMO;
  13015. switch (N->getOpcode()) {
  13016. default:
  13017. llvm_unreachable("Unexpected opcode for little endian VSX load");
  13018. case ISD::LOAD: {
  13019. LoadSDNode *LD = cast<LoadSDNode>(N);
  13020. Chain = LD->getChain();
  13021. Base = LD->getBasePtr();
  13022. MMO = LD->getMemOperand();
  13023. // If the MMO suggests this isn't a load of a full vector, leave
  13024. // things alone. For a built-in, we have to make the change for
  13025. // correctness, so if there is a size problem that will be a bug.
  13026. if (MMO->getSize() < 16)
  13027. return SDValue();
  13028. break;
  13029. }
  13030. case ISD::INTRINSIC_W_CHAIN: {
  13031. MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
  13032. Chain = Intrin->getChain();
  13033. // Similarly to the store case below, Intrin->getBasePtr() doesn't get
  13034. // us what we want. Get operand 2 instead.
  13035. Base = Intrin->getOperand(2);
  13036. MMO = Intrin->getMemOperand();
  13037. break;
  13038. }
  13039. }
  13040. MVT VecTy = N->getValueType(0).getSimpleVT();
  13041. SDValue LoadOps[] = { Chain, Base };
  13042. SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
  13043. DAG.getVTList(MVT::v2f64, MVT::Other),
  13044. LoadOps, MVT::v2f64, MMO);
  13045. DCI.AddToWorklist(Load.getNode());
  13046. Chain = Load.getValue(1);
  13047. SDValue Swap = DAG.getNode(
  13048. PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
  13049. DCI.AddToWorklist(Swap.getNode());
  13050. // Add a bitcast if the resulting load type doesn't match v2f64.
  13051. if (VecTy != MVT::v2f64) {
  13052. SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
  13053. DCI.AddToWorklist(N.getNode());
  13054. // Package {bitcast value, swap's chain} to match Load's shape.
  13055. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
  13056. N, Swap.getValue(1));
  13057. }
  13058. return Swap;
  13059. }
  13060. // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
  13061. // builtins) into stores with swaps.
  13062. SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
  13063. DAGCombinerInfo &DCI) const {
  13064. // Delay VSX store for LE combine until after LegalizeOps to prioritize other
  13065. // store combines.
  13066. if (DCI.isBeforeLegalizeOps())
  13067. return SDValue();
  13068. SelectionDAG &DAG = DCI.DAG;
  13069. SDLoc dl(N);
  13070. SDValue Chain;
  13071. SDValue Base;
  13072. unsigned SrcOpnd;
  13073. MachineMemOperand *MMO;
  13074. switch (N->getOpcode()) {
  13075. default:
  13076. llvm_unreachable("Unexpected opcode for little endian VSX store");
  13077. case ISD::STORE: {
  13078. StoreSDNode *ST = cast<StoreSDNode>(N);
  13079. Chain = ST->getChain();
  13080. Base = ST->getBasePtr();
  13081. MMO = ST->getMemOperand();
  13082. SrcOpnd = 1;
  13083. // If the MMO suggests this isn't a store of a full vector, leave
  13084. // things alone. For a built-in, we have to make the change for
  13085. // correctness, so if there is a size problem that will be a bug.
  13086. if (MMO->getSize() < 16)
  13087. return SDValue();
  13088. break;
  13089. }
  13090. case ISD::INTRINSIC_VOID: {
  13091. MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
  13092. Chain = Intrin->getChain();
  13093. // Intrin->getBasePtr() oddly does not get what we want.
  13094. Base = Intrin->getOperand(3);
  13095. MMO = Intrin->getMemOperand();
  13096. SrcOpnd = 2;
  13097. break;
  13098. }
  13099. }
  13100. SDValue Src = N->getOperand(SrcOpnd);
  13101. MVT VecTy = Src.getValueType().getSimpleVT();
  13102. // All stores are done as v2f64 and possible bit cast.
  13103. if (VecTy != MVT::v2f64) {
  13104. Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
  13105. DCI.AddToWorklist(Src.getNode());
  13106. }
  13107. SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
  13108. DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
  13109. DCI.AddToWorklist(Swap.getNode());
  13110. Chain = Swap.getValue(1);
  13111. SDValue StoreOps[] = { Chain, Swap, Base };
  13112. SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
  13113. DAG.getVTList(MVT::Other),
  13114. StoreOps, VecTy, MMO);
  13115. DCI.AddToWorklist(Store.getNode());
  13116. return Store;
  13117. }
  13118. // Handle DAG combine for STORE (FP_TO_INT F).
  13119. SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
  13120. DAGCombinerInfo &DCI) const {
  13121. SelectionDAG &DAG = DCI.DAG;
  13122. SDLoc dl(N);
  13123. unsigned Opcode = N->getOperand(1).getOpcode();
  13124. assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
  13125. && "Not a FP_TO_INT Instruction!");
  13126. SDValue Val = N->getOperand(1).getOperand(0);
  13127. EVT Op1VT = N->getOperand(1).getValueType();
  13128. EVT ResVT = Val.getValueType();
  13129. if (!isTypeLegal(ResVT))
  13130. return SDValue();
  13131. // Only perform combine for conversion to i64/i32 or power9 i16/i8.
  13132. bool ValidTypeForStoreFltAsInt =
  13133. (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
  13134. (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
  13135. if (ResVT == MVT::f128 && !Subtarget.hasP9Vector())
  13136. return SDValue();
  13137. if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
  13138. cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
  13139. return SDValue();
  13140. // Extend f32 values to f64
  13141. if (ResVT.getScalarSizeInBits() == 32) {
  13142. Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
  13143. DCI.AddToWorklist(Val.getNode());
  13144. }
  13145. // Set signed or unsigned conversion opcode.
  13146. unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
  13147. PPCISD::FP_TO_SINT_IN_VSR :
  13148. PPCISD::FP_TO_UINT_IN_VSR;
  13149. Val = DAG.getNode(ConvOpcode,
  13150. dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
  13151. DCI.AddToWorklist(Val.getNode());
  13152. // Set number of bytes being converted.
  13153. unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
  13154. SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
  13155. DAG.getIntPtrConstant(ByteSize, dl, false),
  13156. DAG.getValueType(Op1VT) };
  13157. Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
  13158. DAG.getVTList(MVT::Other), Ops,
  13159. cast<StoreSDNode>(N)->getMemoryVT(),
  13160. cast<StoreSDNode>(N)->getMemOperand());
  13161. DCI.AddToWorklist(Val.getNode());
  13162. return Val;
  13163. }
  13164. static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
  13165. // Check that the source of the element keeps flipping
  13166. // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
  13167. bool PrevElemFromFirstVec = Mask[0] < NumElts;
  13168. for (int i = 1, e = Mask.size(); i < e; i++) {
  13169. if (PrevElemFromFirstVec && Mask[i] < NumElts)
  13170. return false;
  13171. if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
  13172. return false;
  13173. PrevElemFromFirstVec = !PrevElemFromFirstVec;
  13174. }
  13175. return true;
  13176. }
  13177. static bool isSplatBV(SDValue Op) {
  13178. if (Op.getOpcode() != ISD::BUILD_VECTOR)
  13179. return false;
  13180. SDValue FirstOp;
  13181. // Find first non-undef input.
  13182. for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
  13183. FirstOp = Op.getOperand(i);
  13184. if (!FirstOp.isUndef())
  13185. break;
  13186. }
  13187. // All inputs are undef or the same as the first non-undef input.
  13188. for (int i = 1, e = Op.getNumOperands(); i < e; i++)
  13189. if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
  13190. return false;
  13191. return true;
  13192. }
  13193. static SDValue isScalarToVec(SDValue Op) {
  13194. if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
  13195. return Op;
  13196. if (Op.getOpcode() != ISD::BITCAST)
  13197. return SDValue();
  13198. Op = Op.getOperand(0);
  13199. if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
  13200. return Op;
  13201. return SDValue();
  13202. }
  13203. // Fix up the shuffle mask to account for the fact that the result of
  13204. // scalar_to_vector is not in lane zero. This just takes all values in
  13205. // the ranges specified by the min/max indices and adds the number of
  13206. // elements required to ensure each element comes from the respective
  13207. // position in the valid lane.
  13208. // On little endian, that's just the corresponding element in the other
  13209. // half of the vector. On big endian, it is in the same half but right
  13210. // justified rather than left justified in that half.
  13211. static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
  13212. int LHSMaxIdx, int RHSMinIdx,
  13213. int RHSMaxIdx, int HalfVec,
  13214. unsigned ValidLaneWidth,
  13215. const PPCSubtarget &Subtarget) {
  13216. for (int i = 0, e = ShuffV.size(); i < e; i++) {
  13217. int Idx = ShuffV[i];
  13218. if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
  13219. ShuffV[i] +=
  13220. Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth;
  13221. }
  13222. }
  13223. // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
  13224. // the original is:
  13225. // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
  13226. // In such a case, just change the shuffle mask to extract the element
  13227. // from the permuted index.
  13228. static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG,
  13229. const PPCSubtarget &Subtarget) {
  13230. SDLoc dl(OrigSToV);
  13231. EVT VT = OrigSToV.getValueType();
  13232. assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
  13233. "Expecting a SCALAR_TO_VECTOR here");
  13234. SDValue Input = OrigSToV.getOperand(0);
  13235. if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
  13236. ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
  13237. SDValue OrigVector = Input.getOperand(0);
  13238. // Can't handle non-const element indices or different vector types
  13239. // for the input to the extract and the output of the scalar_to_vector.
  13240. if (Idx && VT == OrigVector.getValueType()) {
  13241. unsigned NumElts = VT.getVectorNumElements();
  13242. assert(
  13243. NumElts > 1 &&
  13244. "Cannot produce a permuted scalar_to_vector for one element vector");
  13245. SmallVector<int, 16> NewMask(NumElts, -1);
  13246. unsigned ResultInElt = NumElts / 2;
  13247. ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1;
  13248. NewMask[ResultInElt] = Idx->getZExtValue();
  13249. return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
  13250. }
  13251. }
  13252. return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
  13253. OrigSToV.getOperand(0));
  13254. }
  13255. // On little endian subtargets, combine shuffles such as:
  13256. // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
  13257. // into:
  13258. // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
  13259. // because the latter can be matched to a single instruction merge.
  13260. // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
  13261. // to put the value into element zero. Adjust the shuffle mask so that the
  13262. // vector can remain in permuted form (to prevent a swap prior to a shuffle).
  13263. // On big endian targets, this is still useful for SCALAR_TO_VECTOR
  13264. // nodes with elements smaller than doubleword because all the ways
  13265. // of getting scalar data into a vector register put the value in the
  13266. // rightmost element of the left half of the vector.
  13267. SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
  13268. SelectionDAG &DAG) const {
  13269. SDValue LHS = SVN->getOperand(0);
  13270. SDValue RHS = SVN->getOperand(1);
  13271. auto Mask = SVN->getMask();
  13272. int NumElts = LHS.getValueType().getVectorNumElements();
  13273. SDValue Res(SVN, 0);
  13274. SDLoc dl(SVN);
  13275. bool IsLittleEndian = Subtarget.isLittleEndian();
  13276. // On big endian targets this is only useful for subtargets with direct moves.
  13277. // On little endian targets it would be useful for all subtargets with VSX.
  13278. // However adding special handling for LE subtargets without direct moves
  13279. // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8)
  13280. // which includes direct moves.
  13281. if (!Subtarget.hasDirectMove())
  13282. return Res;
  13283. // If this is not a shuffle of a shuffle and the first element comes from
  13284. // the second vector, canonicalize to the commuted form. This will make it
  13285. // more likely to match one of the single instruction patterns.
  13286. if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
  13287. RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
  13288. std::swap(LHS, RHS);
  13289. Res = DAG.getCommutedVectorShuffle(*SVN);
  13290. Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
  13291. }
  13292. // Adjust the shuffle mask if either input vector comes from a
  13293. // SCALAR_TO_VECTOR and keep the respective input vector in permuted
  13294. // form (to prevent the need for a swap).
  13295. SmallVector<int, 16> ShuffV(Mask);
  13296. SDValue SToVLHS = isScalarToVec(LHS);
  13297. SDValue SToVRHS = isScalarToVec(RHS);
  13298. if (SToVLHS || SToVRHS) {
  13299. // FIXME: If both LHS and RHS are SCALAR_TO_VECTOR, but are not the
  13300. // same type and have differing element sizes, then do not perform
  13301. // the following transformation. The current transformation for
  13302. // SCALAR_TO_VECTOR assumes that both input vectors have the same
  13303. // element size. This will be updated in the future to account for
  13304. // differing sizes of the LHS and RHS.
  13305. if (SToVLHS && SToVRHS &&
  13306. (SToVLHS.getValueType().getScalarSizeInBits() !=
  13307. SToVRHS.getValueType().getScalarSizeInBits()))
  13308. return Res;
  13309. int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
  13310. : SToVRHS.getValueType().getVectorNumElements();
  13311. int NumEltsOut = ShuffV.size();
  13312. // The width of the "valid lane" (i.e. the lane that contains the value that
  13313. // is vectorized) needs to be expressed in terms of the number of elements
  13314. // of the shuffle. It is thereby the ratio of the values before and after
  13315. // any bitcast.
  13316. unsigned ValidLaneWidth =
  13317. SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() /
  13318. LHS.getValueType().getScalarSizeInBits()
  13319. : SToVRHS.getValueType().getScalarSizeInBits() /
  13320. RHS.getValueType().getScalarSizeInBits();
  13321. // Initially assume that neither input is permuted. These will be adjusted
  13322. // accordingly if either input is.
  13323. int LHSMaxIdx = -1;
  13324. int RHSMinIdx = -1;
  13325. int RHSMaxIdx = -1;
  13326. int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
  13327. // Get the permuted scalar to vector nodes for the source(s) that come from
  13328. // ISD::SCALAR_TO_VECTOR.
  13329. // On big endian systems, this only makes sense for element sizes smaller
  13330. // than 64 bits since for 64-bit elements, all instructions already put
  13331. // the value into element zero. Since scalar size of LHS and RHS may differ
  13332. // after isScalarToVec, this should be checked using their own sizes.
  13333. if (SToVLHS) {
  13334. if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64)
  13335. return Res;
  13336. // Set up the values for the shuffle vector fixup.
  13337. LHSMaxIdx = NumEltsOut / NumEltsIn;
  13338. SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget);
  13339. if (SToVLHS.getValueType() != LHS.getValueType())
  13340. SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
  13341. LHS = SToVLHS;
  13342. }
  13343. if (SToVRHS) {
  13344. if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64)
  13345. return Res;
  13346. RHSMinIdx = NumEltsOut;
  13347. RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
  13348. SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget);
  13349. if (SToVRHS.getValueType() != RHS.getValueType())
  13350. SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
  13351. RHS = SToVRHS;
  13352. }
  13353. // Fix up the shuffle mask to reflect where the desired element actually is.
  13354. // The minimum and maximum indices that correspond to element zero for both
  13355. // the LHS and RHS are computed and will control which shuffle mask entries
  13356. // are to be changed. For example, if the RHS is permuted, any shuffle mask
  13357. // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted.
  13358. fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
  13359. HalfVec, ValidLaneWidth, Subtarget);
  13360. Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
  13361. // We may have simplified away the shuffle. We won't be able to do anything
  13362. // further with it here.
  13363. if (!isa<ShuffleVectorSDNode>(Res))
  13364. return Res;
  13365. Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
  13366. }
  13367. SDValue TheSplat = IsLittleEndian ? RHS : LHS;
  13368. // The common case after we commuted the shuffle is that the RHS is a splat
  13369. // and we have elements coming in from the splat at indices that are not
  13370. // conducive to using a merge.
  13371. // Example:
  13372. // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
  13373. if (!isSplatBV(TheSplat))
  13374. return Res;
  13375. // We are looking for a mask such that all even elements are from
  13376. // one vector and all odd elements from the other.
  13377. if (!isAlternatingShuffMask(Mask, NumElts))
  13378. return Res;
  13379. // Adjust the mask so we are pulling in the same index from the splat
  13380. // as the index from the interesting vector in consecutive elements.
  13381. if (IsLittleEndian) {
  13382. // Example (even elements from first vector):
  13383. // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
  13384. if (Mask[0] < NumElts)
  13385. for (int i = 1, e = Mask.size(); i < e; i += 2) {
  13386. if (ShuffV[i] < 0)
  13387. continue;
  13388. ShuffV[i] = (ShuffV[i - 1] + NumElts);
  13389. }
  13390. // Example (odd elements from first vector):
  13391. // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
  13392. else
  13393. for (int i = 0, e = Mask.size(); i < e; i += 2) {
  13394. if (ShuffV[i] < 0)
  13395. continue;
  13396. ShuffV[i] = (ShuffV[i + 1] + NumElts);
  13397. }
  13398. } else {
  13399. // Example (even elements from first vector):
  13400. // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1
  13401. if (Mask[0] < NumElts)
  13402. for (int i = 0, e = Mask.size(); i < e; i += 2) {
  13403. if (ShuffV[i] < 0)
  13404. continue;
  13405. ShuffV[i] = ShuffV[i + 1] - NumElts;
  13406. }
  13407. // Example (odd elements from first vector):
  13408. // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1
  13409. else
  13410. for (int i = 1, e = Mask.size(); i < e; i += 2) {
  13411. if (ShuffV[i] < 0)
  13412. continue;
  13413. ShuffV[i] = ShuffV[i - 1] - NumElts;
  13414. }
  13415. }
  13416. // If the RHS has undefs, we need to remove them since we may have created
  13417. // a shuffle that adds those instead of the splat value.
  13418. SDValue SplatVal =
  13419. cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue();
  13420. TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal);
  13421. if (IsLittleEndian)
  13422. RHS = TheSplat;
  13423. else
  13424. LHS = TheSplat;
  13425. return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
  13426. }
  13427. SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
  13428. LSBaseSDNode *LSBase,
  13429. DAGCombinerInfo &DCI) const {
  13430. assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
  13431. "Not a reverse memop pattern!");
  13432. auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
  13433. auto Mask = SVN->getMask();
  13434. int i = 0;
  13435. auto I = Mask.rbegin();
  13436. auto E = Mask.rend();
  13437. for (; I != E; ++I) {
  13438. if (*I != i)
  13439. return false;
  13440. i++;
  13441. }
  13442. return true;
  13443. };
  13444. SelectionDAG &DAG = DCI.DAG;
  13445. EVT VT = SVN->getValueType(0);
  13446. if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
  13447. return SDValue();
  13448. // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
  13449. // See comment in PPCVSXSwapRemoval.cpp.
  13450. // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
  13451. if (!Subtarget.hasP9Vector())
  13452. return SDValue();
  13453. if(!IsElementReverse(SVN))
  13454. return SDValue();
  13455. if (LSBase->getOpcode() == ISD::LOAD) {
  13456. // If the load return value 0 has more than one user except the
  13457. // shufflevector instruction, it is not profitable to replace the
  13458. // shufflevector with a reverse load.
  13459. for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end();
  13460. UI != UE; ++UI)
  13461. if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE)
  13462. return SDValue();
  13463. SDLoc dl(LSBase);
  13464. SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
  13465. return DAG.getMemIntrinsicNode(
  13466. PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
  13467. LSBase->getMemoryVT(), LSBase->getMemOperand());
  13468. }
  13469. if (LSBase->getOpcode() == ISD::STORE) {
  13470. // If there are other uses of the shuffle, the swap cannot be avoided.
  13471. // Forcing the use of an X-Form (since swapped stores only have
  13472. // X-Forms) without removing the swap is unprofitable.
  13473. if (!SVN->hasOneUse())
  13474. return SDValue();
  13475. SDLoc dl(LSBase);
  13476. SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
  13477. LSBase->getBasePtr()};
  13478. return DAG.getMemIntrinsicNode(
  13479. PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
  13480. LSBase->getMemoryVT(), LSBase->getMemOperand());
  13481. }
  13482. llvm_unreachable("Expected a load or store node here");
  13483. }
  13484. static bool isStoreConditional(SDValue Intrin, unsigned &StoreWidth) {
  13485. unsigned IntrinsicID =
  13486. cast<ConstantSDNode>(Intrin.getOperand(1))->getZExtValue();
  13487. if (IntrinsicID == Intrinsic::ppc_stdcx)
  13488. StoreWidth = 8;
  13489. else if (IntrinsicID == Intrinsic::ppc_stwcx)
  13490. StoreWidth = 4;
  13491. else if (IntrinsicID == Intrinsic::ppc_sthcx)
  13492. StoreWidth = 2;
  13493. else if (IntrinsicID == Intrinsic::ppc_stbcx)
  13494. StoreWidth = 1;
  13495. else
  13496. return false;
  13497. return true;
  13498. }
  13499. SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
  13500. DAGCombinerInfo &DCI) const {
  13501. SelectionDAG &DAG = DCI.DAG;
  13502. SDLoc dl(N);
  13503. switch (N->getOpcode()) {
  13504. default: break;
  13505. case ISD::ADD:
  13506. return combineADD(N, DCI);
  13507. case ISD::SHL:
  13508. return combineSHL(N, DCI);
  13509. case ISD::SRA:
  13510. return combineSRA(N, DCI);
  13511. case ISD::SRL:
  13512. return combineSRL(N, DCI);
  13513. case ISD::MUL:
  13514. return combineMUL(N, DCI);
  13515. case ISD::FMA:
  13516. case PPCISD::FNMSUB:
  13517. return combineFMALike(N, DCI);
  13518. case PPCISD::SHL:
  13519. if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
  13520. return N->getOperand(0);
  13521. break;
  13522. case PPCISD::SRL:
  13523. if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
  13524. return N->getOperand(0);
  13525. break;
  13526. case PPCISD::SRA:
  13527. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
  13528. if (C->isZero() || // 0 >>s V -> 0.
  13529. C->isAllOnes()) // -1 >>s V -> -1.
  13530. return N->getOperand(0);
  13531. }
  13532. break;
  13533. case ISD::SIGN_EXTEND:
  13534. case ISD::ZERO_EXTEND:
  13535. case ISD::ANY_EXTEND:
  13536. return DAGCombineExtBoolTrunc(N, DCI);
  13537. case ISD::TRUNCATE:
  13538. return combineTRUNCATE(N, DCI);
  13539. case ISD::SETCC:
  13540. if (SDValue CSCC = combineSetCC(N, DCI))
  13541. return CSCC;
  13542. [[fallthrough]];
  13543. case ISD::SELECT_CC:
  13544. return DAGCombineTruncBoolExt(N, DCI);
  13545. case ISD::SINT_TO_FP:
  13546. case ISD::UINT_TO_FP:
  13547. return combineFPToIntToFP(N, DCI);
  13548. case ISD::VECTOR_SHUFFLE:
  13549. if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
  13550. LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
  13551. return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
  13552. }
  13553. return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
  13554. case ISD::STORE: {
  13555. EVT Op1VT = N->getOperand(1).getValueType();
  13556. unsigned Opcode = N->getOperand(1).getOpcode();
  13557. if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
  13558. SDValue Val= combineStoreFPToInt(N, DCI);
  13559. if (Val)
  13560. return Val;
  13561. }
  13562. if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
  13563. ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
  13564. SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
  13565. if (Val)
  13566. return Val;
  13567. }
  13568. // Turn STORE (BSWAP) -> sthbrx/stwbrx.
  13569. if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
  13570. N->getOperand(1).getNode()->hasOneUse() &&
  13571. (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
  13572. (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
  13573. // STBRX can only handle simple types and it makes no sense to store less
  13574. // two bytes in byte-reversed order.
  13575. EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
  13576. if (mVT.isExtended() || mVT.getSizeInBits() < 16)
  13577. break;
  13578. SDValue BSwapOp = N->getOperand(1).getOperand(0);
  13579. // Do an any-extend to 32-bits if this is a half-word input.
  13580. if (BSwapOp.getValueType() == MVT::i16)
  13581. BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
  13582. // If the type of BSWAP operand is wider than stored memory width
  13583. // it need to be shifted to the right side before STBRX.
  13584. if (Op1VT.bitsGT(mVT)) {
  13585. int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
  13586. BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
  13587. DAG.getConstant(Shift, dl, MVT::i32));
  13588. // Need to truncate if this is a bswap of i64 stored as i32/i16.
  13589. if (Op1VT == MVT::i64)
  13590. BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
  13591. }
  13592. SDValue Ops[] = {
  13593. N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
  13594. };
  13595. return
  13596. DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
  13597. Ops, cast<StoreSDNode>(N)->getMemoryVT(),
  13598. cast<StoreSDNode>(N)->getMemOperand());
  13599. }
  13600. // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0>
  13601. // So it can increase the chance of CSE constant construction.
  13602. if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
  13603. isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
  13604. // Need to sign-extended to 64-bits to handle negative values.
  13605. EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
  13606. uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
  13607. MemVT.getSizeInBits());
  13608. SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
  13609. // DAG.getTruncStore() can't be used here because it doesn't accept
  13610. // the general (base + offset) addressing mode.
  13611. // So we use UpdateNodeOperands and setTruncatingStore instead.
  13612. DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
  13613. N->getOperand(3));
  13614. cast<StoreSDNode>(N)->setTruncatingStore(true);
  13615. return SDValue(N, 0);
  13616. }
  13617. // For little endian, VSX stores require generating xxswapd/lxvd2x.
  13618. // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
  13619. if (Op1VT.isSimple()) {
  13620. MVT StoreVT = Op1VT.getSimpleVT();
  13621. if (Subtarget.needsSwapsForVSXMemOps() &&
  13622. (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
  13623. StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
  13624. return expandVSXStoreForLE(N, DCI);
  13625. }
  13626. break;
  13627. }
  13628. case ISD::LOAD: {
  13629. LoadSDNode *LD = cast<LoadSDNode>(N);
  13630. EVT VT = LD->getValueType(0);
  13631. // For little endian, VSX loads require generating lxvd2x/xxswapd.
  13632. // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
  13633. if (VT.isSimple()) {
  13634. MVT LoadVT = VT.getSimpleVT();
  13635. if (Subtarget.needsSwapsForVSXMemOps() &&
  13636. (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
  13637. LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
  13638. return expandVSXLoadForLE(N, DCI);
  13639. }
  13640. // We sometimes end up with a 64-bit integer load, from which we extract
  13641. // two single-precision floating-point numbers. This happens with
  13642. // std::complex<float>, and other similar structures, because of the way we
  13643. // canonicalize structure copies. However, if we lack direct moves,
  13644. // then the final bitcasts from the extracted integer values to the
  13645. // floating-point numbers turn into store/load pairs. Even with direct moves,
  13646. // just loading the two floating-point numbers is likely better.
  13647. auto ReplaceTwoFloatLoad = [&]() {
  13648. if (VT != MVT::i64)
  13649. return false;
  13650. if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
  13651. LD->isVolatile())
  13652. return false;
  13653. // We're looking for a sequence like this:
  13654. // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
  13655. // t16: i64 = srl t13, Constant:i32<32>
  13656. // t17: i32 = truncate t16
  13657. // t18: f32 = bitcast t17
  13658. // t19: i32 = truncate t13
  13659. // t20: f32 = bitcast t19
  13660. if (!LD->hasNUsesOfValue(2, 0))
  13661. return false;
  13662. auto UI = LD->use_begin();
  13663. while (UI.getUse().getResNo() != 0) ++UI;
  13664. SDNode *Trunc = *UI++;
  13665. while (UI.getUse().getResNo() != 0) ++UI;
  13666. SDNode *RightShift = *UI;
  13667. if (Trunc->getOpcode() != ISD::TRUNCATE)
  13668. std::swap(Trunc, RightShift);
  13669. if (Trunc->getOpcode() != ISD::TRUNCATE ||
  13670. Trunc->getValueType(0) != MVT::i32 ||
  13671. !Trunc->hasOneUse())
  13672. return false;
  13673. if (RightShift->getOpcode() != ISD::SRL ||
  13674. !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
  13675. RightShift->getConstantOperandVal(1) != 32 ||
  13676. !RightShift->hasOneUse())
  13677. return false;
  13678. SDNode *Trunc2 = *RightShift->use_begin();
  13679. if (Trunc2->getOpcode() != ISD::TRUNCATE ||
  13680. Trunc2->getValueType(0) != MVT::i32 ||
  13681. !Trunc2->hasOneUse())
  13682. return false;
  13683. SDNode *Bitcast = *Trunc->use_begin();
  13684. SDNode *Bitcast2 = *Trunc2->use_begin();
  13685. if (Bitcast->getOpcode() != ISD::BITCAST ||
  13686. Bitcast->getValueType(0) != MVT::f32)
  13687. return false;
  13688. if (Bitcast2->getOpcode() != ISD::BITCAST ||
  13689. Bitcast2->getValueType(0) != MVT::f32)
  13690. return false;
  13691. if (Subtarget.isLittleEndian())
  13692. std::swap(Bitcast, Bitcast2);
  13693. // Bitcast has the second float (in memory-layout order) and Bitcast2
  13694. // has the first one.
  13695. SDValue BasePtr = LD->getBasePtr();
  13696. if (LD->isIndexed()) {
  13697. assert(LD->getAddressingMode() == ISD::PRE_INC &&
  13698. "Non-pre-inc AM on PPC?");
  13699. BasePtr =
  13700. DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
  13701. LD->getOffset());
  13702. }
  13703. auto MMOFlags =
  13704. LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
  13705. SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
  13706. LD->getPointerInfo(), LD->getAlign(),
  13707. MMOFlags, LD->getAAInfo());
  13708. SDValue AddPtr =
  13709. DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
  13710. BasePtr, DAG.getIntPtrConstant(4, dl));
  13711. SDValue FloatLoad2 = DAG.getLoad(
  13712. MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
  13713. LD->getPointerInfo().getWithOffset(4),
  13714. commonAlignment(LD->getAlign(), 4), MMOFlags, LD->getAAInfo());
  13715. if (LD->isIndexed()) {
  13716. // Note that DAGCombine should re-form any pre-increment load(s) from
  13717. // what is produced here if that makes sense.
  13718. DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
  13719. }
  13720. DCI.CombineTo(Bitcast2, FloatLoad);
  13721. DCI.CombineTo(Bitcast, FloatLoad2);
  13722. DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
  13723. SDValue(FloatLoad2.getNode(), 1));
  13724. return true;
  13725. };
  13726. if (ReplaceTwoFloatLoad())
  13727. return SDValue(N, 0);
  13728. EVT MemVT = LD->getMemoryVT();
  13729. Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
  13730. Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
  13731. if (LD->isUnindexed() && VT.isVector() &&
  13732. ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
  13733. // P8 and later hardware should just use LOAD.
  13734. !Subtarget.hasP8Vector() &&
  13735. (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
  13736. VT == MVT::v4f32))) &&
  13737. LD->getAlign() < ABIAlignment) {
  13738. // This is a type-legal unaligned Altivec load.
  13739. SDValue Chain = LD->getChain();
  13740. SDValue Ptr = LD->getBasePtr();
  13741. bool isLittleEndian = Subtarget.isLittleEndian();
  13742. // This implements the loading of unaligned vectors as described in
  13743. // the venerable Apple Velocity Engine overview. Specifically:
  13744. // https://developer.apple.com/hardwaredrivers/ve/alignment.html
  13745. // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
  13746. //
  13747. // The general idea is to expand a sequence of one or more unaligned
  13748. // loads into an alignment-based permutation-control instruction (lvsl
  13749. // or lvsr), a series of regular vector loads (which always truncate
  13750. // their input address to an aligned address), and a series of
  13751. // permutations. The results of these permutations are the requested
  13752. // loaded values. The trick is that the last "extra" load is not taken
  13753. // from the address you might suspect (sizeof(vector) bytes after the
  13754. // last requested load), but rather sizeof(vector) - 1 bytes after the
  13755. // last requested vector. The point of this is to avoid a page fault if
  13756. // the base address happened to be aligned. This works because if the
  13757. // base address is aligned, then adding less than a full vector length
  13758. // will cause the last vector in the sequence to be (re)loaded.
  13759. // Otherwise, the next vector will be fetched as you might suspect was
  13760. // necessary.
  13761. // We might be able to reuse the permutation generation from
  13762. // a different base address offset from this one by an aligned amount.
  13763. // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
  13764. // optimization later.
  13765. Intrinsic::ID Intr, IntrLD, IntrPerm;
  13766. MVT PermCntlTy, PermTy, LDTy;
  13767. Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
  13768. : Intrinsic::ppc_altivec_lvsl;
  13769. IntrLD = Intrinsic::ppc_altivec_lvx;
  13770. IntrPerm = Intrinsic::ppc_altivec_vperm;
  13771. PermCntlTy = MVT::v16i8;
  13772. PermTy = MVT::v4i32;
  13773. LDTy = MVT::v4i32;
  13774. SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
  13775. // Create the new MMO for the new base load. It is like the original MMO,
  13776. // but represents an area in memory almost twice the vector size centered
  13777. // on the original address. If the address is unaligned, we might start
  13778. // reading up to (sizeof(vector)-1) bytes below the address of the
  13779. // original unaligned load.
  13780. MachineFunction &MF = DAG.getMachineFunction();
  13781. MachineMemOperand *BaseMMO =
  13782. MF.getMachineMemOperand(LD->getMemOperand(),
  13783. -(int64_t)MemVT.getStoreSize()+1,
  13784. 2*MemVT.getStoreSize()-1);
  13785. // Create the new base load.
  13786. SDValue LDXIntID =
  13787. DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
  13788. SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
  13789. SDValue BaseLoad =
  13790. DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
  13791. DAG.getVTList(PermTy, MVT::Other),
  13792. BaseLoadOps, LDTy, BaseMMO);
  13793. // Note that the value of IncOffset (which is provided to the next
  13794. // load's pointer info offset value, and thus used to calculate the
  13795. // alignment), and the value of IncValue (which is actually used to
  13796. // increment the pointer value) are different! This is because we
  13797. // require the next load to appear to be aligned, even though it
  13798. // is actually offset from the base pointer by a lesser amount.
  13799. int IncOffset = VT.getSizeInBits() / 8;
  13800. int IncValue = IncOffset;
  13801. // Walk (both up and down) the chain looking for another load at the real
  13802. // (aligned) offset (the alignment of the other load does not matter in
  13803. // this case). If found, then do not use the offset reduction trick, as
  13804. // that will prevent the loads from being later combined (as they would
  13805. // otherwise be duplicates).
  13806. if (!findConsecutiveLoad(LD, DAG))
  13807. --IncValue;
  13808. SDValue Increment =
  13809. DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
  13810. Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
  13811. MachineMemOperand *ExtraMMO =
  13812. MF.getMachineMemOperand(LD->getMemOperand(),
  13813. 1, 2*MemVT.getStoreSize()-1);
  13814. SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
  13815. SDValue ExtraLoad =
  13816. DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
  13817. DAG.getVTList(PermTy, MVT::Other),
  13818. ExtraLoadOps, LDTy, ExtraMMO);
  13819. SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  13820. BaseLoad.getValue(1), ExtraLoad.getValue(1));
  13821. // Because vperm has a big-endian bias, we must reverse the order
  13822. // of the input vectors and complement the permute control vector
  13823. // when generating little endian code. We have already handled the
  13824. // latter by using lvsr instead of lvsl, so just reverse BaseLoad
  13825. // and ExtraLoad here.
  13826. SDValue Perm;
  13827. if (isLittleEndian)
  13828. Perm = BuildIntrinsicOp(IntrPerm,
  13829. ExtraLoad, BaseLoad, PermCntl, DAG, dl);
  13830. else
  13831. Perm = BuildIntrinsicOp(IntrPerm,
  13832. BaseLoad, ExtraLoad, PermCntl, DAG, dl);
  13833. if (VT != PermTy)
  13834. Perm = Subtarget.hasAltivec()
  13835. ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
  13836. : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
  13837. DAG.getTargetConstant(1, dl, MVT::i64));
  13838. // second argument is 1 because this rounding
  13839. // is always exact.
  13840. // The output of the permutation is our loaded result, the TokenFactor is
  13841. // our new chain.
  13842. DCI.CombineTo(N, Perm, TF);
  13843. return SDValue(N, 0);
  13844. }
  13845. }
  13846. break;
  13847. case ISD::INTRINSIC_WO_CHAIN: {
  13848. bool isLittleEndian = Subtarget.isLittleEndian();
  13849. unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
  13850. Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
  13851. : Intrinsic::ppc_altivec_lvsl);
  13852. if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
  13853. SDValue Add = N->getOperand(1);
  13854. int Bits = 4 /* 16 byte alignment */;
  13855. if (DAG.MaskedValueIsZero(Add->getOperand(1),
  13856. APInt::getAllOnes(Bits /* alignment */)
  13857. .zext(Add.getScalarValueSizeInBits()))) {
  13858. SDNode *BasePtr = Add->getOperand(0).getNode();
  13859. for (SDNode *U : BasePtr->uses()) {
  13860. if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
  13861. cast<ConstantSDNode>(U->getOperand(0))->getZExtValue() == IID) {
  13862. // We've found another LVSL/LVSR, and this address is an aligned
  13863. // multiple of that one. The results will be the same, so use the
  13864. // one we've just found instead.
  13865. return SDValue(U, 0);
  13866. }
  13867. }
  13868. }
  13869. if (isa<ConstantSDNode>(Add->getOperand(1))) {
  13870. SDNode *BasePtr = Add->getOperand(0).getNode();
  13871. for (SDNode *U : BasePtr->uses()) {
  13872. if (U->getOpcode() == ISD::ADD &&
  13873. isa<ConstantSDNode>(U->getOperand(1)) &&
  13874. (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
  13875. cast<ConstantSDNode>(U->getOperand(1))->getZExtValue()) %
  13876. (1ULL << Bits) ==
  13877. 0) {
  13878. SDNode *OtherAdd = U;
  13879. for (SDNode *V : OtherAdd->uses()) {
  13880. if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
  13881. cast<ConstantSDNode>(V->getOperand(0))->getZExtValue() ==
  13882. IID) {
  13883. return SDValue(V, 0);
  13884. }
  13885. }
  13886. }
  13887. }
  13888. }
  13889. }
  13890. // Combine vmaxsw/h/b(a, a's negation) to abs(a)
  13891. // Expose the vabsduw/h/b opportunity for down stream
  13892. if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
  13893. (IID == Intrinsic::ppc_altivec_vmaxsw ||
  13894. IID == Intrinsic::ppc_altivec_vmaxsh ||
  13895. IID == Intrinsic::ppc_altivec_vmaxsb)) {
  13896. SDValue V1 = N->getOperand(1);
  13897. SDValue V2 = N->getOperand(2);
  13898. if ((V1.getSimpleValueType() == MVT::v4i32 ||
  13899. V1.getSimpleValueType() == MVT::v8i16 ||
  13900. V1.getSimpleValueType() == MVT::v16i8) &&
  13901. V1.getSimpleValueType() == V2.getSimpleValueType()) {
  13902. // (0-a, a)
  13903. if (V1.getOpcode() == ISD::SUB &&
  13904. ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
  13905. V1.getOperand(1) == V2) {
  13906. return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
  13907. }
  13908. // (a, 0-a)
  13909. if (V2.getOpcode() == ISD::SUB &&
  13910. ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
  13911. V2.getOperand(1) == V1) {
  13912. return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
  13913. }
  13914. // (x-y, y-x)
  13915. if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
  13916. V1.getOperand(0) == V2.getOperand(1) &&
  13917. V1.getOperand(1) == V2.getOperand(0)) {
  13918. return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
  13919. }
  13920. }
  13921. }
  13922. }
  13923. break;
  13924. case ISD::INTRINSIC_W_CHAIN:
  13925. // For little endian, VSX loads require generating lxvd2x/xxswapd.
  13926. // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
  13927. if (Subtarget.needsSwapsForVSXMemOps()) {
  13928. switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
  13929. default:
  13930. break;
  13931. case Intrinsic::ppc_vsx_lxvw4x:
  13932. case Intrinsic::ppc_vsx_lxvd2x:
  13933. return expandVSXLoadForLE(N, DCI);
  13934. }
  13935. }
  13936. break;
  13937. case ISD::INTRINSIC_VOID:
  13938. // For little endian, VSX stores require generating xxswapd/stxvd2x.
  13939. // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
  13940. if (Subtarget.needsSwapsForVSXMemOps()) {
  13941. switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
  13942. default:
  13943. break;
  13944. case Intrinsic::ppc_vsx_stxvw4x:
  13945. case Intrinsic::ppc_vsx_stxvd2x:
  13946. return expandVSXStoreForLE(N, DCI);
  13947. }
  13948. }
  13949. break;
  13950. case ISD::BSWAP: {
  13951. // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
  13952. // For subtargets without LDBRX, we can still do better than the default
  13953. // expansion even for 64-bit BSWAP (LOAD).
  13954. bool Is64BitBswapOn64BitTgt =
  13955. Subtarget.isPPC64() && N->getValueType(0) == MVT::i64;
  13956. bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) &&
  13957. N->getOperand(0).hasOneUse();
  13958. if (IsSingleUseNormalLd &&
  13959. (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
  13960. (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) {
  13961. SDValue Load = N->getOperand(0);
  13962. LoadSDNode *LD = cast<LoadSDNode>(Load);
  13963. // Create the byte-swapping load.
  13964. SDValue Ops[] = {
  13965. LD->getChain(), // Chain
  13966. LD->getBasePtr(), // Ptr
  13967. DAG.getValueType(N->getValueType(0)) // VT
  13968. };
  13969. SDValue BSLoad =
  13970. DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
  13971. DAG.getVTList(N->getValueType(0) == MVT::i64 ?
  13972. MVT::i64 : MVT::i32, MVT::Other),
  13973. Ops, LD->getMemoryVT(), LD->getMemOperand());
  13974. // If this is an i16 load, insert the truncate.
  13975. SDValue ResVal = BSLoad;
  13976. if (N->getValueType(0) == MVT::i16)
  13977. ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
  13978. // First, combine the bswap away. This makes the value produced by the
  13979. // load dead.
  13980. DCI.CombineTo(N, ResVal);
  13981. // Next, combine the load away, we give it a bogus result value but a real
  13982. // chain result. The result value is dead because the bswap is dead.
  13983. DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
  13984. // Return N so it doesn't get rechecked!
  13985. return SDValue(N, 0);
  13986. }
  13987. // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only
  13988. // before legalization so that the BUILD_PAIR is handled correctly.
  13989. if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt ||
  13990. !IsSingleUseNormalLd)
  13991. return SDValue();
  13992. LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0));
  13993. // Can't split volatile or atomic loads.
  13994. if (!LD->isSimple())
  13995. return SDValue();
  13996. SDValue BasePtr = LD->getBasePtr();
  13997. SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr,
  13998. LD->getPointerInfo(), LD->getAlign());
  13999. Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo);
  14000. BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
  14001. DAG.getIntPtrConstant(4, dl));
  14002. MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand(
  14003. LD->getMemOperand(), 4, 4);
  14004. SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO);
  14005. Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi);
  14006. SDValue Res;
  14007. if (Subtarget.isLittleEndian())
  14008. Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo);
  14009. else
  14010. Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
  14011. SDValue TF =
  14012. DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  14013. Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1));
  14014. DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF);
  14015. return Res;
  14016. }
  14017. case PPCISD::VCMP:
  14018. // If a VCMP_rec node already exists with exactly the same operands as this
  14019. // node, use its result instead of this node (VCMP_rec computes both a CR6
  14020. // and a normal output).
  14021. //
  14022. if (!N->getOperand(0).hasOneUse() &&
  14023. !N->getOperand(1).hasOneUse() &&
  14024. !N->getOperand(2).hasOneUse()) {
  14025. // Scan all of the users of the LHS, looking for VCMP_rec's that match.
  14026. SDNode *VCMPrecNode = nullptr;
  14027. SDNode *LHSN = N->getOperand(0).getNode();
  14028. for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
  14029. UI != E; ++UI)
  14030. if (UI->getOpcode() == PPCISD::VCMP_rec &&
  14031. UI->getOperand(1) == N->getOperand(1) &&
  14032. UI->getOperand(2) == N->getOperand(2) &&
  14033. UI->getOperand(0) == N->getOperand(0)) {
  14034. VCMPrecNode = *UI;
  14035. break;
  14036. }
  14037. // If there is no VCMP_rec node, or if the flag value has a single use,
  14038. // don't transform this.
  14039. if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
  14040. break;
  14041. // Look at the (necessarily single) use of the flag value. If it has a
  14042. // chain, this transformation is more complex. Note that multiple things
  14043. // could use the value result, which we should ignore.
  14044. SDNode *FlagUser = nullptr;
  14045. for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
  14046. FlagUser == nullptr; ++UI) {
  14047. assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
  14048. SDNode *User = *UI;
  14049. for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
  14050. if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
  14051. FlagUser = User;
  14052. break;
  14053. }
  14054. }
  14055. }
  14056. // If the user is a MFOCRF instruction, we know this is safe.
  14057. // Otherwise we give up for right now.
  14058. if (FlagUser->getOpcode() == PPCISD::MFOCRF)
  14059. return SDValue(VCMPrecNode, 0);
  14060. }
  14061. break;
  14062. case ISD::BR_CC: {
  14063. // If this is a branch on an altivec predicate comparison, lower this so
  14064. // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
  14065. // lowering is done pre-legalize, because the legalizer lowers the predicate
  14066. // compare down to code that is difficult to reassemble.
  14067. // This code also handles branches that depend on the result of a store
  14068. // conditional.
  14069. ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
  14070. SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
  14071. int CompareOpc;
  14072. bool isDot;
  14073. if (!isa<ConstantSDNode>(RHS) || (CC != ISD::SETEQ && CC != ISD::SETNE))
  14074. break;
  14075. // Since we are doing this pre-legalize, the RHS can be a constant of
  14076. // arbitrary bitwidth which may cause issues when trying to get the value
  14077. // from the underlying APInt.
  14078. auto RHSAPInt = cast<ConstantSDNode>(RHS)->getAPIntValue();
  14079. if (!RHSAPInt.isIntN(64))
  14080. break;
  14081. unsigned Val = RHSAPInt.getZExtValue();
  14082. auto isImpossibleCompare = [&]() {
  14083. // If this is a comparison against something other than 0/1, then we know
  14084. // that the condition is never/always true.
  14085. if (Val != 0 && Val != 1) {
  14086. if (CC == ISD::SETEQ) // Cond never true, remove branch.
  14087. return N->getOperand(0);
  14088. // Always !=, turn it into an unconditional branch.
  14089. return DAG.getNode(ISD::BR, dl, MVT::Other,
  14090. N->getOperand(0), N->getOperand(4));
  14091. }
  14092. return SDValue();
  14093. };
  14094. // Combine branches fed by store conditional instructions (st[bhwd]cx).
  14095. unsigned StoreWidth = 0;
  14096. if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
  14097. isStoreConditional(LHS, StoreWidth)) {
  14098. if (SDValue Impossible = isImpossibleCompare())
  14099. return Impossible;
  14100. PPC::Predicate CompOpc;
  14101. // eq 0 => ne
  14102. // ne 0 => eq
  14103. // eq 1 => eq
  14104. // ne 1 => ne
  14105. if (Val == 0)
  14106. CompOpc = CC == ISD::SETEQ ? PPC::PRED_NE : PPC::PRED_EQ;
  14107. else
  14108. CompOpc = CC == ISD::SETEQ ? PPC::PRED_EQ : PPC::PRED_NE;
  14109. SDValue Ops[] = {LHS.getOperand(0), LHS.getOperand(2), LHS.getOperand(3),
  14110. DAG.getConstant(StoreWidth, dl, MVT::i32)};
  14111. auto *MemNode = cast<MemSDNode>(LHS);
  14112. SDValue ConstSt = DAG.getMemIntrinsicNode(
  14113. PPCISD::STORE_COND, dl,
  14114. DAG.getVTList(MVT::i32, MVT::Other, MVT::Glue), Ops,
  14115. MemNode->getMemoryVT(), MemNode->getMemOperand());
  14116. SDValue InChain;
  14117. // Unchain the branch from the original store conditional.
  14118. if (N->getOperand(0) == LHS.getValue(1))
  14119. InChain = LHS.getOperand(0);
  14120. else if (N->getOperand(0).getOpcode() == ISD::TokenFactor) {
  14121. SmallVector<SDValue, 4> InChains;
  14122. SDValue InTF = N->getOperand(0);
  14123. for (int i = 0, e = InTF.getNumOperands(); i < e; i++)
  14124. if (InTF.getOperand(i) != LHS.getValue(1))
  14125. InChains.push_back(InTF.getOperand(i));
  14126. InChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, InChains);
  14127. }
  14128. return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, InChain,
  14129. DAG.getConstant(CompOpc, dl, MVT::i32),
  14130. DAG.getRegister(PPC::CR0, MVT::i32), N->getOperand(4),
  14131. ConstSt.getValue(2));
  14132. }
  14133. if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
  14134. getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
  14135. assert(isDot && "Can't compare against a vector result!");
  14136. if (SDValue Impossible = isImpossibleCompare())
  14137. return Impossible;
  14138. bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
  14139. // Create the PPCISD altivec 'dot' comparison node.
  14140. SDValue Ops[] = {
  14141. LHS.getOperand(2), // LHS of compare
  14142. LHS.getOperand(3), // RHS of compare
  14143. DAG.getConstant(CompareOpc, dl, MVT::i32)
  14144. };
  14145. EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
  14146. SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
  14147. // Unpack the result based on how the target uses it.
  14148. PPC::Predicate CompOpc;
  14149. switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
  14150. default: // Can't happen, don't crash on invalid number though.
  14151. case 0: // Branch on the value of the EQ bit of CR6.
  14152. CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
  14153. break;
  14154. case 1: // Branch on the inverted value of the EQ bit of CR6.
  14155. CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
  14156. break;
  14157. case 2: // Branch on the value of the LT bit of CR6.
  14158. CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
  14159. break;
  14160. case 3: // Branch on the inverted value of the LT bit of CR6.
  14161. CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
  14162. break;
  14163. }
  14164. return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
  14165. DAG.getConstant(CompOpc, dl, MVT::i32),
  14166. DAG.getRegister(PPC::CR6, MVT::i32),
  14167. N->getOperand(4), CompNode.getValue(1));
  14168. }
  14169. break;
  14170. }
  14171. case ISD::BUILD_VECTOR:
  14172. return DAGCombineBuildVector(N, DCI);
  14173. case ISD::ABS:
  14174. return combineABS(N, DCI);
  14175. case ISD::VSELECT:
  14176. return combineVSelect(N, DCI);
  14177. }
  14178. return SDValue();
  14179. }
  14180. SDValue
  14181. PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
  14182. SelectionDAG &DAG,
  14183. SmallVectorImpl<SDNode *> &Created) const {
  14184. // fold (sdiv X, pow2)
  14185. EVT VT = N->getValueType(0);
  14186. if (VT == MVT::i64 && !Subtarget.isPPC64())
  14187. return SDValue();
  14188. if ((VT != MVT::i32 && VT != MVT::i64) ||
  14189. !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
  14190. return SDValue();
  14191. SDLoc DL(N);
  14192. SDValue N0 = N->getOperand(0);
  14193. bool IsNegPow2 = Divisor.isNegatedPowerOf2();
  14194. unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
  14195. SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
  14196. SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
  14197. Created.push_back(Op.getNode());
  14198. if (IsNegPow2) {
  14199. Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
  14200. Created.push_back(Op.getNode());
  14201. }
  14202. return Op;
  14203. }
  14204. //===----------------------------------------------------------------------===//
  14205. // Inline Assembly Support
  14206. //===----------------------------------------------------------------------===//
  14207. void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
  14208. KnownBits &Known,
  14209. const APInt &DemandedElts,
  14210. const SelectionDAG &DAG,
  14211. unsigned Depth) const {
  14212. Known.resetAll();
  14213. switch (Op.getOpcode()) {
  14214. default: break;
  14215. case PPCISD::LBRX: {
  14216. // lhbrx is known to have the top bits cleared out.
  14217. if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
  14218. Known.Zero = 0xFFFF0000;
  14219. break;
  14220. }
  14221. case ISD::INTRINSIC_WO_CHAIN: {
  14222. switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
  14223. default: break;
  14224. case Intrinsic::ppc_altivec_vcmpbfp_p:
  14225. case Intrinsic::ppc_altivec_vcmpeqfp_p:
  14226. case Intrinsic::ppc_altivec_vcmpequb_p:
  14227. case Intrinsic::ppc_altivec_vcmpequh_p:
  14228. case Intrinsic::ppc_altivec_vcmpequw_p:
  14229. case Intrinsic::ppc_altivec_vcmpequd_p:
  14230. case Intrinsic::ppc_altivec_vcmpequq_p:
  14231. case Intrinsic::ppc_altivec_vcmpgefp_p:
  14232. case Intrinsic::ppc_altivec_vcmpgtfp_p:
  14233. case Intrinsic::ppc_altivec_vcmpgtsb_p:
  14234. case Intrinsic::ppc_altivec_vcmpgtsh_p:
  14235. case Intrinsic::ppc_altivec_vcmpgtsw_p:
  14236. case Intrinsic::ppc_altivec_vcmpgtsd_p:
  14237. case Intrinsic::ppc_altivec_vcmpgtsq_p:
  14238. case Intrinsic::ppc_altivec_vcmpgtub_p:
  14239. case Intrinsic::ppc_altivec_vcmpgtuh_p:
  14240. case Intrinsic::ppc_altivec_vcmpgtuw_p:
  14241. case Intrinsic::ppc_altivec_vcmpgtud_p:
  14242. case Intrinsic::ppc_altivec_vcmpgtuq_p:
  14243. Known.Zero = ~1U; // All bits but the low one are known to be zero.
  14244. break;
  14245. }
  14246. break;
  14247. }
  14248. case ISD::INTRINSIC_W_CHAIN: {
  14249. switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
  14250. default:
  14251. break;
  14252. case Intrinsic::ppc_load2r:
  14253. // Top bits are cleared for load2r (which is the same as lhbrx).
  14254. Known.Zero = 0xFFFF0000;
  14255. break;
  14256. }
  14257. break;
  14258. }
  14259. }
  14260. }
  14261. Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
  14262. switch (Subtarget.getCPUDirective()) {
  14263. default: break;
  14264. case PPC::DIR_970:
  14265. case PPC::DIR_PWR4:
  14266. case PPC::DIR_PWR5:
  14267. case PPC::DIR_PWR5X:
  14268. case PPC::DIR_PWR6:
  14269. case PPC::DIR_PWR6X:
  14270. case PPC::DIR_PWR7:
  14271. case PPC::DIR_PWR8:
  14272. case PPC::DIR_PWR9:
  14273. case PPC::DIR_PWR10:
  14274. case PPC::DIR_PWR_FUTURE: {
  14275. if (!ML)
  14276. break;
  14277. if (!DisableInnermostLoopAlign32) {
  14278. // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
  14279. // so that we can decrease cache misses and branch-prediction misses.
  14280. // Actual alignment of the loop will depend on the hotness check and other
  14281. // logic in alignBlocks.
  14282. if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
  14283. return Align(32);
  14284. }
  14285. const PPCInstrInfo *TII = Subtarget.getInstrInfo();
  14286. // For small loops (between 5 and 8 instructions), align to a 32-byte
  14287. // boundary so that the entire loop fits in one instruction-cache line.
  14288. uint64_t LoopSize = 0;
  14289. for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
  14290. for (const MachineInstr &J : **I) {
  14291. LoopSize += TII->getInstSizeInBytes(J);
  14292. if (LoopSize > 32)
  14293. break;
  14294. }
  14295. if (LoopSize > 16 && LoopSize <= 32)
  14296. return Align(32);
  14297. break;
  14298. }
  14299. }
  14300. return TargetLowering::getPrefLoopAlignment(ML);
  14301. }
  14302. /// getConstraintType - Given a constraint, return the type of
  14303. /// constraint it is for this target.
  14304. PPCTargetLowering::ConstraintType
  14305. PPCTargetLowering::getConstraintType(StringRef Constraint) const {
  14306. if (Constraint.size() == 1) {
  14307. switch (Constraint[0]) {
  14308. default: break;
  14309. case 'b':
  14310. case 'r':
  14311. case 'f':
  14312. case 'd':
  14313. case 'v':
  14314. case 'y':
  14315. return C_RegisterClass;
  14316. case 'Z':
  14317. // FIXME: While Z does indicate a memory constraint, it specifically
  14318. // indicates an r+r address (used in conjunction with the 'y' modifier
  14319. // in the replacement string). Currently, we're forcing the base
  14320. // register to be r0 in the asm printer (which is interpreted as zero)
  14321. // and forming the complete address in the second register. This is
  14322. // suboptimal.
  14323. return C_Memory;
  14324. }
  14325. } else if (Constraint == "wc") { // individual CR bits.
  14326. return C_RegisterClass;
  14327. } else if (Constraint == "wa" || Constraint == "wd" ||
  14328. Constraint == "wf" || Constraint == "ws" ||
  14329. Constraint == "wi" || Constraint == "ww") {
  14330. return C_RegisterClass; // VSX registers.
  14331. }
  14332. return TargetLowering::getConstraintType(Constraint);
  14333. }
  14334. /// Examine constraint type and operand type and determine a weight value.
  14335. /// This object must already have been set up with the operand type
  14336. /// and the current alternative constraint selected.
  14337. TargetLowering::ConstraintWeight
  14338. PPCTargetLowering::getSingleConstraintMatchWeight(
  14339. AsmOperandInfo &info, const char *constraint) const {
  14340. ConstraintWeight weight = CW_Invalid;
  14341. Value *CallOperandVal = info.CallOperandVal;
  14342. // If we don't have a value, we can't do a match,
  14343. // but allow it at the lowest weight.
  14344. if (!CallOperandVal)
  14345. return CW_Default;
  14346. Type *type = CallOperandVal->getType();
  14347. // Look at the constraint type.
  14348. if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
  14349. return CW_Register; // an individual CR bit.
  14350. else if ((StringRef(constraint) == "wa" ||
  14351. StringRef(constraint) == "wd" ||
  14352. StringRef(constraint) == "wf") &&
  14353. type->isVectorTy())
  14354. return CW_Register;
  14355. else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
  14356. return CW_Register; // just hold 64-bit integers data.
  14357. else if (StringRef(constraint) == "ws" && type->isDoubleTy())
  14358. return CW_Register;
  14359. else if (StringRef(constraint) == "ww" && type->isFloatTy())
  14360. return CW_Register;
  14361. switch (*constraint) {
  14362. default:
  14363. weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
  14364. break;
  14365. case 'b':
  14366. if (type->isIntegerTy())
  14367. weight = CW_Register;
  14368. break;
  14369. case 'f':
  14370. if (type->isFloatTy())
  14371. weight = CW_Register;
  14372. break;
  14373. case 'd':
  14374. if (type->isDoubleTy())
  14375. weight = CW_Register;
  14376. break;
  14377. case 'v':
  14378. if (type->isVectorTy())
  14379. weight = CW_Register;
  14380. break;
  14381. case 'y':
  14382. weight = CW_Register;
  14383. break;
  14384. case 'Z':
  14385. weight = CW_Memory;
  14386. break;
  14387. }
  14388. return weight;
  14389. }
  14390. std::pair<unsigned, const TargetRegisterClass *>
  14391. PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
  14392. StringRef Constraint,
  14393. MVT VT) const {
  14394. if (Constraint.size() == 1) {
  14395. // GCC RS6000 Constraint Letters
  14396. switch (Constraint[0]) {
  14397. case 'b': // R1-R31
  14398. if (VT == MVT::i64 && Subtarget.isPPC64())
  14399. return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
  14400. return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
  14401. case 'r': // R0-R31
  14402. if (VT == MVT::i64 && Subtarget.isPPC64())
  14403. return std::make_pair(0U, &PPC::G8RCRegClass);
  14404. return std::make_pair(0U, &PPC::GPRCRegClass);
  14405. // 'd' and 'f' constraints are both defined to be "the floating point
  14406. // registers", where one is for 32-bit and the other for 64-bit. We don't
  14407. // really care overly much here so just give them all the same reg classes.
  14408. case 'd':
  14409. case 'f':
  14410. if (Subtarget.hasSPE()) {
  14411. if (VT == MVT::f32 || VT == MVT::i32)
  14412. return std::make_pair(0U, &PPC::GPRCRegClass);
  14413. if (VT == MVT::f64 || VT == MVT::i64)
  14414. return std::make_pair(0U, &PPC::SPERCRegClass);
  14415. } else {
  14416. if (VT == MVT::f32 || VT == MVT::i32)
  14417. return std::make_pair(0U, &PPC::F4RCRegClass);
  14418. if (VT == MVT::f64 || VT == MVT::i64)
  14419. return std::make_pair(0U, &PPC::F8RCRegClass);
  14420. }
  14421. break;
  14422. case 'v':
  14423. if (Subtarget.hasAltivec() && VT.isVector())
  14424. return std::make_pair(0U, &PPC::VRRCRegClass);
  14425. else if (Subtarget.hasVSX())
  14426. // Scalars in Altivec registers only make sense with VSX.
  14427. return std::make_pair(0U, &PPC::VFRCRegClass);
  14428. break;
  14429. case 'y': // crrc
  14430. return std::make_pair(0U, &PPC::CRRCRegClass);
  14431. }
  14432. } else if (Constraint == "wc" && Subtarget.useCRBits()) {
  14433. // An individual CR bit.
  14434. return std::make_pair(0U, &PPC::CRBITRCRegClass);
  14435. } else if ((Constraint == "wa" || Constraint == "wd" ||
  14436. Constraint == "wf" || Constraint == "wi") &&
  14437. Subtarget.hasVSX()) {
  14438. // A VSX register for either a scalar (FP) or vector. There is no
  14439. // support for single precision scalars on subtargets prior to Power8.
  14440. if (VT.isVector())
  14441. return std::make_pair(0U, &PPC::VSRCRegClass);
  14442. if (VT == MVT::f32 && Subtarget.hasP8Vector())
  14443. return std::make_pair(0U, &PPC::VSSRCRegClass);
  14444. return std::make_pair(0U, &PPC::VSFRCRegClass);
  14445. } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
  14446. if (VT == MVT::f32 && Subtarget.hasP8Vector())
  14447. return std::make_pair(0U, &PPC::VSSRCRegClass);
  14448. else
  14449. return std::make_pair(0U, &PPC::VSFRCRegClass);
  14450. } else if (Constraint == "lr") {
  14451. if (VT == MVT::i64)
  14452. return std::make_pair(0U, &PPC::LR8RCRegClass);
  14453. else
  14454. return std::make_pair(0U, &PPC::LRRCRegClass);
  14455. }
  14456. // Handle special cases of physical registers that are not properly handled
  14457. // by the base class.
  14458. if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
  14459. // If we name a VSX register, we can't defer to the base class because it
  14460. // will not recognize the correct register (their names will be VSL{0-31}
  14461. // and V{0-31} so they won't match). So we match them here.
  14462. if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
  14463. int VSNum = atoi(Constraint.data() + 3);
  14464. assert(VSNum >= 0 && VSNum <= 63 &&
  14465. "Attempted to access a vsr out of range");
  14466. if (VSNum < 32)
  14467. return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
  14468. return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
  14469. }
  14470. // For float registers, we can't defer to the base class as it will match
  14471. // the SPILLTOVSRRC class.
  14472. if (Constraint.size() > 3 && Constraint[1] == 'f') {
  14473. int RegNum = atoi(Constraint.data() + 2);
  14474. if (RegNum > 31 || RegNum < 0)
  14475. report_fatal_error("Invalid floating point register number");
  14476. if (VT == MVT::f32 || VT == MVT::i32)
  14477. return Subtarget.hasSPE()
  14478. ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
  14479. : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
  14480. if (VT == MVT::f64 || VT == MVT::i64)
  14481. return Subtarget.hasSPE()
  14482. ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
  14483. : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
  14484. }
  14485. }
  14486. std::pair<unsigned, const TargetRegisterClass *> R =
  14487. TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
  14488. // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
  14489. // (which we call X[0-9]+). If a 64-bit value has been requested, and a
  14490. // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
  14491. // register.
  14492. // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
  14493. // the AsmName field from *RegisterInfo.td, then this would not be necessary.
  14494. if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
  14495. PPC::GPRCRegClass.contains(R.first))
  14496. return std::make_pair(TRI->getMatchingSuperReg(R.first,
  14497. PPC::sub_32, &PPC::G8RCRegClass),
  14498. &PPC::G8RCRegClass);
  14499. // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
  14500. if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) {
  14501. R.first = PPC::CR0;
  14502. R.second = &PPC::CRRCRegClass;
  14503. }
  14504. // FIXME: This warning should ideally be emitted in the front end.
  14505. const auto &TM = getTargetMachine();
  14506. if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) {
  14507. if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
  14508. (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
  14509. (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
  14510. errs() << "warning: vector registers 20 to 32 are reserved in the "
  14511. "default AIX AltiVec ABI and cannot be used\n";
  14512. }
  14513. return R;
  14514. }
  14515. /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
  14516. /// vector. If it is invalid, don't add anything to Ops.
  14517. void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
  14518. std::string &Constraint,
  14519. std::vector<SDValue>&Ops,
  14520. SelectionDAG &DAG) const {
  14521. SDValue Result;
  14522. // Only support length 1 constraints.
  14523. if (Constraint.length() > 1) return;
  14524. char Letter = Constraint[0];
  14525. switch (Letter) {
  14526. default: break;
  14527. case 'I':
  14528. case 'J':
  14529. case 'K':
  14530. case 'L':
  14531. case 'M':
  14532. case 'N':
  14533. case 'O':
  14534. case 'P': {
  14535. ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
  14536. if (!CST) return; // Must be an immediate to match.
  14537. SDLoc dl(Op);
  14538. int64_t Value = CST->getSExtValue();
  14539. EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
  14540. // numbers are printed as such.
  14541. switch (Letter) {
  14542. default: llvm_unreachable("Unknown constraint letter!");
  14543. case 'I': // "I" is a signed 16-bit constant.
  14544. if (isInt<16>(Value))
  14545. Result = DAG.getTargetConstant(Value, dl, TCVT);
  14546. break;
  14547. case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
  14548. if (isShiftedUInt<16, 16>(Value))
  14549. Result = DAG.getTargetConstant(Value, dl, TCVT);
  14550. break;
  14551. case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
  14552. if (isShiftedInt<16, 16>(Value))
  14553. Result = DAG.getTargetConstant(Value, dl, TCVT);
  14554. break;
  14555. case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
  14556. if (isUInt<16>(Value))
  14557. Result = DAG.getTargetConstant(Value, dl, TCVT);
  14558. break;
  14559. case 'M': // "M" is a constant that is greater than 31.
  14560. if (Value > 31)
  14561. Result = DAG.getTargetConstant(Value, dl, TCVT);
  14562. break;
  14563. case 'N': // "N" is a positive constant that is an exact power of two.
  14564. if (Value > 0 && isPowerOf2_64(Value))
  14565. Result = DAG.getTargetConstant(Value, dl, TCVT);
  14566. break;
  14567. case 'O': // "O" is the constant zero.
  14568. if (Value == 0)
  14569. Result = DAG.getTargetConstant(Value, dl, TCVT);
  14570. break;
  14571. case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
  14572. if (isInt<16>(-Value))
  14573. Result = DAG.getTargetConstant(Value, dl, TCVT);
  14574. break;
  14575. }
  14576. break;
  14577. }
  14578. }
  14579. if (Result.getNode()) {
  14580. Ops.push_back(Result);
  14581. return;
  14582. }
  14583. // Handle standard constraint letters.
  14584. TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
  14585. }
  14586. void PPCTargetLowering::CollectTargetIntrinsicOperands(const CallInst &I,
  14587. SmallVectorImpl<SDValue> &Ops,
  14588. SelectionDAG &DAG) const {
  14589. if (I.getNumOperands() <= 1)
  14590. return;
  14591. if (!isa<ConstantSDNode>(Ops[1].getNode()))
  14592. return;
  14593. auto IntrinsicID = cast<ConstantSDNode>(Ops[1].getNode())->getZExtValue();
  14594. if (IntrinsicID != Intrinsic::ppc_tdw && IntrinsicID != Intrinsic::ppc_tw &&
  14595. IntrinsicID != Intrinsic::ppc_trapd && IntrinsicID != Intrinsic::ppc_trap)
  14596. return;
  14597. if (I.hasMetadata("annotation")) {
  14598. MDNode *MDN = I.getMetadata("annotation");
  14599. Ops.push_back(DAG.getMDNode(MDN));
  14600. }
  14601. }
  14602. // isLegalAddressingMode - Return true if the addressing mode represented
  14603. // by AM is legal for this target, for a load/store of the specified type.
  14604. bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
  14605. const AddrMode &AM, Type *Ty,
  14606. unsigned AS,
  14607. Instruction *I) const {
  14608. // Vector type r+i form is supported since power9 as DQ form. We don't check
  14609. // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
  14610. // imm form is preferred and the offset can be adjusted to use imm form later
  14611. // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
  14612. // max offset to check legal addressing mode, we should be a little aggressive
  14613. // to contain other offsets for that LSRUse.
  14614. if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
  14615. return false;
  14616. // PPC allows a sign-extended 16-bit immediate field.
  14617. if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
  14618. return false;
  14619. // No global is ever allowed as a base.
  14620. if (AM.BaseGV)
  14621. return false;
  14622. // PPC only support r+r,
  14623. switch (AM.Scale) {
  14624. case 0: // "r+i" or just "i", depending on HasBaseReg.
  14625. break;
  14626. case 1:
  14627. if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
  14628. return false;
  14629. // Otherwise we have r+r or r+i.
  14630. break;
  14631. case 2:
  14632. if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
  14633. return false;
  14634. // Allow 2*r as r+r.
  14635. break;
  14636. default:
  14637. // No other scales are supported.
  14638. return false;
  14639. }
  14640. return true;
  14641. }
  14642. SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
  14643. SelectionDAG &DAG) const {
  14644. MachineFunction &MF = DAG.getMachineFunction();
  14645. MachineFrameInfo &MFI = MF.getFrameInfo();
  14646. MFI.setReturnAddressIsTaken(true);
  14647. if (verifyReturnAddressArgumentIsConstant(Op, DAG))
  14648. return SDValue();
  14649. SDLoc dl(Op);
  14650. unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
  14651. // Make sure the function does not optimize away the store of the RA to
  14652. // the stack.
  14653. PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  14654. FuncInfo->setLRStoreRequired();
  14655. bool isPPC64 = Subtarget.isPPC64();
  14656. auto PtrVT = getPointerTy(MF.getDataLayout());
  14657. if (Depth > 0) {
  14658. // The link register (return address) is saved in the caller's frame
  14659. // not the callee's stack frame. So we must get the caller's frame
  14660. // address and load the return address at the LR offset from there.
  14661. SDValue FrameAddr =
  14662. DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
  14663. LowerFRAMEADDR(Op, DAG), MachinePointerInfo());
  14664. SDValue Offset =
  14665. DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
  14666. isPPC64 ? MVT::i64 : MVT::i32);
  14667. return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
  14668. DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
  14669. MachinePointerInfo());
  14670. }
  14671. // Just load the return address off the stack.
  14672. SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
  14673. return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
  14674. MachinePointerInfo());
  14675. }
  14676. SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
  14677. SelectionDAG &DAG) const {
  14678. SDLoc dl(Op);
  14679. unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
  14680. MachineFunction &MF = DAG.getMachineFunction();
  14681. MachineFrameInfo &MFI = MF.getFrameInfo();
  14682. MFI.setFrameAddressIsTaken(true);
  14683. EVT PtrVT = getPointerTy(MF.getDataLayout());
  14684. bool isPPC64 = PtrVT == MVT::i64;
  14685. // Naked functions never have a frame pointer, and so we use r1. For all
  14686. // other functions, this decision must be delayed until during PEI.
  14687. unsigned FrameReg;
  14688. if (MF.getFunction().hasFnAttribute(Attribute::Naked))
  14689. FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
  14690. else
  14691. FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
  14692. SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
  14693. PtrVT);
  14694. while (Depth--)
  14695. FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
  14696. FrameAddr, MachinePointerInfo());
  14697. return FrameAddr;
  14698. }
  14699. // FIXME? Maybe this could be a TableGen attribute on some registers and
  14700. // this table could be generated automatically from RegInfo.
  14701. Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
  14702. const MachineFunction &MF) const {
  14703. bool isPPC64 = Subtarget.isPPC64();
  14704. bool is64Bit = isPPC64 && VT == LLT::scalar(64);
  14705. if (!is64Bit && VT != LLT::scalar(32))
  14706. report_fatal_error("Invalid register global variable type");
  14707. Register Reg = StringSwitch<Register>(RegName)
  14708. .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
  14709. .Case("r2", isPPC64 ? Register() : PPC::R2)
  14710. .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
  14711. .Default(Register());
  14712. if (Reg)
  14713. return Reg;
  14714. report_fatal_error("Invalid register name global variable");
  14715. }
  14716. bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
  14717. // 32-bit SVR4 ABI access everything as got-indirect.
  14718. if (Subtarget.is32BitELFABI())
  14719. return true;
  14720. // AIX accesses everything indirectly through the TOC, which is similar to
  14721. // the GOT.
  14722. if (Subtarget.isAIXABI())
  14723. return true;
  14724. CodeModel::Model CModel = getTargetMachine().getCodeModel();
  14725. // If it is small or large code model, module locals are accessed
  14726. // indirectly by loading their address from .toc/.got.
  14727. if (CModel == CodeModel::Small || CModel == CodeModel::Large)
  14728. return true;
  14729. // JumpTable and BlockAddress are accessed as got-indirect.
  14730. if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
  14731. return true;
  14732. if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
  14733. return Subtarget.isGVIndirectSymbol(G->getGlobal());
  14734. return false;
  14735. }
  14736. bool
  14737. PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
  14738. // The PowerPC target isn't yet aware of offsets.
  14739. return false;
  14740. }
  14741. bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
  14742. const CallInst &I,
  14743. MachineFunction &MF,
  14744. unsigned Intrinsic) const {
  14745. switch (Intrinsic) {
  14746. case Intrinsic::ppc_atomicrmw_xchg_i128:
  14747. case Intrinsic::ppc_atomicrmw_add_i128:
  14748. case Intrinsic::ppc_atomicrmw_sub_i128:
  14749. case Intrinsic::ppc_atomicrmw_nand_i128:
  14750. case Intrinsic::ppc_atomicrmw_and_i128:
  14751. case Intrinsic::ppc_atomicrmw_or_i128:
  14752. case Intrinsic::ppc_atomicrmw_xor_i128:
  14753. case Intrinsic::ppc_cmpxchg_i128:
  14754. Info.opc = ISD::INTRINSIC_W_CHAIN;
  14755. Info.memVT = MVT::i128;
  14756. Info.ptrVal = I.getArgOperand(0);
  14757. Info.offset = 0;
  14758. Info.align = Align(16);
  14759. Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
  14760. MachineMemOperand::MOVolatile;
  14761. return true;
  14762. case Intrinsic::ppc_atomic_load_i128:
  14763. Info.opc = ISD::INTRINSIC_W_CHAIN;
  14764. Info.memVT = MVT::i128;
  14765. Info.ptrVal = I.getArgOperand(0);
  14766. Info.offset = 0;
  14767. Info.align = Align(16);
  14768. Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
  14769. return true;
  14770. case Intrinsic::ppc_atomic_store_i128:
  14771. Info.opc = ISD::INTRINSIC_VOID;
  14772. Info.memVT = MVT::i128;
  14773. Info.ptrVal = I.getArgOperand(2);
  14774. Info.offset = 0;
  14775. Info.align = Align(16);
  14776. Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
  14777. return true;
  14778. case Intrinsic::ppc_altivec_lvx:
  14779. case Intrinsic::ppc_altivec_lvxl:
  14780. case Intrinsic::ppc_altivec_lvebx:
  14781. case Intrinsic::ppc_altivec_lvehx:
  14782. case Intrinsic::ppc_altivec_lvewx:
  14783. case Intrinsic::ppc_vsx_lxvd2x:
  14784. case Intrinsic::ppc_vsx_lxvw4x:
  14785. case Intrinsic::ppc_vsx_lxvd2x_be:
  14786. case Intrinsic::ppc_vsx_lxvw4x_be:
  14787. case Intrinsic::ppc_vsx_lxvl:
  14788. case Intrinsic::ppc_vsx_lxvll: {
  14789. EVT VT;
  14790. switch (Intrinsic) {
  14791. case Intrinsic::ppc_altivec_lvebx:
  14792. VT = MVT::i8;
  14793. break;
  14794. case Intrinsic::ppc_altivec_lvehx:
  14795. VT = MVT::i16;
  14796. break;
  14797. case Intrinsic::ppc_altivec_lvewx:
  14798. VT = MVT::i32;
  14799. break;
  14800. case Intrinsic::ppc_vsx_lxvd2x:
  14801. case Intrinsic::ppc_vsx_lxvd2x_be:
  14802. VT = MVT::v2f64;
  14803. break;
  14804. default:
  14805. VT = MVT::v4i32;
  14806. break;
  14807. }
  14808. Info.opc = ISD::INTRINSIC_W_CHAIN;
  14809. Info.memVT = VT;
  14810. Info.ptrVal = I.getArgOperand(0);
  14811. Info.offset = -VT.getStoreSize()+1;
  14812. Info.size = 2*VT.getStoreSize()-1;
  14813. Info.align = Align(1);
  14814. Info.flags = MachineMemOperand::MOLoad;
  14815. return true;
  14816. }
  14817. case Intrinsic::ppc_altivec_stvx:
  14818. case Intrinsic::ppc_altivec_stvxl:
  14819. case Intrinsic::ppc_altivec_stvebx:
  14820. case Intrinsic::ppc_altivec_stvehx:
  14821. case Intrinsic::ppc_altivec_stvewx:
  14822. case Intrinsic::ppc_vsx_stxvd2x:
  14823. case Intrinsic::ppc_vsx_stxvw4x:
  14824. case Intrinsic::ppc_vsx_stxvd2x_be:
  14825. case Intrinsic::ppc_vsx_stxvw4x_be:
  14826. case Intrinsic::ppc_vsx_stxvl:
  14827. case Intrinsic::ppc_vsx_stxvll: {
  14828. EVT VT;
  14829. switch (Intrinsic) {
  14830. case Intrinsic::ppc_altivec_stvebx:
  14831. VT = MVT::i8;
  14832. break;
  14833. case Intrinsic::ppc_altivec_stvehx:
  14834. VT = MVT::i16;
  14835. break;
  14836. case Intrinsic::ppc_altivec_stvewx:
  14837. VT = MVT::i32;
  14838. break;
  14839. case Intrinsic::ppc_vsx_stxvd2x:
  14840. case Intrinsic::ppc_vsx_stxvd2x_be:
  14841. VT = MVT::v2f64;
  14842. break;
  14843. default:
  14844. VT = MVT::v4i32;
  14845. break;
  14846. }
  14847. Info.opc = ISD::INTRINSIC_VOID;
  14848. Info.memVT = VT;
  14849. Info.ptrVal = I.getArgOperand(1);
  14850. Info.offset = -VT.getStoreSize()+1;
  14851. Info.size = 2*VT.getStoreSize()-1;
  14852. Info.align = Align(1);
  14853. Info.flags = MachineMemOperand::MOStore;
  14854. return true;
  14855. }
  14856. case Intrinsic::ppc_stdcx:
  14857. case Intrinsic::ppc_stwcx:
  14858. case Intrinsic::ppc_sthcx:
  14859. case Intrinsic::ppc_stbcx: {
  14860. EVT VT;
  14861. auto Alignment = Align(8);
  14862. switch (Intrinsic) {
  14863. case Intrinsic::ppc_stdcx:
  14864. VT = MVT::i64;
  14865. break;
  14866. case Intrinsic::ppc_stwcx:
  14867. VT = MVT::i32;
  14868. Alignment = Align(4);
  14869. break;
  14870. case Intrinsic::ppc_sthcx:
  14871. VT = MVT::i16;
  14872. Alignment = Align(2);
  14873. break;
  14874. case Intrinsic::ppc_stbcx:
  14875. VT = MVT::i8;
  14876. Alignment = Align(1);
  14877. break;
  14878. }
  14879. Info.opc = ISD::INTRINSIC_W_CHAIN;
  14880. Info.memVT = VT;
  14881. Info.ptrVal = I.getArgOperand(0);
  14882. Info.offset = 0;
  14883. Info.align = Alignment;
  14884. Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
  14885. return true;
  14886. }
  14887. default:
  14888. break;
  14889. }
  14890. return false;
  14891. }
  14892. /// It returns EVT::Other if the type should be determined using generic
  14893. /// target-independent logic.
  14894. EVT PPCTargetLowering::getOptimalMemOpType(
  14895. const MemOp &Op, const AttributeList &FuncAttributes) const {
  14896. if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
  14897. // We should use Altivec/VSX loads and stores when available. For unaligned
  14898. // addresses, unaligned VSX loads are only fast starting with the P8.
  14899. if (Subtarget.hasAltivec() && Op.size() >= 16 &&
  14900. (Op.isAligned(Align(16)) ||
  14901. ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
  14902. return MVT::v4i32;
  14903. }
  14904. if (Subtarget.isPPC64()) {
  14905. return MVT::i64;
  14906. }
  14907. return MVT::i32;
  14908. }
  14909. /// Returns true if it is beneficial to convert a load of a constant
  14910. /// to just the constant itself.
  14911. bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
  14912. Type *Ty) const {
  14913. assert(Ty->isIntegerTy());
  14914. unsigned BitSize = Ty->getPrimitiveSizeInBits();
  14915. return !(BitSize == 0 || BitSize > 64);
  14916. }
  14917. bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
  14918. if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
  14919. return false;
  14920. unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
  14921. unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
  14922. return NumBits1 == 64 && NumBits2 == 32;
  14923. }
  14924. bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
  14925. if (!VT1.isInteger() || !VT2.isInteger())
  14926. return false;
  14927. unsigned NumBits1 = VT1.getSizeInBits();
  14928. unsigned NumBits2 = VT2.getSizeInBits();
  14929. return NumBits1 == 64 && NumBits2 == 32;
  14930. }
  14931. bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
  14932. // Generally speaking, zexts are not free, but they are free when they can be
  14933. // folded with other operations.
  14934. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
  14935. EVT MemVT = LD->getMemoryVT();
  14936. if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
  14937. (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
  14938. (LD->getExtensionType() == ISD::NON_EXTLOAD ||
  14939. LD->getExtensionType() == ISD::ZEXTLOAD))
  14940. return true;
  14941. }
  14942. // FIXME: Add other cases...
  14943. // - 32-bit shifts with a zext to i64
  14944. // - zext after ctlz, bswap, etc.
  14945. // - zext after and by a constant mask
  14946. return TargetLowering::isZExtFree(Val, VT2);
  14947. }
  14948. bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
  14949. assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
  14950. "invalid fpext types");
  14951. // Extending to float128 is not free.
  14952. if (DestVT == MVT::f128)
  14953. return false;
  14954. return true;
  14955. }
  14956. bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
  14957. return isInt<16>(Imm) || isUInt<16>(Imm);
  14958. }
  14959. bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
  14960. return isInt<16>(Imm) || isUInt<16>(Imm);
  14961. }
  14962. bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align,
  14963. MachineMemOperand::Flags,
  14964. unsigned *Fast) const {
  14965. if (DisablePPCUnaligned)
  14966. return false;
  14967. // PowerPC supports unaligned memory access for simple non-vector types.
  14968. // Although accessing unaligned addresses is not as efficient as accessing
  14969. // aligned addresses, it is generally more efficient than manual expansion,
  14970. // and generally only traps for software emulation when crossing page
  14971. // boundaries.
  14972. if (!VT.isSimple())
  14973. return false;
  14974. if (VT.isFloatingPoint() && !VT.isVector() &&
  14975. !Subtarget.allowsUnalignedFPAccess())
  14976. return false;
  14977. if (VT.getSimpleVT().isVector()) {
  14978. if (Subtarget.hasVSX()) {
  14979. if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
  14980. VT != MVT::v4f32 && VT != MVT::v4i32)
  14981. return false;
  14982. } else {
  14983. return false;
  14984. }
  14985. }
  14986. if (VT == MVT::ppcf128)
  14987. return false;
  14988. if (Fast)
  14989. *Fast = 1;
  14990. return true;
  14991. }
  14992. bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
  14993. SDValue C) const {
  14994. // Check integral scalar types.
  14995. if (!VT.isScalarInteger())
  14996. return false;
  14997. if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
  14998. if (!ConstNode->getAPIntValue().isSignedIntN(64))
  14999. return false;
  15000. // This transformation will generate >= 2 operations. But the following
  15001. // cases will generate <= 2 instructions during ISEL. So exclude them.
  15002. // 1. If the constant multiplier fits 16 bits, it can be handled by one
  15003. // HW instruction, ie. MULLI
  15004. // 2. If the multiplier after shifted fits 16 bits, an extra shift
  15005. // instruction is needed than case 1, ie. MULLI and RLDICR
  15006. int64_t Imm = ConstNode->getSExtValue();
  15007. unsigned Shift = countTrailingZeros<uint64_t>(Imm);
  15008. Imm >>= Shift;
  15009. if (isInt<16>(Imm))
  15010. return false;
  15011. uint64_t UImm = static_cast<uint64_t>(Imm);
  15012. if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
  15013. isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
  15014. return true;
  15015. }
  15016. return false;
  15017. }
  15018. bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
  15019. EVT VT) const {
  15020. return isFMAFasterThanFMulAndFAdd(
  15021. MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
  15022. }
  15023. bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
  15024. Type *Ty) const {
  15025. if (Subtarget.hasSPE())
  15026. return false;
  15027. switch (Ty->getScalarType()->getTypeID()) {
  15028. case Type::FloatTyID:
  15029. case Type::DoubleTyID:
  15030. return true;
  15031. case Type::FP128TyID:
  15032. return Subtarget.hasP9Vector();
  15033. default:
  15034. return false;
  15035. }
  15036. }
  15037. // FIXME: add more patterns which are not profitable to hoist.
  15038. bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
  15039. if (!I->hasOneUse())
  15040. return true;
  15041. Instruction *User = I->user_back();
  15042. assert(User && "A single use instruction with no uses.");
  15043. switch (I->getOpcode()) {
  15044. case Instruction::FMul: {
  15045. // Don't break FMA, PowerPC prefers FMA.
  15046. if (User->getOpcode() != Instruction::FSub &&
  15047. User->getOpcode() != Instruction::FAdd)
  15048. return true;
  15049. const TargetOptions &Options = getTargetMachine().Options;
  15050. const Function *F = I->getFunction();
  15051. const DataLayout &DL = F->getParent()->getDataLayout();
  15052. Type *Ty = User->getOperand(0)->getType();
  15053. return !(
  15054. isFMAFasterThanFMulAndFAdd(*F, Ty) &&
  15055. isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
  15056. (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
  15057. }
  15058. case Instruction::Load: {
  15059. // Don't break "store (load float*)" pattern, this pattern will be combined
  15060. // to "store (load int32)" in later InstCombine pass. See function
  15061. // combineLoadToOperationType. On PowerPC, loading a float point takes more
  15062. // cycles than loading a 32 bit integer.
  15063. LoadInst *LI = cast<LoadInst>(I);
  15064. // For the loads that combineLoadToOperationType does nothing, like
  15065. // ordered load, it should be profitable to hoist them.
  15066. // For swifterror load, it can only be used for pointer to pointer type, so
  15067. // later type check should get rid of this case.
  15068. if (!LI->isUnordered())
  15069. return true;
  15070. if (User->getOpcode() != Instruction::Store)
  15071. return true;
  15072. if (I->getType()->getTypeID() != Type::FloatTyID)
  15073. return true;
  15074. return false;
  15075. }
  15076. default:
  15077. return true;
  15078. }
  15079. return true;
  15080. }
  15081. const MCPhysReg *
  15082. PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
  15083. // LR is a callee-save register, but we must treat it as clobbered by any call
  15084. // site. Hence we include LR in the scratch registers, which are in turn added
  15085. // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
  15086. // to CTR, which is used by any indirect call.
  15087. static const MCPhysReg ScratchRegs[] = {
  15088. PPC::X12, PPC::LR8, PPC::CTR8, 0
  15089. };
  15090. return ScratchRegs;
  15091. }
  15092. Register PPCTargetLowering::getExceptionPointerRegister(
  15093. const Constant *PersonalityFn) const {
  15094. return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
  15095. }
  15096. Register PPCTargetLowering::getExceptionSelectorRegister(
  15097. const Constant *PersonalityFn) const {
  15098. return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
  15099. }
  15100. bool
  15101. PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
  15102. EVT VT , unsigned DefinedValues) const {
  15103. if (VT == MVT::v2i64)
  15104. return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
  15105. if (Subtarget.hasVSX())
  15106. return true;
  15107. return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
  15108. }
  15109. Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
  15110. if (DisableILPPref || Subtarget.enableMachineScheduler())
  15111. return TargetLowering::getSchedulingPreference(N);
  15112. return Sched::ILP;
  15113. }
  15114. // Create a fast isel object.
  15115. FastISel *
  15116. PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
  15117. const TargetLibraryInfo *LibInfo) const {
  15118. return PPC::createFastISel(FuncInfo, LibInfo);
  15119. }
  15120. // 'Inverted' means the FMA opcode after negating one multiplicand.
  15121. // For example, (fma -a b c) = (fnmsub a b c)
  15122. static unsigned invertFMAOpcode(unsigned Opc) {
  15123. switch (Opc) {
  15124. default:
  15125. llvm_unreachable("Invalid FMA opcode for PowerPC!");
  15126. case ISD::FMA:
  15127. return PPCISD::FNMSUB;
  15128. case PPCISD::FNMSUB:
  15129. return ISD::FMA;
  15130. }
  15131. }
  15132. SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
  15133. bool LegalOps, bool OptForSize,
  15134. NegatibleCost &Cost,
  15135. unsigned Depth) const {
  15136. if (Depth > SelectionDAG::MaxRecursionDepth)
  15137. return SDValue();
  15138. unsigned Opc = Op.getOpcode();
  15139. EVT VT = Op.getValueType();
  15140. SDNodeFlags Flags = Op.getNode()->getFlags();
  15141. switch (Opc) {
  15142. case PPCISD::FNMSUB:
  15143. if (!Op.hasOneUse() || !isTypeLegal(VT))
  15144. break;
  15145. const TargetOptions &Options = getTargetMachine().Options;
  15146. SDValue N0 = Op.getOperand(0);
  15147. SDValue N1 = Op.getOperand(1);
  15148. SDValue N2 = Op.getOperand(2);
  15149. SDLoc Loc(Op);
  15150. NegatibleCost N2Cost = NegatibleCost::Expensive;
  15151. SDValue NegN2 =
  15152. getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
  15153. if (!NegN2)
  15154. return SDValue();
  15155. // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
  15156. // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
  15157. // These transformations may change sign of zeroes. For example,
  15158. // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
  15159. if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
  15160. // Try and choose the cheaper one to negate.
  15161. NegatibleCost N0Cost = NegatibleCost::Expensive;
  15162. SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
  15163. N0Cost, Depth + 1);
  15164. NegatibleCost N1Cost = NegatibleCost::Expensive;
  15165. SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
  15166. N1Cost, Depth + 1);
  15167. if (NegN0 && N0Cost <= N1Cost) {
  15168. Cost = std::min(N0Cost, N2Cost);
  15169. return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
  15170. } else if (NegN1) {
  15171. Cost = std::min(N1Cost, N2Cost);
  15172. return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
  15173. }
  15174. }
  15175. // (fneg (fnmsub a b c)) => (fma a b (fneg c))
  15176. if (isOperationLegal(ISD::FMA, VT)) {
  15177. Cost = N2Cost;
  15178. return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
  15179. }
  15180. break;
  15181. }
  15182. return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
  15183. Cost, Depth);
  15184. }
  15185. // Override to enable LOAD_STACK_GUARD lowering on Linux.
  15186. bool PPCTargetLowering::useLoadStackGuardNode() const {
  15187. if (!Subtarget.isTargetLinux())
  15188. return TargetLowering::useLoadStackGuardNode();
  15189. return true;
  15190. }
  15191. // Override to disable global variable loading on Linux and insert AIX canary
  15192. // word declaration.
  15193. void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
  15194. if (Subtarget.isAIXABI()) {
  15195. M.getOrInsertGlobal(AIXSSPCanaryWordName,
  15196. Type::getInt8PtrTy(M.getContext()));
  15197. return;
  15198. }
  15199. if (!Subtarget.isTargetLinux())
  15200. return TargetLowering::insertSSPDeclarations(M);
  15201. }
  15202. Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const {
  15203. if (Subtarget.isAIXABI())
  15204. return M.getGlobalVariable(AIXSSPCanaryWordName);
  15205. return TargetLowering::getSDagStackGuard(M);
  15206. }
  15207. bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
  15208. bool ForCodeSize) const {
  15209. if (!VT.isSimple() || !Subtarget.hasVSX())
  15210. return false;
  15211. switch(VT.getSimpleVT().SimpleTy) {
  15212. default:
  15213. // For FP types that are currently not supported by PPC backend, return
  15214. // false. Examples: f16, f80.
  15215. return false;
  15216. case MVT::f32:
  15217. case MVT::f64: {
  15218. if (Subtarget.hasPrefixInstrs()) {
  15219. // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP.
  15220. return true;
  15221. }
  15222. bool IsExact;
  15223. APSInt IntResult(16, false);
  15224. // The rounding mode doesn't really matter because we only care about floats
  15225. // that can be converted to integers exactly.
  15226. Imm.convertToInteger(IntResult, APFloat::rmTowardZero, &IsExact);
  15227. // For exact values in the range [-16, 15] we can materialize the float.
  15228. if (IsExact && IntResult <= 15 && IntResult >= -16)
  15229. return true;
  15230. return Imm.isZero();
  15231. }
  15232. case MVT::ppcf128:
  15233. return Imm.isPosZero();
  15234. }
  15235. }
  15236. // For vector shift operation op, fold
  15237. // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
  15238. static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
  15239. SelectionDAG &DAG) {
  15240. SDValue N0 = N->getOperand(0);
  15241. SDValue N1 = N->getOperand(1);
  15242. EVT VT = N0.getValueType();
  15243. unsigned OpSizeInBits = VT.getScalarSizeInBits();
  15244. unsigned Opcode = N->getOpcode();
  15245. unsigned TargetOpcode;
  15246. switch (Opcode) {
  15247. default:
  15248. llvm_unreachable("Unexpected shift operation");
  15249. case ISD::SHL:
  15250. TargetOpcode = PPCISD::SHL;
  15251. break;
  15252. case ISD::SRL:
  15253. TargetOpcode = PPCISD::SRL;
  15254. break;
  15255. case ISD::SRA:
  15256. TargetOpcode = PPCISD::SRA;
  15257. break;
  15258. }
  15259. if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
  15260. N1->getOpcode() == ISD::AND)
  15261. if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
  15262. if (Mask->getZExtValue() == OpSizeInBits - 1)
  15263. return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
  15264. return SDValue();
  15265. }
  15266. SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
  15267. if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
  15268. return Value;
  15269. SDValue N0 = N->getOperand(0);
  15270. ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
  15271. if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
  15272. N0.getOpcode() != ISD::SIGN_EXTEND ||
  15273. N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
  15274. N->getValueType(0) != MVT::i64)
  15275. return SDValue();
  15276. // We can't save an operation here if the value is already extended, and
  15277. // the existing shift is easier to combine.
  15278. SDValue ExtsSrc = N0.getOperand(0);
  15279. if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
  15280. ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
  15281. return SDValue();
  15282. SDLoc DL(N0);
  15283. SDValue ShiftBy = SDValue(CN1, 0);
  15284. // We want the shift amount to be i32 on the extswli, but the shift could
  15285. // have an i64.
  15286. if (ShiftBy.getValueType() == MVT::i64)
  15287. ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
  15288. return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
  15289. ShiftBy);
  15290. }
  15291. SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
  15292. if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
  15293. return Value;
  15294. return SDValue();
  15295. }
  15296. SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
  15297. if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
  15298. return Value;
  15299. return SDValue();
  15300. }
  15301. // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
  15302. // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
  15303. // When C is zero, the equation (addi Z, -C) can be simplified to Z
  15304. // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
  15305. static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
  15306. const PPCSubtarget &Subtarget) {
  15307. if (!Subtarget.isPPC64())
  15308. return SDValue();
  15309. SDValue LHS = N->getOperand(0);
  15310. SDValue RHS = N->getOperand(1);
  15311. auto isZextOfCompareWithConstant = [](SDValue Op) {
  15312. if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
  15313. Op.getValueType() != MVT::i64)
  15314. return false;
  15315. SDValue Cmp = Op.getOperand(0);
  15316. if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
  15317. Cmp.getOperand(0).getValueType() != MVT::i64)
  15318. return false;
  15319. if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
  15320. int64_t NegConstant = 0 - Constant->getSExtValue();
  15321. // Due to the limitations of the addi instruction,
  15322. // -C is required to be [-32768, 32767].
  15323. return isInt<16>(NegConstant);
  15324. }
  15325. return false;
  15326. };
  15327. bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
  15328. bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
  15329. // If there is a pattern, canonicalize a zext operand to the RHS.
  15330. if (LHSHasPattern && !RHSHasPattern)
  15331. std::swap(LHS, RHS);
  15332. else if (!LHSHasPattern && !RHSHasPattern)
  15333. return SDValue();
  15334. SDLoc DL(N);
  15335. SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
  15336. SDValue Cmp = RHS.getOperand(0);
  15337. SDValue Z = Cmp.getOperand(0);
  15338. auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1));
  15339. int64_t NegConstant = 0 - Constant->getSExtValue();
  15340. switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
  15341. default: break;
  15342. case ISD::SETNE: {
  15343. // when C == 0
  15344. // --> addze X, (addic Z, -1).carry
  15345. // /
  15346. // add X, (zext(setne Z, C))--
  15347. // \ when -32768 <= -C <= 32767 && C != 0
  15348. // --> addze X, (addic (addi Z, -C), -1).carry
  15349. SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
  15350. DAG.getConstant(NegConstant, DL, MVT::i64));
  15351. SDValue AddOrZ = NegConstant != 0 ? Add : Z;
  15352. SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
  15353. AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
  15354. return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
  15355. SDValue(Addc.getNode(), 1));
  15356. }
  15357. case ISD::SETEQ: {
  15358. // when C == 0
  15359. // --> addze X, (subfic Z, 0).carry
  15360. // /
  15361. // add X, (zext(sete Z, C))--
  15362. // \ when -32768 <= -C <= 32767 && C != 0
  15363. // --> addze X, (subfic (addi Z, -C), 0).carry
  15364. SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
  15365. DAG.getConstant(NegConstant, DL, MVT::i64));
  15366. SDValue AddOrZ = NegConstant != 0 ? Add : Z;
  15367. SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
  15368. DAG.getConstant(0, DL, MVT::i64), AddOrZ);
  15369. return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
  15370. SDValue(Subc.getNode(), 1));
  15371. }
  15372. }
  15373. return SDValue();
  15374. }
  15375. // Transform
  15376. // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
  15377. // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
  15378. // In this case both C1 and C2 must be known constants.
  15379. // C1+C2 must fit into a 34 bit signed integer.
  15380. static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
  15381. const PPCSubtarget &Subtarget) {
  15382. if (!Subtarget.isUsingPCRelativeCalls())
  15383. return SDValue();
  15384. // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
  15385. // If we find that node try to cast the Global Address and the Constant.
  15386. SDValue LHS = N->getOperand(0);
  15387. SDValue RHS = N->getOperand(1);
  15388. if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
  15389. std::swap(LHS, RHS);
  15390. if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
  15391. return SDValue();
  15392. // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
  15393. GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
  15394. ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
  15395. // Check that both casts succeeded.
  15396. if (!GSDN || !ConstNode)
  15397. return SDValue();
  15398. int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
  15399. SDLoc DL(GSDN);
  15400. // The signed int offset needs to fit in 34 bits.
  15401. if (!isInt<34>(NewOffset))
  15402. return SDValue();
  15403. // The new global address is a copy of the old global address except
  15404. // that it has the updated Offset.
  15405. SDValue GA =
  15406. DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
  15407. NewOffset, GSDN->getTargetFlags());
  15408. SDValue MatPCRel =
  15409. DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
  15410. return MatPCRel;
  15411. }
  15412. SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
  15413. if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
  15414. return Value;
  15415. if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
  15416. return Value;
  15417. return SDValue();
  15418. }
  15419. // Detect TRUNCATE operations on bitcasts of float128 values.
  15420. // What we are looking for here is the situtation where we extract a subset
  15421. // of bits from a 128 bit float.
  15422. // This can be of two forms:
  15423. // 1) BITCAST of f128 feeding TRUNCATE
  15424. // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
  15425. // The reason this is required is because we do not have a legal i128 type
  15426. // and so we want to prevent having to store the f128 and then reload part
  15427. // of it.
  15428. SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
  15429. DAGCombinerInfo &DCI) const {
  15430. // If we are using CRBits then try that first.
  15431. if (Subtarget.useCRBits()) {
  15432. // Check if CRBits did anything and return that if it did.
  15433. if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
  15434. return CRTruncValue;
  15435. }
  15436. SDLoc dl(N);
  15437. SDValue Op0 = N->getOperand(0);
  15438. // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
  15439. if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
  15440. EVT VT = N->getValueType(0);
  15441. if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
  15442. return SDValue();
  15443. SDValue Sub = Op0.getOperand(0);
  15444. if (Sub.getOpcode() == ISD::SUB) {
  15445. SDValue SubOp0 = Sub.getOperand(0);
  15446. SDValue SubOp1 = Sub.getOperand(1);
  15447. if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
  15448. (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
  15449. return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
  15450. SubOp1.getOperand(0),
  15451. DCI.DAG.getTargetConstant(0, dl, MVT::i32));
  15452. }
  15453. }
  15454. }
  15455. // Looking for a truncate of i128 to i64.
  15456. if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
  15457. return SDValue();
  15458. int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
  15459. // SRL feeding TRUNCATE.
  15460. if (Op0.getOpcode() == ISD::SRL) {
  15461. ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
  15462. // The right shift has to be by 64 bits.
  15463. if (!ConstNode || ConstNode->getZExtValue() != 64)
  15464. return SDValue();
  15465. // Switch the element number to extract.
  15466. EltToExtract = EltToExtract ? 0 : 1;
  15467. // Update Op0 past the SRL.
  15468. Op0 = Op0.getOperand(0);
  15469. }
  15470. // BITCAST feeding a TRUNCATE possibly via SRL.
  15471. if (Op0.getOpcode() == ISD::BITCAST &&
  15472. Op0.getValueType() == MVT::i128 &&
  15473. Op0.getOperand(0).getValueType() == MVT::f128) {
  15474. SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
  15475. return DCI.DAG.getNode(
  15476. ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
  15477. DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
  15478. }
  15479. return SDValue();
  15480. }
  15481. SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
  15482. SelectionDAG &DAG = DCI.DAG;
  15483. ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
  15484. if (!ConstOpOrElement)
  15485. return SDValue();
  15486. // An imul is usually smaller than the alternative sequence for legal type.
  15487. if (DAG.getMachineFunction().getFunction().hasMinSize() &&
  15488. isOperationLegal(ISD::MUL, N->getValueType(0)))
  15489. return SDValue();
  15490. auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
  15491. switch (this->Subtarget.getCPUDirective()) {
  15492. default:
  15493. // TODO: enhance the condition for subtarget before pwr8
  15494. return false;
  15495. case PPC::DIR_PWR8:
  15496. // type mul add shl
  15497. // scalar 4 1 1
  15498. // vector 7 2 2
  15499. return true;
  15500. case PPC::DIR_PWR9:
  15501. case PPC::DIR_PWR10:
  15502. case PPC::DIR_PWR_FUTURE:
  15503. // type mul add shl
  15504. // scalar 5 2 2
  15505. // vector 7 2 2
  15506. // The cycle RATIO of related operations are showed as a table above.
  15507. // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
  15508. // scalar and vector type. For 2 instrs patterns, add/sub + shl
  15509. // are 4, it is always profitable; but for 3 instrs patterns
  15510. // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
  15511. // So we should only do it for vector type.
  15512. return IsAddOne && IsNeg ? VT.isVector() : true;
  15513. }
  15514. };
  15515. EVT VT = N->getValueType(0);
  15516. SDLoc DL(N);
  15517. const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
  15518. bool IsNeg = MulAmt.isNegative();
  15519. APInt MulAmtAbs = MulAmt.abs();
  15520. if ((MulAmtAbs - 1).isPowerOf2()) {
  15521. // (mul x, 2^N + 1) => (add (shl x, N), x)
  15522. // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
  15523. if (!IsProfitable(IsNeg, true, VT))
  15524. return SDValue();
  15525. SDValue Op0 = N->getOperand(0);
  15526. SDValue Op1 =
  15527. DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
  15528. DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
  15529. SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
  15530. if (!IsNeg)
  15531. return Res;
  15532. return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
  15533. } else if ((MulAmtAbs + 1).isPowerOf2()) {
  15534. // (mul x, 2^N - 1) => (sub (shl x, N), x)
  15535. // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
  15536. if (!IsProfitable(IsNeg, false, VT))
  15537. return SDValue();
  15538. SDValue Op0 = N->getOperand(0);
  15539. SDValue Op1 =
  15540. DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
  15541. DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
  15542. if (!IsNeg)
  15543. return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
  15544. else
  15545. return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
  15546. } else {
  15547. return SDValue();
  15548. }
  15549. }
  15550. // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
  15551. // in combiner since we need to check SD flags and other subtarget features.
  15552. SDValue PPCTargetLowering::combineFMALike(SDNode *N,
  15553. DAGCombinerInfo &DCI) const {
  15554. SDValue N0 = N->getOperand(0);
  15555. SDValue N1 = N->getOperand(1);
  15556. SDValue N2 = N->getOperand(2);
  15557. SDNodeFlags Flags = N->getFlags();
  15558. EVT VT = N->getValueType(0);
  15559. SelectionDAG &DAG = DCI.DAG;
  15560. const TargetOptions &Options = getTargetMachine().Options;
  15561. unsigned Opc = N->getOpcode();
  15562. bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
  15563. bool LegalOps = !DCI.isBeforeLegalizeOps();
  15564. SDLoc Loc(N);
  15565. if (!isOperationLegal(ISD::FMA, VT))
  15566. return SDValue();
  15567. // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
  15568. // since (fnmsub a b c)=-0 while c-ab=+0.
  15569. if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
  15570. return SDValue();
  15571. // (fma (fneg a) b c) => (fnmsub a b c)
  15572. // (fnmsub (fneg a) b c) => (fma a b c)
  15573. if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
  15574. return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
  15575. // (fma a (fneg b) c) => (fnmsub a b c)
  15576. // (fnmsub a (fneg b) c) => (fma a b c)
  15577. if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
  15578. return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
  15579. return SDValue();
  15580. }
  15581. bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
  15582. // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
  15583. if (!Subtarget.is64BitELFABI())
  15584. return false;
  15585. // If not a tail call then no need to proceed.
  15586. if (!CI->isTailCall())
  15587. return false;
  15588. // If sibling calls have been disabled and tail-calls aren't guaranteed
  15589. // there is no reason to duplicate.
  15590. auto &TM = getTargetMachine();
  15591. if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
  15592. return false;
  15593. // Can't tail call a function called indirectly, or if it has variadic args.
  15594. const Function *Callee = CI->getCalledFunction();
  15595. if (!Callee || Callee->isVarArg())
  15596. return false;
  15597. // Make sure the callee and caller calling conventions are eligible for tco.
  15598. const Function *Caller = CI->getParent()->getParent();
  15599. if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
  15600. CI->getCallingConv()))
  15601. return false;
  15602. // If the function is local then we have a good chance at tail-calling it
  15603. return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
  15604. }
  15605. bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
  15606. if (!Subtarget.hasVSX())
  15607. return false;
  15608. if (Subtarget.hasP9Vector() && VT == MVT::f128)
  15609. return true;
  15610. return VT == MVT::f32 || VT == MVT::f64 ||
  15611. VT == MVT::v4f32 || VT == MVT::v2f64;
  15612. }
  15613. bool PPCTargetLowering::
  15614. isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
  15615. const Value *Mask = AndI.getOperand(1);
  15616. // If the mask is suitable for andi. or andis. we should sink the and.
  15617. if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
  15618. // Can't handle constants wider than 64-bits.
  15619. if (CI->getBitWidth() > 64)
  15620. return false;
  15621. int64_t ConstVal = CI->getZExtValue();
  15622. return isUInt<16>(ConstVal) ||
  15623. (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
  15624. }
  15625. // For non-constant masks, we can always use the record-form and.
  15626. return true;
  15627. }
  15628. // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
  15629. // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
  15630. // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
  15631. // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
  15632. // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
  15633. SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
  15634. assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
  15635. assert(Subtarget.hasP9Altivec() &&
  15636. "Only combine this when P9 altivec supported!");
  15637. EVT VT = N->getValueType(0);
  15638. if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
  15639. return SDValue();
  15640. SelectionDAG &DAG = DCI.DAG;
  15641. SDLoc dl(N);
  15642. if (N->getOperand(0).getOpcode() == ISD::SUB) {
  15643. // Even for signed integers, if it's known to be positive (as signed
  15644. // integer) due to zero-extended inputs.
  15645. unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
  15646. unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
  15647. if ((SubOpcd0 == ISD::ZERO_EXTEND ||
  15648. SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
  15649. (SubOpcd1 == ISD::ZERO_EXTEND ||
  15650. SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
  15651. return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
  15652. N->getOperand(0)->getOperand(0),
  15653. N->getOperand(0)->getOperand(1),
  15654. DAG.getTargetConstant(0, dl, MVT::i32));
  15655. }
  15656. // For type v4i32, it can be optimized with xvnegsp + vabsduw
  15657. if (N->getOperand(0).getValueType() == MVT::v4i32 &&
  15658. N->getOperand(0).hasOneUse()) {
  15659. return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
  15660. N->getOperand(0)->getOperand(0),
  15661. N->getOperand(0)->getOperand(1),
  15662. DAG.getTargetConstant(1, dl, MVT::i32));
  15663. }
  15664. }
  15665. return SDValue();
  15666. }
  15667. // For type v4i32/v8ii16/v16i8, transform
  15668. // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
  15669. // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
  15670. // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
  15671. // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
  15672. SDValue PPCTargetLowering::combineVSelect(SDNode *N,
  15673. DAGCombinerInfo &DCI) const {
  15674. assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
  15675. assert(Subtarget.hasP9Altivec() &&
  15676. "Only combine this when P9 altivec supported!");
  15677. SelectionDAG &DAG = DCI.DAG;
  15678. SDLoc dl(N);
  15679. SDValue Cond = N->getOperand(0);
  15680. SDValue TrueOpnd = N->getOperand(1);
  15681. SDValue FalseOpnd = N->getOperand(2);
  15682. EVT VT = N->getOperand(1).getValueType();
  15683. if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
  15684. FalseOpnd.getOpcode() != ISD::SUB)
  15685. return SDValue();
  15686. // ABSD only available for type v4i32/v8i16/v16i8
  15687. if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
  15688. return SDValue();
  15689. // At least to save one more dependent computation
  15690. if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
  15691. return SDValue();
  15692. ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
  15693. // Can only handle unsigned comparison here
  15694. switch (CC) {
  15695. default:
  15696. return SDValue();
  15697. case ISD::SETUGT:
  15698. case ISD::SETUGE:
  15699. break;
  15700. case ISD::SETULT:
  15701. case ISD::SETULE:
  15702. std::swap(TrueOpnd, FalseOpnd);
  15703. break;
  15704. }
  15705. SDValue CmpOpnd1 = Cond.getOperand(0);
  15706. SDValue CmpOpnd2 = Cond.getOperand(1);
  15707. // SETCC CmpOpnd1 CmpOpnd2 cond
  15708. // TrueOpnd = CmpOpnd1 - CmpOpnd2
  15709. // FalseOpnd = CmpOpnd2 - CmpOpnd1
  15710. if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
  15711. TrueOpnd.getOperand(1) == CmpOpnd2 &&
  15712. FalseOpnd.getOperand(0) == CmpOpnd2 &&
  15713. FalseOpnd.getOperand(1) == CmpOpnd1) {
  15714. return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
  15715. CmpOpnd1, CmpOpnd2,
  15716. DAG.getTargetConstant(0, dl, MVT::i32));
  15717. }
  15718. return SDValue();
  15719. }
  15720. /// getAddrModeForFlags - Based on the set of address flags, select the most
  15721. /// optimal instruction format to match by.
  15722. PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const {
  15723. // This is not a node we should be handling here.
  15724. if (Flags == PPC::MOF_None)
  15725. return PPC::AM_None;
  15726. // Unaligned D-Forms are tried first, followed by the aligned D-Forms.
  15727. for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm))
  15728. if ((Flags & FlagSet) == FlagSet)
  15729. return PPC::AM_DForm;
  15730. for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm))
  15731. if ((Flags & FlagSet) == FlagSet)
  15732. return PPC::AM_DSForm;
  15733. for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm))
  15734. if ((Flags & FlagSet) == FlagSet)
  15735. return PPC::AM_DQForm;
  15736. for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm))
  15737. if ((Flags & FlagSet) == FlagSet)
  15738. return PPC::AM_PrefixDForm;
  15739. // If no other forms are selected, return an X-Form as it is the most
  15740. // general addressing mode.
  15741. return PPC::AM_XForm;
  15742. }
  15743. /// Set alignment flags based on whether or not the Frame Index is aligned.
  15744. /// Utilized when computing flags for address computation when selecting
  15745. /// load and store instructions.
  15746. static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet,
  15747. SelectionDAG &DAG) {
  15748. bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR));
  15749. FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N);
  15750. if (!FI)
  15751. return;
  15752. const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  15753. unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value();
  15754. // If this is (add $FI, $S16Imm), the alignment flags are already set
  15755. // based on the immediate. We just need to clear the alignment flags
  15756. // if the FI alignment is weaker.
  15757. if ((FrameIndexAlign % 4) != 0)
  15758. FlagSet &= ~PPC::MOF_RPlusSImm16Mult4;
  15759. if ((FrameIndexAlign % 16) != 0)
  15760. FlagSet &= ~PPC::MOF_RPlusSImm16Mult16;
  15761. // If the address is a plain FrameIndex, set alignment flags based on
  15762. // FI alignment.
  15763. if (!IsAdd) {
  15764. if ((FrameIndexAlign % 4) == 0)
  15765. FlagSet |= PPC::MOF_RPlusSImm16Mult4;
  15766. if ((FrameIndexAlign % 16) == 0)
  15767. FlagSet |= PPC::MOF_RPlusSImm16Mult16;
  15768. }
  15769. }
  15770. /// Given a node, compute flags that are used for address computation when
  15771. /// selecting load and store instructions. The flags computed are stored in
  15772. /// FlagSet. This function takes into account whether the node is a constant,
  15773. /// an ADD, OR, or a constant, and computes the address flags accordingly.
  15774. static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet,
  15775. SelectionDAG &DAG) {
  15776. // Set the alignment flags for the node depending on if the node is
  15777. // 4-byte or 16-byte aligned.
  15778. auto SetAlignFlagsForImm = [&](uint64_t Imm) {
  15779. if ((Imm & 0x3) == 0)
  15780. FlagSet |= PPC::MOF_RPlusSImm16Mult4;
  15781. if ((Imm & 0xf) == 0)
  15782. FlagSet |= PPC::MOF_RPlusSImm16Mult16;
  15783. };
  15784. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
  15785. // All 32-bit constants can be computed as LIS + Disp.
  15786. const APInt &ConstImm = CN->getAPIntValue();
  15787. if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants.
  15788. FlagSet |= PPC::MOF_AddrIsSImm32;
  15789. SetAlignFlagsForImm(ConstImm.getZExtValue());
  15790. setAlignFlagsForFI(N, FlagSet, DAG);
  15791. }
  15792. if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants.
  15793. FlagSet |= PPC::MOF_RPlusSImm34;
  15794. else // Let constant materialization handle large constants.
  15795. FlagSet |= PPC::MOF_NotAddNorCst;
  15796. } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) {
  15797. // This address can be represented as an addition of:
  15798. // - Register + Imm16 (possibly a multiple of 4/16)
  15799. // - Register + Imm34
  15800. // - Register + PPCISD::Lo
  15801. // - Register + Register
  15802. // In any case, we won't have to match this as Base + Zero.
  15803. SDValue RHS = N.getOperand(1);
  15804. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) {
  15805. const APInt &ConstImm = CN->getAPIntValue();
  15806. if (ConstImm.isSignedIntN(16)) {
  15807. FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates.
  15808. SetAlignFlagsForImm(ConstImm.getZExtValue());
  15809. setAlignFlagsForFI(N, FlagSet, DAG);
  15810. }
  15811. if (ConstImm.isSignedIntN(34))
  15812. FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates.
  15813. else
  15814. FlagSet |= PPC::MOF_RPlusR; // Register.
  15815. } else if (RHS.getOpcode() == PPCISD::Lo &&
  15816. !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue())
  15817. FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo.
  15818. else
  15819. FlagSet |= PPC::MOF_RPlusR;
  15820. } else { // The address computation is not a constant or an addition.
  15821. setAlignFlagsForFI(N, FlagSet, DAG);
  15822. FlagSet |= PPC::MOF_NotAddNorCst;
  15823. }
  15824. }
  15825. static bool isPCRelNode(SDValue N) {
  15826. return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR ||
  15827. isValidPCRelNode<ConstantPoolSDNode>(N) ||
  15828. isValidPCRelNode<GlobalAddressSDNode>(N) ||
  15829. isValidPCRelNode<JumpTableSDNode>(N) ||
  15830. isValidPCRelNode<BlockAddressSDNode>(N));
  15831. }
  15832. /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute
  15833. /// the address flags of the load/store instruction that is to be matched.
  15834. unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N,
  15835. SelectionDAG &DAG) const {
  15836. unsigned FlagSet = PPC::MOF_None;
  15837. // Compute subtarget flags.
  15838. if (!Subtarget.hasP9Vector())
  15839. FlagSet |= PPC::MOF_SubtargetBeforeP9;
  15840. else {
  15841. FlagSet |= PPC::MOF_SubtargetP9;
  15842. if (Subtarget.hasPrefixInstrs())
  15843. FlagSet |= PPC::MOF_SubtargetP10;
  15844. }
  15845. if (Subtarget.hasSPE())
  15846. FlagSet |= PPC::MOF_SubtargetSPE;
  15847. // Check if we have a PCRel node and return early.
  15848. if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N))
  15849. return FlagSet;
  15850. // If the node is the paired load/store intrinsics, compute flags for
  15851. // address computation and return early.
  15852. unsigned ParentOp = Parent->getOpcode();
  15853. if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) ||
  15854. (ParentOp == ISD::INTRINSIC_VOID))) {
  15855. unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue();
  15856. if ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) {
  15857. SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp)
  15858. ? Parent->getOperand(2)
  15859. : Parent->getOperand(3);
  15860. computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG);
  15861. FlagSet |= PPC::MOF_Vector;
  15862. return FlagSet;
  15863. }
  15864. }
  15865. // Mark this as something we don't want to handle here if it is atomic
  15866. // or pre-increment instruction.
  15867. if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent))
  15868. if (LSB->isIndexed())
  15869. return PPC::MOF_None;
  15870. // Compute in-memory type flags. This is based on if there are scalars,
  15871. // floats or vectors.
  15872. const MemSDNode *MN = dyn_cast<MemSDNode>(Parent);
  15873. assert(MN && "Parent should be a MemSDNode!");
  15874. EVT MemVT = MN->getMemoryVT();
  15875. unsigned Size = MemVT.getSizeInBits();
  15876. if (MemVT.isScalarInteger()) {
  15877. assert(Size <= 128 &&
  15878. "Not expecting scalar integers larger than 16 bytes!");
  15879. if (Size < 32)
  15880. FlagSet |= PPC::MOF_SubWordInt;
  15881. else if (Size == 32)
  15882. FlagSet |= PPC::MOF_WordInt;
  15883. else
  15884. FlagSet |= PPC::MOF_DoubleWordInt;
  15885. } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors.
  15886. if (Size == 128)
  15887. FlagSet |= PPC::MOF_Vector;
  15888. else if (Size == 256) {
  15889. assert(Subtarget.pairedVectorMemops() &&
  15890. "256-bit vectors are only available when paired vector memops is "
  15891. "enabled!");
  15892. FlagSet |= PPC::MOF_Vector;
  15893. } else
  15894. llvm_unreachable("Not expecting illegal vectors!");
  15895. } else { // Floating point type: can be scalar, f128 or vector types.
  15896. if (Size == 32 || Size == 64)
  15897. FlagSet |= PPC::MOF_ScalarFloat;
  15898. else if (MemVT == MVT::f128 || MemVT.isVector())
  15899. FlagSet |= PPC::MOF_Vector;
  15900. else
  15901. llvm_unreachable("Not expecting illegal scalar floats!");
  15902. }
  15903. // Compute flags for address computation.
  15904. computeFlagsForAddressComputation(N, FlagSet, DAG);
  15905. // Compute type extension flags.
  15906. if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) {
  15907. switch (LN->getExtensionType()) {
  15908. case ISD::SEXTLOAD:
  15909. FlagSet |= PPC::MOF_SExt;
  15910. break;
  15911. case ISD::EXTLOAD:
  15912. case ISD::ZEXTLOAD:
  15913. FlagSet |= PPC::MOF_ZExt;
  15914. break;
  15915. case ISD::NON_EXTLOAD:
  15916. FlagSet |= PPC::MOF_NoExt;
  15917. break;
  15918. }
  15919. } else
  15920. FlagSet |= PPC::MOF_NoExt;
  15921. // For integers, no extension is the same as zero extension.
  15922. // We set the extension mode to zero extension so we don't have
  15923. // to add separate entries in AddrModesMap for loads and stores.
  15924. if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) {
  15925. FlagSet |= PPC::MOF_ZExt;
  15926. FlagSet &= ~PPC::MOF_NoExt;
  15927. }
  15928. // If we don't have prefixed instructions, 34-bit constants should be
  15929. // treated as PPC::MOF_NotAddNorCst so they can match D-Forms.
  15930. bool IsNonP1034BitConst =
  15931. ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) &
  15932. FlagSet) == PPC::MOF_RPlusSImm34;
  15933. if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR &&
  15934. IsNonP1034BitConst)
  15935. FlagSet |= PPC::MOF_NotAddNorCst;
  15936. return FlagSet;
  15937. }
  15938. /// SelectForceXFormMode - Given the specified address, force it to be
  15939. /// represented as an indexed [r+r] operation (an XForm instruction).
  15940. PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp,
  15941. SDValue &Base,
  15942. SelectionDAG &DAG) const {
  15943. PPC::AddrMode Mode = PPC::AM_XForm;
  15944. int16_t ForceXFormImm = 0;
  15945. if (provablyDisjointOr(DAG, N) &&
  15946. !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) {
  15947. Disp = N.getOperand(0);
  15948. Base = N.getOperand(1);
  15949. return Mode;
  15950. }
  15951. // If the address is the result of an add, we will utilize the fact that the
  15952. // address calculation includes an implicit add. However, we can reduce
  15953. // register pressure if we do not materialize a constant just for use as the
  15954. // index register. We only get rid of the add if it is not an add of a
  15955. // value and a 16-bit signed constant and both have a single use.
  15956. if (N.getOpcode() == ISD::ADD &&
  15957. (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) ||
  15958. !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
  15959. Disp = N.getOperand(0);
  15960. Base = N.getOperand(1);
  15961. return Mode;
  15962. }
  15963. // Otherwise, use R0 as the base register.
  15964. Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
  15965. N.getValueType());
  15966. Base = N;
  15967. return Mode;
  15968. }
  15969. bool PPCTargetLowering::splitValueIntoRegisterParts(
  15970. SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
  15971. unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
  15972. EVT ValVT = Val.getValueType();
  15973. // If we are splitting a scalar integer into f64 parts (i.e. so they
  15974. // can be placed into VFRC registers), we need to zero extend and
  15975. // bitcast the values. This will ensure the value is placed into a
  15976. // VSR using direct moves or stack operations as needed.
  15977. if (PartVT == MVT::f64 &&
  15978. (ValVT == MVT::i32 || ValVT == MVT::i16 || ValVT == MVT::i8)) {
  15979. Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
  15980. Val = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Val);
  15981. Parts[0] = Val;
  15982. return true;
  15983. }
  15984. return false;
  15985. }
  15986. SDValue PPCTargetLowering::lowerToLibCall(const char *LibCallName, SDValue Op,
  15987. SelectionDAG &DAG) const {
  15988. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  15989. TargetLowering::CallLoweringInfo CLI(DAG);
  15990. EVT RetVT = Op.getValueType();
  15991. Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
  15992. SDValue Callee =
  15993. DAG.getExternalSymbol(LibCallName, TLI.getPointerTy(DAG.getDataLayout()));
  15994. bool SignExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, false);
  15995. TargetLowering::ArgListTy Args;
  15996. TargetLowering::ArgListEntry Entry;
  15997. for (const SDValue &N : Op->op_values()) {
  15998. EVT ArgVT = N.getValueType();
  15999. Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
  16000. Entry.Node = N;
  16001. Entry.Ty = ArgTy;
  16002. Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, SignExtend);
  16003. Entry.IsZExt = !Entry.IsSExt;
  16004. Args.push_back(Entry);
  16005. }
  16006. SDValue InChain = DAG.getEntryNode();
  16007. SDValue TCChain = InChain;
  16008. const Function &F = DAG.getMachineFunction().getFunction();
  16009. bool isTailCall =
  16010. TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
  16011. (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy());
  16012. if (isTailCall)
  16013. InChain = TCChain;
  16014. CLI.setDebugLoc(SDLoc(Op))
  16015. .setChain(InChain)
  16016. .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args))
  16017. .setTailCall(isTailCall)
  16018. .setSExtResult(SignExtend)
  16019. .setZExtResult(!SignExtend)
  16020. .setIsPostTypeLegalization(true);
  16021. return TLI.LowerCallTo(CLI).first;
  16022. }
  16023. SDValue PPCTargetLowering::lowerLibCallBasedOnType(
  16024. const char *LibCallFloatName, const char *LibCallDoubleName, SDValue Op,
  16025. SelectionDAG &DAG) const {
  16026. if (Op.getValueType() == MVT::f32)
  16027. return lowerToLibCall(LibCallFloatName, Op, DAG);
  16028. if (Op.getValueType() == MVT::f64)
  16029. return lowerToLibCall(LibCallDoubleName, Op, DAG);
  16030. return SDValue();
  16031. }
  16032. bool PPCTargetLowering::isLowringToMASSFiniteSafe(SDValue Op) const {
  16033. SDNodeFlags Flags = Op.getNode()->getFlags();
  16034. return isLowringToMASSSafe(Op) && Flags.hasNoSignedZeros() &&
  16035. Flags.hasNoNaNs() && Flags.hasNoInfs();
  16036. }
  16037. bool PPCTargetLowering::isLowringToMASSSafe(SDValue Op) const {
  16038. return Op.getNode()->getFlags().hasApproximateFuncs();
  16039. }
  16040. bool PPCTargetLowering::isScalarMASSConversionEnabled() const {
  16041. return getTargetMachine().Options.PPCGenScalarMASSEntries;
  16042. }
  16043. SDValue PPCTargetLowering::lowerLibCallBase(const char *LibCallDoubleName,
  16044. const char *LibCallFloatName,
  16045. const char *LibCallDoubleNameFinite,
  16046. const char *LibCallFloatNameFinite,
  16047. SDValue Op,
  16048. SelectionDAG &DAG) const {
  16049. if (!isScalarMASSConversionEnabled() || !isLowringToMASSSafe(Op))
  16050. return SDValue();
  16051. if (!isLowringToMASSFiniteSafe(Op))
  16052. return lowerLibCallBasedOnType(LibCallFloatName, LibCallDoubleName, Op,
  16053. DAG);
  16054. return lowerLibCallBasedOnType(LibCallFloatNameFinite,
  16055. LibCallDoubleNameFinite, Op, DAG);
  16056. }
  16057. SDValue PPCTargetLowering::lowerPow(SDValue Op, SelectionDAG &DAG) const {
  16058. return lowerLibCallBase("__xl_pow", "__xl_powf", "__xl_pow_finite",
  16059. "__xl_powf_finite", Op, DAG);
  16060. }
  16061. SDValue PPCTargetLowering::lowerSin(SDValue Op, SelectionDAG &DAG) const {
  16062. return lowerLibCallBase("__xl_sin", "__xl_sinf", "__xl_sin_finite",
  16063. "__xl_sinf_finite", Op, DAG);
  16064. }
  16065. SDValue PPCTargetLowering::lowerCos(SDValue Op, SelectionDAG &DAG) const {
  16066. return lowerLibCallBase("__xl_cos", "__xl_cosf", "__xl_cos_finite",
  16067. "__xl_cosf_finite", Op, DAG);
  16068. }
  16069. SDValue PPCTargetLowering::lowerLog(SDValue Op, SelectionDAG &DAG) const {
  16070. return lowerLibCallBase("__xl_log", "__xl_logf", "__xl_log_finite",
  16071. "__xl_logf_finite", Op, DAG);
  16072. }
  16073. SDValue PPCTargetLowering::lowerLog10(SDValue Op, SelectionDAG &DAG) const {
  16074. return lowerLibCallBase("__xl_log10", "__xl_log10f", "__xl_log10_finite",
  16075. "__xl_log10f_finite", Op, DAG);
  16076. }
  16077. SDValue PPCTargetLowering::lowerExp(SDValue Op, SelectionDAG &DAG) const {
  16078. return lowerLibCallBase("__xl_exp", "__xl_expf", "__xl_exp_finite",
  16079. "__xl_expf_finite", Op, DAG);
  16080. }
  16081. // If we happen to match to an aligned D-Form, check if the Frame Index is
  16082. // adequately aligned. If it is not, reset the mode to match to X-Form.
  16083. static void setXFormForUnalignedFI(SDValue N, unsigned Flags,
  16084. PPC::AddrMode &Mode) {
  16085. if (!isa<FrameIndexSDNode>(N))
  16086. return;
  16087. if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) ||
  16088. (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16)))
  16089. Mode = PPC::AM_XForm;
  16090. }
  16091. /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode),
  16092. /// compute the address flags of the node, get the optimal address mode based
  16093. /// on the flags, and set the Base and Disp based on the address mode.
  16094. PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent,
  16095. SDValue N, SDValue &Disp,
  16096. SDValue &Base,
  16097. SelectionDAG &DAG,
  16098. MaybeAlign Align) const {
  16099. SDLoc DL(Parent);
  16100. // Compute the address flags.
  16101. unsigned Flags = computeMOFlags(Parent, N, DAG);
  16102. // Get the optimal address mode based on the Flags.
  16103. PPC::AddrMode Mode = getAddrModeForFlags(Flags);
  16104. // If the address mode is DS-Form or DQ-Form, check if the FI is aligned.
  16105. // Select an X-Form load if it is not.
  16106. setXFormForUnalignedFI(N, Flags, Mode);
  16107. // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node.
  16108. if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) {
  16109. assert(Subtarget.isUsingPCRelativeCalls() &&
  16110. "Must be using PC-Relative calls when a valid PC-Relative node is "
  16111. "present!");
  16112. Mode = PPC::AM_PCRel;
  16113. }
  16114. // Set Base and Disp accordingly depending on the address mode.
  16115. switch (Mode) {
  16116. case PPC::AM_DForm:
  16117. case PPC::AM_DSForm:
  16118. case PPC::AM_DQForm: {
  16119. // This is a register plus a 16-bit immediate. The base will be the
  16120. // register and the displacement will be the immediate unless it
  16121. // isn't sufficiently aligned.
  16122. if (Flags & PPC::MOF_RPlusSImm16) {
  16123. SDValue Op0 = N.getOperand(0);
  16124. SDValue Op1 = N.getOperand(1);
  16125. int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue();
  16126. if (!Align || isAligned(*Align, Imm)) {
  16127. Disp = DAG.getTargetConstant(Imm, DL, N.getValueType());
  16128. Base = Op0;
  16129. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) {
  16130. Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
  16131. fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
  16132. }
  16133. break;
  16134. }
  16135. }
  16136. // This is a register plus the @lo relocation. The base is the register
  16137. // and the displacement is the global address.
  16138. else if (Flags & PPC::MOF_RPlusLo) {
  16139. Disp = N.getOperand(1).getOperand(0); // The global address.
  16140. assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
  16141. Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
  16142. Disp.getOpcode() == ISD::TargetConstantPool ||
  16143. Disp.getOpcode() == ISD::TargetJumpTable);
  16144. Base = N.getOperand(0);
  16145. break;
  16146. }
  16147. // This is a constant address at most 32 bits. The base will be
  16148. // zero or load-immediate-shifted and the displacement will be
  16149. // the low 16 bits of the address.
  16150. else if (Flags & PPC::MOF_AddrIsSImm32) {
  16151. auto *CN = cast<ConstantSDNode>(N);
  16152. EVT CNType = CN->getValueType(0);
  16153. uint64_t CNImm = CN->getZExtValue();
  16154. // If this address fits entirely in a 16-bit sext immediate field, codegen
  16155. // this as "d, 0".
  16156. int16_t Imm;
  16157. if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) {
  16158. Disp = DAG.getTargetConstant(Imm, DL, CNType);
  16159. Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
  16160. CNType);
  16161. break;
  16162. }
  16163. // Handle 32-bit sext immediate with LIS + Addr mode.
  16164. if ((CNType == MVT::i32 || isInt<32>(CNImm)) &&
  16165. (!Align || isAligned(*Align, CNImm))) {
  16166. int32_t Addr = (int32_t)CNImm;
  16167. // Otherwise, break this down into LIS + Disp.
  16168. Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32);
  16169. Base =
  16170. DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32);
  16171. uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8;
  16172. Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0);
  16173. break;
  16174. }
  16175. }
  16176. // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable.
  16177. Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout()));
  16178. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
  16179. Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
  16180. fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
  16181. } else
  16182. Base = N;
  16183. break;
  16184. }
  16185. case PPC::AM_PrefixDForm: {
  16186. int64_t Imm34 = 0;
  16187. unsigned Opcode = N.getOpcode();
  16188. if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) &&
  16189. (isIntS34Immediate(N.getOperand(1), Imm34))) {
  16190. // N is an Add/OR Node, and it's operand is a 34-bit signed immediate.
  16191. Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
  16192. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
  16193. Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
  16194. else
  16195. Base = N.getOperand(0);
  16196. } else if (isIntS34Immediate(N, Imm34)) {
  16197. // The address is a 34-bit signed immediate.
  16198. Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
  16199. Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
  16200. }
  16201. break;
  16202. }
  16203. case PPC::AM_PCRel: {
  16204. // When selecting PC-Relative instructions, "Base" is not utilized as
  16205. // we select the address as [PC+imm].
  16206. Disp = N;
  16207. break;
  16208. }
  16209. case PPC::AM_None:
  16210. break;
  16211. default: { // By default, X-Form is always available to be selected.
  16212. // When a frame index is not aligned, we also match by XForm.
  16213. FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N);
  16214. Base = FI ? N : N.getOperand(1);
  16215. Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
  16216. N.getValueType())
  16217. : N.getOperand(0);
  16218. break;
  16219. }
  16220. }
  16221. return Mode;
  16222. }
  16223. CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC,
  16224. bool Return,
  16225. bool IsVarArg) const {
  16226. switch (CC) {
  16227. case CallingConv::Cold:
  16228. return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS);
  16229. default:
  16230. return CC_PPC64_ELF_FIS;
  16231. }
  16232. }
  16233. bool PPCTargetLowering::shouldInlineQuadwordAtomics() const {
  16234. // TODO: 16-byte atomic type support for AIX is in progress; we should be able
  16235. // to inline 16-byte atomic ops on AIX too in the future.
  16236. return Subtarget.isPPC64() &&
  16237. (EnableQuadwordAtomics || !Subtarget.getTargetTriple().isOSAIX()) &&
  16238. Subtarget.hasQuadwordAtomics();
  16239. }
  16240. TargetLowering::AtomicExpansionKind
  16241. PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
  16242. unsigned Size = AI->getType()->getPrimitiveSizeInBits();
  16243. if (shouldInlineQuadwordAtomics() && Size == 128)
  16244. return AtomicExpansionKind::MaskedIntrinsic;
  16245. switch (AI->getOperation()) {
  16246. case AtomicRMWInst::UIncWrap:
  16247. case AtomicRMWInst::UDecWrap:
  16248. return AtomicExpansionKind::CmpXChg;
  16249. default:
  16250. return TargetLowering::shouldExpandAtomicRMWInIR(AI);
  16251. }
  16252. llvm_unreachable("unreachable atomicrmw operation");
  16253. }
  16254. TargetLowering::AtomicExpansionKind
  16255. PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
  16256. unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits();
  16257. if (shouldInlineQuadwordAtomics() && Size == 128)
  16258. return AtomicExpansionKind::MaskedIntrinsic;
  16259. return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI);
  16260. }
  16261. static Intrinsic::ID
  16262. getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) {
  16263. switch (BinOp) {
  16264. default:
  16265. llvm_unreachable("Unexpected AtomicRMW BinOp");
  16266. case AtomicRMWInst::Xchg:
  16267. return Intrinsic::ppc_atomicrmw_xchg_i128;
  16268. case AtomicRMWInst::Add:
  16269. return Intrinsic::ppc_atomicrmw_add_i128;
  16270. case AtomicRMWInst::Sub:
  16271. return Intrinsic::ppc_atomicrmw_sub_i128;
  16272. case AtomicRMWInst::And:
  16273. return Intrinsic::ppc_atomicrmw_and_i128;
  16274. case AtomicRMWInst::Or:
  16275. return Intrinsic::ppc_atomicrmw_or_i128;
  16276. case AtomicRMWInst::Xor:
  16277. return Intrinsic::ppc_atomicrmw_xor_i128;
  16278. case AtomicRMWInst::Nand:
  16279. return Intrinsic::ppc_atomicrmw_nand_i128;
  16280. }
  16281. }
  16282. Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic(
  16283. IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
  16284. Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
  16285. assert(shouldInlineQuadwordAtomics() && "Only support quadword now");
  16286. Module *M = Builder.GetInsertBlock()->getParent()->getParent();
  16287. Type *ValTy = Incr->getType();
  16288. assert(ValTy->getPrimitiveSizeInBits() == 128);
  16289. Function *RMW = Intrinsic::getDeclaration(
  16290. M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation()));
  16291. Type *Int64Ty = Type::getInt64Ty(M->getContext());
  16292. Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo");
  16293. Value *IncrHi =
  16294. Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi");
  16295. Value *Addr =
  16296. Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
  16297. Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi});
  16298. Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
  16299. Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
  16300. Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
  16301. Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
  16302. return Builder.CreateOr(
  16303. Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
  16304. }
  16305. Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
  16306. IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
  16307. Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
  16308. assert(shouldInlineQuadwordAtomics() && "Only support quadword now");
  16309. Module *M = Builder.GetInsertBlock()->getParent()->getParent();
  16310. Type *ValTy = CmpVal->getType();
  16311. assert(ValTy->getPrimitiveSizeInBits() == 128);
  16312. Function *IntCmpXchg =
  16313. Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128);
  16314. Type *Int64Ty = Type::getInt64Ty(M->getContext());
  16315. Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo");
  16316. Value *CmpHi =
  16317. Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi");
  16318. Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo");
  16319. Value *NewHi =
  16320. Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi");
  16321. Value *Addr =
  16322. Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
  16323. emitLeadingFence(Builder, CI, Ord);
  16324. Value *LoHi =
  16325. Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi});
  16326. emitTrailingFence(Builder, CI, Ord);
  16327. Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
  16328. Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
  16329. Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
  16330. Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
  16331. return Builder.CreateOr(
  16332. Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
  16333. }