PPCInstrInfo.cpp 204 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528
  1. //===-- PPCInstrInfo.cpp - PowerPC Instruction Information ----------------===//
  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 contains the PowerPC implementation of the TargetInstrInfo class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "PPCInstrInfo.h"
  13. #include "MCTargetDesc/PPCPredicates.h"
  14. #include "PPC.h"
  15. #include "PPCHazardRecognizers.h"
  16. #include "PPCInstrBuilder.h"
  17. #include "PPCMachineFunctionInfo.h"
  18. #include "PPCTargetMachine.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/Analysis/AliasAnalysis.h"
  22. #include "llvm/CodeGen/LiveIntervals.h"
  23. #include "llvm/CodeGen/MachineConstantPool.h"
  24. #include "llvm/CodeGen/MachineFrameInfo.h"
  25. #include "llvm/CodeGen/MachineFunctionPass.h"
  26. #include "llvm/CodeGen/MachineInstrBuilder.h"
  27. #include "llvm/CodeGen/MachineMemOperand.h"
  28. #include "llvm/CodeGen/MachineRegisterInfo.h"
  29. #include "llvm/CodeGen/PseudoSourceValue.h"
  30. #include "llvm/CodeGen/RegisterClassInfo.h"
  31. #include "llvm/CodeGen/RegisterPressure.h"
  32. #include "llvm/CodeGen/ScheduleDAG.h"
  33. #include "llvm/CodeGen/SlotIndexes.h"
  34. #include "llvm/CodeGen/StackMaps.h"
  35. #include "llvm/MC/MCAsmInfo.h"
  36. #include "llvm/MC/MCInst.h"
  37. #include "llvm/MC/TargetRegistry.h"
  38. #include "llvm/Support/CommandLine.h"
  39. #include "llvm/Support/Debug.h"
  40. #include "llvm/Support/ErrorHandling.h"
  41. #include "llvm/Support/raw_ostream.h"
  42. using namespace llvm;
  43. #define DEBUG_TYPE "ppc-instr-info"
  44. #define GET_INSTRMAP_INFO
  45. #define GET_INSTRINFO_CTOR_DTOR
  46. #include "PPCGenInstrInfo.inc"
  47. STATISTIC(NumStoreSPILLVSRRCAsVec,
  48. "Number of spillvsrrc spilled to stack as vec");
  49. STATISTIC(NumStoreSPILLVSRRCAsGpr,
  50. "Number of spillvsrrc spilled to stack as gpr");
  51. STATISTIC(NumGPRtoVSRSpill, "Number of gpr spills to spillvsrrc");
  52. STATISTIC(CmpIselsConverted,
  53. "Number of ISELs that depend on comparison of constants converted");
  54. STATISTIC(MissedConvertibleImmediateInstrs,
  55. "Number of compare-immediate instructions fed by constants");
  56. STATISTIC(NumRcRotatesConvertedToRcAnd,
  57. "Number of record-form rotates converted to record-form andi");
  58. static cl::
  59. opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
  60. cl::desc("Disable analysis for CTR loops"));
  61. static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
  62. cl::desc("Disable compare instruction optimization"), cl::Hidden);
  63. static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
  64. cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
  65. cl::Hidden);
  66. static cl::opt<bool>
  67. UseOldLatencyCalc("ppc-old-latency-calc", cl::Hidden,
  68. cl::desc("Use the old (incorrect) instruction latency calculation"));
  69. static cl::opt<float>
  70. FMARPFactor("ppc-fma-rp-factor", cl::Hidden, cl::init(1.5),
  71. cl::desc("register pressure factor for the transformations."));
  72. static cl::opt<bool> EnableFMARegPressureReduction(
  73. "ppc-fma-rp-reduction", cl::Hidden, cl::init(true),
  74. cl::desc("enable register pressure reduce in machine combiner pass."));
  75. // Pin the vtable to this file.
  76. void PPCInstrInfo::anchor() {}
  77. PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI)
  78. : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP,
  79. /* CatchRetOpcode */ -1,
  80. STI.isPPC64() ? PPC::BLR8 : PPC::BLR),
  81. Subtarget(STI), RI(STI.getTargetMachine()) {}
  82. /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
  83. /// this target when scheduling the DAG.
  84. ScheduleHazardRecognizer *
  85. PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
  86. const ScheduleDAG *DAG) const {
  87. unsigned Directive =
  88. static_cast<const PPCSubtarget *>(STI)->getCPUDirective();
  89. if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
  90. Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
  91. const InstrItineraryData *II =
  92. static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData();
  93. return new ScoreboardHazardRecognizer(II, DAG);
  94. }
  95. return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
  96. }
  97. /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
  98. /// to use for this target when scheduling the DAG.
  99. ScheduleHazardRecognizer *
  100. PPCInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
  101. const ScheduleDAG *DAG) const {
  102. unsigned Directive =
  103. DAG->MF.getSubtarget<PPCSubtarget>().getCPUDirective();
  104. // FIXME: Leaving this as-is until we have POWER9 scheduling info
  105. if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8)
  106. return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
  107. // Most subtargets use a PPC970 recognizer.
  108. if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
  109. Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
  110. assert(DAG->TII && "No InstrInfo?");
  111. return new PPCHazardRecognizer970(*DAG);
  112. }
  113. return new ScoreboardHazardRecognizer(II, DAG);
  114. }
  115. unsigned PPCInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
  116. const MachineInstr &MI,
  117. unsigned *PredCost) const {
  118. if (!ItinData || UseOldLatencyCalc)
  119. return PPCGenInstrInfo::getInstrLatency(ItinData, MI, PredCost);
  120. // The default implementation of getInstrLatency calls getStageLatency, but
  121. // getStageLatency does not do the right thing for us. While we have
  122. // itinerary, most cores are fully pipelined, and so the itineraries only
  123. // express the first part of the pipeline, not every stage. Instead, we need
  124. // to use the listed output operand cycle number (using operand 0 here, which
  125. // is an output).
  126. unsigned Latency = 1;
  127. unsigned DefClass = MI.getDesc().getSchedClass();
  128. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  129. const MachineOperand &MO = MI.getOperand(i);
  130. if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
  131. continue;
  132. int Cycle = ItinData->getOperandCycle(DefClass, i);
  133. if (Cycle < 0)
  134. continue;
  135. Latency = std::max(Latency, (unsigned) Cycle);
  136. }
  137. return Latency;
  138. }
  139. int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
  140. const MachineInstr &DefMI, unsigned DefIdx,
  141. const MachineInstr &UseMI,
  142. unsigned UseIdx) const {
  143. int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
  144. UseMI, UseIdx);
  145. if (!DefMI.getParent())
  146. return Latency;
  147. const MachineOperand &DefMO = DefMI.getOperand(DefIdx);
  148. Register Reg = DefMO.getReg();
  149. bool IsRegCR;
  150. if (Register::isVirtualRegister(Reg)) {
  151. const MachineRegisterInfo *MRI =
  152. &DefMI.getParent()->getParent()->getRegInfo();
  153. IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
  154. MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
  155. } else {
  156. IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
  157. PPC::CRBITRCRegClass.contains(Reg);
  158. }
  159. if (UseMI.isBranch() && IsRegCR) {
  160. if (Latency < 0)
  161. Latency = getInstrLatency(ItinData, DefMI);
  162. // On some cores, there is an additional delay between writing to a condition
  163. // register, and using it from a branch.
  164. unsigned Directive = Subtarget.getCPUDirective();
  165. switch (Directive) {
  166. default: break;
  167. case PPC::DIR_7400:
  168. case PPC::DIR_750:
  169. case PPC::DIR_970:
  170. case PPC::DIR_E5500:
  171. case PPC::DIR_PWR4:
  172. case PPC::DIR_PWR5:
  173. case PPC::DIR_PWR5X:
  174. case PPC::DIR_PWR6:
  175. case PPC::DIR_PWR6X:
  176. case PPC::DIR_PWR7:
  177. case PPC::DIR_PWR8:
  178. // FIXME: Is this needed for POWER9?
  179. Latency += 2;
  180. break;
  181. }
  182. }
  183. return Latency;
  184. }
  185. /// This is an architecture-specific helper function of reassociateOps.
  186. /// Set special operand attributes for new instructions after reassociation.
  187. void PPCInstrInfo::setSpecialOperandAttr(MachineInstr &OldMI1,
  188. MachineInstr &OldMI2,
  189. MachineInstr &NewMI1,
  190. MachineInstr &NewMI2) const {
  191. // Propagate FP flags from the original instructions.
  192. // But clear poison-generating flags because those may not be valid now.
  193. uint16_t IntersectedFlags = OldMI1.getFlags() & OldMI2.getFlags();
  194. NewMI1.setFlags(IntersectedFlags);
  195. NewMI1.clearFlag(MachineInstr::MIFlag::NoSWrap);
  196. NewMI1.clearFlag(MachineInstr::MIFlag::NoUWrap);
  197. NewMI1.clearFlag(MachineInstr::MIFlag::IsExact);
  198. NewMI2.setFlags(IntersectedFlags);
  199. NewMI2.clearFlag(MachineInstr::MIFlag::NoSWrap);
  200. NewMI2.clearFlag(MachineInstr::MIFlag::NoUWrap);
  201. NewMI2.clearFlag(MachineInstr::MIFlag::IsExact);
  202. }
  203. void PPCInstrInfo::setSpecialOperandAttr(MachineInstr &MI,
  204. uint16_t Flags) const {
  205. MI.setFlags(Flags);
  206. MI.clearFlag(MachineInstr::MIFlag::NoSWrap);
  207. MI.clearFlag(MachineInstr::MIFlag::NoUWrap);
  208. MI.clearFlag(MachineInstr::MIFlag::IsExact);
  209. }
  210. // This function does not list all associative and commutative operations, but
  211. // only those worth feeding through the machine combiner in an attempt to
  212. // reduce the critical path. Mostly, this means floating-point operations,
  213. // because they have high latencies(>=5) (compared to other operations, such as
  214. // and/or, which are also associative and commutative, but have low latencies).
  215. bool PPCInstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst) const {
  216. switch (Inst.getOpcode()) {
  217. // Floating point:
  218. // FP Add:
  219. case PPC::FADD:
  220. case PPC::FADDS:
  221. // FP Multiply:
  222. case PPC::FMUL:
  223. case PPC::FMULS:
  224. // Altivec Add:
  225. case PPC::VADDFP:
  226. // VSX Add:
  227. case PPC::XSADDDP:
  228. case PPC::XVADDDP:
  229. case PPC::XVADDSP:
  230. case PPC::XSADDSP:
  231. // VSX Multiply:
  232. case PPC::XSMULDP:
  233. case PPC::XVMULDP:
  234. case PPC::XVMULSP:
  235. case PPC::XSMULSP:
  236. return Inst.getFlag(MachineInstr::MIFlag::FmReassoc) &&
  237. Inst.getFlag(MachineInstr::MIFlag::FmNsz);
  238. // Fixed point:
  239. // Multiply:
  240. case PPC::MULHD:
  241. case PPC::MULLD:
  242. case PPC::MULHW:
  243. case PPC::MULLW:
  244. return true;
  245. default:
  246. return false;
  247. }
  248. }
  249. #define InfoArrayIdxFMAInst 0
  250. #define InfoArrayIdxFAddInst 1
  251. #define InfoArrayIdxFMULInst 2
  252. #define InfoArrayIdxAddOpIdx 3
  253. #define InfoArrayIdxMULOpIdx 4
  254. #define InfoArrayIdxFSubInst 5
  255. // Array keeps info for FMA instructions:
  256. // Index 0(InfoArrayIdxFMAInst): FMA instruction;
  257. // Index 1(InfoArrayIdxFAddInst): ADD instruction associated with FMA;
  258. // Index 2(InfoArrayIdxFMULInst): MUL instruction associated with FMA;
  259. // Index 3(InfoArrayIdxAddOpIdx): ADD operand index in FMA operands;
  260. // Index 4(InfoArrayIdxMULOpIdx): first MUL operand index in FMA operands;
  261. // second MUL operand index is plus 1;
  262. // Index 5(InfoArrayIdxFSubInst): SUB instruction associated with FMA.
  263. static const uint16_t FMAOpIdxInfo[][6] = {
  264. // FIXME: Add more FMA instructions like XSNMADDADP and so on.
  265. {PPC::XSMADDADP, PPC::XSADDDP, PPC::XSMULDP, 1, 2, PPC::XSSUBDP},
  266. {PPC::XSMADDASP, PPC::XSADDSP, PPC::XSMULSP, 1, 2, PPC::XSSUBSP},
  267. {PPC::XVMADDADP, PPC::XVADDDP, PPC::XVMULDP, 1, 2, PPC::XVSUBDP},
  268. {PPC::XVMADDASP, PPC::XVADDSP, PPC::XVMULSP, 1, 2, PPC::XVSUBSP},
  269. {PPC::FMADD, PPC::FADD, PPC::FMUL, 3, 1, PPC::FSUB},
  270. {PPC::FMADDS, PPC::FADDS, PPC::FMULS, 3, 1, PPC::FSUBS}};
  271. // Check if an opcode is a FMA instruction. If it is, return the index in array
  272. // FMAOpIdxInfo. Otherwise, return -1.
  273. int16_t PPCInstrInfo::getFMAOpIdxInfo(unsigned Opcode) const {
  274. for (unsigned I = 0; I < array_lengthof(FMAOpIdxInfo); I++)
  275. if (FMAOpIdxInfo[I][InfoArrayIdxFMAInst] == Opcode)
  276. return I;
  277. return -1;
  278. }
  279. // On PowerPC target, we have two kinds of patterns related to FMA:
  280. // 1: Improve ILP.
  281. // Try to reassociate FMA chains like below:
  282. //
  283. // Pattern 1:
  284. // A = FADD X, Y (Leaf)
  285. // B = FMA A, M21, M22 (Prev)
  286. // C = FMA B, M31, M32 (Root)
  287. // -->
  288. // A = FMA X, M21, M22
  289. // B = FMA Y, M31, M32
  290. // C = FADD A, B
  291. //
  292. // Pattern 2:
  293. // A = FMA X, M11, M12 (Leaf)
  294. // B = FMA A, M21, M22 (Prev)
  295. // C = FMA B, M31, M32 (Root)
  296. // -->
  297. // A = FMUL M11, M12
  298. // B = FMA X, M21, M22
  299. // D = FMA A, M31, M32
  300. // C = FADD B, D
  301. //
  302. // breaking the dependency between A and B, allowing FMA to be executed in
  303. // parallel (or back-to-back in a pipeline) instead of depending on each other.
  304. //
  305. // 2: Reduce register pressure.
  306. // Try to reassociate FMA with FSUB and a constant like below:
  307. // C is a floating point const.
  308. //
  309. // Pattern 1:
  310. // A = FSUB X, Y (Leaf)
  311. // D = FMA B, C, A (Root)
  312. // -->
  313. // A = FMA B, Y, -C
  314. // D = FMA A, X, C
  315. //
  316. // Pattern 2:
  317. // A = FSUB X, Y (Leaf)
  318. // D = FMA B, A, C (Root)
  319. // -->
  320. // A = FMA B, Y, -C
  321. // D = FMA A, X, C
  322. //
  323. // Before the transformation, A must be assigned with different hardware
  324. // register with D. After the transformation, A and D must be assigned with
  325. // same hardware register due to TIE attribute of FMA instructions.
  326. //
  327. bool PPCInstrInfo::getFMAPatterns(
  328. MachineInstr &Root, SmallVectorImpl<MachineCombinerPattern> &Patterns,
  329. bool DoRegPressureReduce) const {
  330. MachineBasicBlock *MBB = Root.getParent();
  331. const MachineRegisterInfo *MRI = &MBB->getParent()->getRegInfo();
  332. const TargetRegisterInfo *TRI = &getRegisterInfo();
  333. auto IsAllOpsVirtualReg = [](const MachineInstr &Instr) {
  334. for (const auto &MO : Instr.explicit_operands())
  335. if (!(MO.isReg() && Register::isVirtualRegister(MO.getReg())))
  336. return false;
  337. return true;
  338. };
  339. auto IsReassociableAddOrSub = [&](const MachineInstr &Instr,
  340. unsigned OpType) {
  341. if (Instr.getOpcode() !=
  342. FMAOpIdxInfo[getFMAOpIdxInfo(Root.getOpcode())][OpType])
  343. return false;
  344. // Instruction can be reassociated.
  345. // fast math flags may prohibit reassociation.
  346. if (!(Instr.getFlag(MachineInstr::MIFlag::FmReassoc) &&
  347. Instr.getFlag(MachineInstr::MIFlag::FmNsz)))
  348. return false;
  349. // Instruction operands are virtual registers for reassociation.
  350. if (!IsAllOpsVirtualReg(Instr))
  351. return false;
  352. // For register pressure reassociation, the FSub must have only one use as
  353. // we want to delete the sub to save its def.
  354. if (OpType == InfoArrayIdxFSubInst &&
  355. !MRI->hasOneNonDBGUse(Instr.getOperand(0).getReg()))
  356. return false;
  357. return true;
  358. };
  359. auto IsReassociableFMA = [&](const MachineInstr &Instr, int16_t &AddOpIdx,
  360. int16_t &MulOpIdx, bool IsLeaf) {
  361. int16_t Idx = getFMAOpIdxInfo(Instr.getOpcode());
  362. if (Idx < 0)
  363. return false;
  364. // Instruction can be reassociated.
  365. // fast math flags may prohibit reassociation.
  366. if (!(Instr.getFlag(MachineInstr::MIFlag::FmReassoc) &&
  367. Instr.getFlag(MachineInstr::MIFlag::FmNsz)))
  368. return false;
  369. // Instruction operands are virtual registers for reassociation.
  370. if (!IsAllOpsVirtualReg(Instr))
  371. return false;
  372. MulOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxMULOpIdx];
  373. if (IsLeaf)
  374. return true;
  375. AddOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxAddOpIdx];
  376. const MachineOperand &OpAdd = Instr.getOperand(AddOpIdx);
  377. MachineInstr *MIAdd = MRI->getUniqueVRegDef(OpAdd.getReg());
  378. // If 'add' operand's def is not in current block, don't do ILP related opt.
  379. if (!MIAdd || MIAdd->getParent() != MBB)
  380. return false;
  381. // If this is not Leaf FMA Instr, its 'add' operand should only have one use
  382. // as this fma will be changed later.
  383. return IsLeaf ? true : MRI->hasOneNonDBGUse(OpAdd.getReg());
  384. };
  385. int16_t AddOpIdx = -1;
  386. int16_t MulOpIdx = -1;
  387. bool IsUsedOnceL = false;
  388. bool IsUsedOnceR = false;
  389. MachineInstr *MULInstrL = nullptr;
  390. MachineInstr *MULInstrR = nullptr;
  391. auto IsRPReductionCandidate = [&]() {
  392. // Currently, we only support float and double.
  393. // FIXME: add support for other types.
  394. unsigned Opcode = Root.getOpcode();
  395. if (Opcode != PPC::XSMADDASP && Opcode != PPC::XSMADDADP)
  396. return false;
  397. // Root must be a valid FMA like instruction.
  398. // Treat it as leaf as we don't care its add operand.
  399. if (IsReassociableFMA(Root, AddOpIdx, MulOpIdx, true)) {
  400. assert((MulOpIdx >= 0) && "mul operand index not right!");
  401. Register MULRegL = TRI->lookThruSingleUseCopyChain(
  402. Root.getOperand(MulOpIdx).getReg(), MRI);
  403. Register MULRegR = TRI->lookThruSingleUseCopyChain(
  404. Root.getOperand(MulOpIdx + 1).getReg(), MRI);
  405. if (!MULRegL && !MULRegR)
  406. return false;
  407. if (MULRegL && !MULRegR) {
  408. MULRegR =
  409. TRI->lookThruCopyLike(Root.getOperand(MulOpIdx + 1).getReg(), MRI);
  410. IsUsedOnceL = true;
  411. } else if (!MULRegL && MULRegR) {
  412. MULRegL =
  413. TRI->lookThruCopyLike(Root.getOperand(MulOpIdx).getReg(), MRI);
  414. IsUsedOnceR = true;
  415. } else {
  416. IsUsedOnceL = true;
  417. IsUsedOnceR = true;
  418. }
  419. if (!Register::isVirtualRegister(MULRegL) ||
  420. !Register::isVirtualRegister(MULRegR))
  421. return false;
  422. MULInstrL = MRI->getVRegDef(MULRegL);
  423. MULInstrR = MRI->getVRegDef(MULRegR);
  424. return true;
  425. }
  426. return false;
  427. };
  428. // Register pressure fma reassociation patterns.
  429. if (DoRegPressureReduce && IsRPReductionCandidate()) {
  430. assert((MULInstrL && MULInstrR) && "wrong register preduction candidate!");
  431. // Register pressure pattern 1
  432. if (isLoadFromConstantPool(MULInstrL) && IsUsedOnceR &&
  433. IsReassociableAddOrSub(*MULInstrR, InfoArrayIdxFSubInst)) {
  434. LLVM_DEBUG(dbgs() << "add pattern REASSOC_XY_BCA\n");
  435. Patterns.push_back(MachineCombinerPattern::REASSOC_XY_BCA);
  436. return true;
  437. }
  438. // Register pressure pattern 2
  439. if ((isLoadFromConstantPool(MULInstrR) && IsUsedOnceL &&
  440. IsReassociableAddOrSub(*MULInstrL, InfoArrayIdxFSubInst))) {
  441. LLVM_DEBUG(dbgs() << "add pattern REASSOC_XY_BAC\n");
  442. Patterns.push_back(MachineCombinerPattern::REASSOC_XY_BAC);
  443. return true;
  444. }
  445. }
  446. // ILP fma reassociation patterns.
  447. // Root must be a valid FMA like instruction.
  448. AddOpIdx = -1;
  449. if (!IsReassociableFMA(Root, AddOpIdx, MulOpIdx, false))
  450. return false;
  451. assert((AddOpIdx >= 0) && "add operand index not right!");
  452. Register RegB = Root.getOperand(AddOpIdx).getReg();
  453. MachineInstr *Prev = MRI->getUniqueVRegDef(RegB);
  454. // Prev must be a valid FMA like instruction.
  455. AddOpIdx = -1;
  456. if (!IsReassociableFMA(*Prev, AddOpIdx, MulOpIdx, false))
  457. return false;
  458. assert((AddOpIdx >= 0) && "add operand index not right!");
  459. Register RegA = Prev->getOperand(AddOpIdx).getReg();
  460. MachineInstr *Leaf = MRI->getUniqueVRegDef(RegA);
  461. AddOpIdx = -1;
  462. if (IsReassociableFMA(*Leaf, AddOpIdx, MulOpIdx, true)) {
  463. Patterns.push_back(MachineCombinerPattern::REASSOC_XMM_AMM_BMM);
  464. LLVM_DEBUG(dbgs() << "add pattern REASSOC_XMM_AMM_BMM\n");
  465. return true;
  466. }
  467. if (IsReassociableAddOrSub(*Leaf, InfoArrayIdxFAddInst)) {
  468. Patterns.push_back(MachineCombinerPattern::REASSOC_XY_AMM_BMM);
  469. LLVM_DEBUG(dbgs() << "add pattern REASSOC_XY_AMM_BMM\n");
  470. return true;
  471. }
  472. return false;
  473. }
  474. void PPCInstrInfo::finalizeInsInstrs(
  475. MachineInstr &Root, MachineCombinerPattern &P,
  476. SmallVectorImpl<MachineInstr *> &InsInstrs) const {
  477. assert(!InsInstrs.empty() && "Instructions set to be inserted is empty!");
  478. MachineFunction *MF = Root.getMF();
  479. MachineRegisterInfo *MRI = &MF->getRegInfo();
  480. const TargetRegisterInfo *TRI = &getRegisterInfo();
  481. MachineConstantPool *MCP = MF->getConstantPool();
  482. int16_t Idx = getFMAOpIdxInfo(Root.getOpcode());
  483. if (Idx < 0)
  484. return;
  485. uint16_t FirstMulOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxMULOpIdx];
  486. // For now we only need to fix up placeholder for register pressure reduce
  487. // patterns.
  488. Register ConstReg = 0;
  489. switch (P) {
  490. case MachineCombinerPattern::REASSOC_XY_BCA:
  491. ConstReg =
  492. TRI->lookThruCopyLike(Root.getOperand(FirstMulOpIdx).getReg(), MRI);
  493. break;
  494. case MachineCombinerPattern::REASSOC_XY_BAC:
  495. ConstReg =
  496. TRI->lookThruCopyLike(Root.getOperand(FirstMulOpIdx + 1).getReg(), MRI);
  497. break;
  498. default:
  499. // Not register pressure reduce patterns.
  500. return;
  501. }
  502. MachineInstr *ConstDefInstr = MRI->getVRegDef(ConstReg);
  503. // Get const value from const pool.
  504. const Constant *C = getConstantFromConstantPool(ConstDefInstr);
  505. assert(isa<llvm::ConstantFP>(C) && "not a valid constant!");
  506. // Get negative fp const.
  507. APFloat F1((dyn_cast<ConstantFP>(C))->getValueAPF());
  508. F1.changeSign();
  509. Constant *NegC = ConstantFP::get(dyn_cast<ConstantFP>(C)->getContext(), F1);
  510. Align Alignment = MF->getDataLayout().getPrefTypeAlign(C->getType());
  511. // Put negative fp const into constant pool.
  512. unsigned ConstPoolIdx = MCP->getConstantPoolIndex(NegC, Alignment);
  513. MachineOperand *Placeholder = nullptr;
  514. // Record the placeholder PPC::ZERO8 we add in reassociateFMA.
  515. for (auto *Inst : InsInstrs) {
  516. for (MachineOperand &Operand : Inst->explicit_operands()) {
  517. assert(Operand.isReg() && "Invalid instruction in InsInstrs!");
  518. if (Operand.getReg() == PPC::ZERO8) {
  519. Placeholder = &Operand;
  520. break;
  521. }
  522. }
  523. }
  524. assert(Placeholder && "Placeholder does not exist!");
  525. // Generate instructions to load the const fp from constant pool.
  526. // We only support PPC64 and medium code model.
  527. Register LoadNewConst =
  528. generateLoadForNewConst(ConstPoolIdx, &Root, C->getType(), InsInstrs);
  529. // Fill the placeholder with the new load from constant pool.
  530. Placeholder->setReg(LoadNewConst);
  531. }
  532. bool PPCInstrInfo::shouldReduceRegisterPressure(
  533. MachineBasicBlock *MBB, RegisterClassInfo *RegClassInfo) const {
  534. if (!EnableFMARegPressureReduction)
  535. return false;
  536. // Currently, we only enable register pressure reducing in machine combiner
  537. // for: 1: PPC64; 2: Code Model is Medium; 3: Power9 which also has vector
  538. // support.
  539. //
  540. // So we need following instructions to access a TOC entry:
  541. //
  542. // %6:g8rc_and_g8rc_nox0 = ADDIStocHA8 $x2, %const.0
  543. // %7:vssrc = DFLOADf32 target-flags(ppc-toc-lo) %const.0,
  544. // killed %6:g8rc_and_g8rc_nox0, implicit $x2 :: (load 4 from constant-pool)
  545. //
  546. // FIXME: add more supported targets, like Small and Large code model, PPC32,
  547. // AIX.
  548. if (!(Subtarget.isPPC64() && Subtarget.hasP9Vector() &&
  549. Subtarget.getTargetMachine().getCodeModel() == CodeModel::Medium))
  550. return false;
  551. const TargetRegisterInfo *TRI = &getRegisterInfo();
  552. MachineFunction *MF = MBB->getParent();
  553. MachineRegisterInfo *MRI = &MF->getRegInfo();
  554. auto GetMBBPressure = [&](MachineBasicBlock *MBB) -> std::vector<unsigned> {
  555. RegionPressure Pressure;
  556. RegPressureTracker RPTracker(Pressure);
  557. // Initialize the register pressure tracker.
  558. RPTracker.init(MBB->getParent(), RegClassInfo, nullptr, MBB, MBB->end(),
  559. /*TrackLaneMasks*/ false, /*TrackUntiedDefs=*/true);
  560. for (MachineBasicBlock::iterator MII = MBB->instr_end(),
  561. MIE = MBB->instr_begin();
  562. MII != MIE; --MII) {
  563. MachineInstr &MI = *std::prev(MII);
  564. if (MI.isDebugValue() || MI.isDebugLabel())
  565. continue;
  566. RegisterOperands RegOpers;
  567. RegOpers.collect(MI, *TRI, *MRI, false, false);
  568. RPTracker.recedeSkipDebugValues();
  569. assert(&*RPTracker.getPos() == &MI && "RPTracker sync error!");
  570. RPTracker.recede(RegOpers);
  571. }
  572. // Close the RPTracker to finalize live ins.
  573. RPTracker.closeRegion();
  574. return RPTracker.getPressure().MaxSetPressure;
  575. };
  576. // For now we only care about float and double type fma.
  577. unsigned VSSRCLimit = TRI->getRegPressureSetLimit(
  578. *MBB->getParent(), PPC::RegisterPressureSets::VSSRC);
  579. // Only reduce register pressure when pressure is high.
  580. return GetMBBPressure(MBB)[PPC::RegisterPressureSets::VSSRC] >
  581. (float)VSSRCLimit * FMARPFactor;
  582. }
  583. bool PPCInstrInfo::isLoadFromConstantPool(MachineInstr *I) const {
  584. // I has only one memory operand which is load from constant pool.
  585. if (!I->hasOneMemOperand())
  586. return false;
  587. MachineMemOperand *Op = I->memoperands()[0];
  588. return Op->isLoad() && Op->getPseudoValue() &&
  589. Op->getPseudoValue()->kind() == PseudoSourceValue::ConstantPool;
  590. }
  591. Register PPCInstrInfo::generateLoadForNewConst(
  592. unsigned Idx, MachineInstr *MI, Type *Ty,
  593. SmallVectorImpl<MachineInstr *> &InsInstrs) const {
  594. // Now we only support PPC64, Medium code model and P9 with vector.
  595. // We have immutable pattern to access const pool. See function
  596. // shouldReduceRegisterPressure.
  597. assert((Subtarget.isPPC64() && Subtarget.hasP9Vector() &&
  598. Subtarget.getTargetMachine().getCodeModel() == CodeModel::Medium) &&
  599. "Target not supported!\n");
  600. MachineFunction *MF = MI->getMF();
  601. MachineRegisterInfo *MRI = &MF->getRegInfo();
  602. // Generate ADDIStocHA8
  603. Register VReg1 = MRI->createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
  604. MachineInstrBuilder TOCOffset =
  605. BuildMI(*MF, MI->getDebugLoc(), get(PPC::ADDIStocHA8), VReg1)
  606. .addReg(PPC::X2)
  607. .addConstantPoolIndex(Idx);
  608. assert((Ty->isFloatTy() || Ty->isDoubleTy()) &&
  609. "Only float and double are supported!");
  610. unsigned LoadOpcode;
  611. // Should be float type or double type.
  612. if (Ty->isFloatTy())
  613. LoadOpcode = PPC::DFLOADf32;
  614. else
  615. LoadOpcode = PPC::DFLOADf64;
  616. const TargetRegisterClass *RC = MRI->getRegClass(MI->getOperand(0).getReg());
  617. Register VReg2 = MRI->createVirtualRegister(RC);
  618. MachineMemOperand *MMO = MF->getMachineMemOperand(
  619. MachinePointerInfo::getConstantPool(*MF), MachineMemOperand::MOLoad,
  620. Ty->getScalarSizeInBits() / 8, MF->getDataLayout().getPrefTypeAlign(Ty));
  621. // Generate Load from constant pool.
  622. MachineInstrBuilder Load =
  623. BuildMI(*MF, MI->getDebugLoc(), get(LoadOpcode), VReg2)
  624. .addConstantPoolIndex(Idx)
  625. .addReg(VReg1, getKillRegState(true))
  626. .addMemOperand(MMO);
  627. Load->getOperand(1).setTargetFlags(PPCII::MO_TOC_LO);
  628. // Insert the toc load instructions into InsInstrs.
  629. InsInstrs.insert(InsInstrs.begin(), Load);
  630. InsInstrs.insert(InsInstrs.begin(), TOCOffset);
  631. return VReg2;
  632. }
  633. // This function returns the const value in constant pool if the \p I is a load
  634. // from constant pool.
  635. const Constant *
  636. PPCInstrInfo::getConstantFromConstantPool(MachineInstr *I) const {
  637. MachineFunction *MF = I->getMF();
  638. MachineRegisterInfo *MRI = &MF->getRegInfo();
  639. MachineConstantPool *MCP = MF->getConstantPool();
  640. assert(I->mayLoad() && "Should be a load instruction.\n");
  641. for (auto MO : I->uses()) {
  642. if (!MO.isReg())
  643. continue;
  644. Register Reg = MO.getReg();
  645. if (Reg == 0 || !Register::isVirtualRegister(Reg))
  646. continue;
  647. // Find the toc address.
  648. MachineInstr *DefMI = MRI->getVRegDef(Reg);
  649. for (auto MO2 : DefMI->uses())
  650. if (MO2.isCPI())
  651. return (MCP->getConstants())[MO2.getIndex()].Val.ConstVal;
  652. }
  653. return nullptr;
  654. }
  655. bool PPCInstrInfo::getMachineCombinerPatterns(
  656. MachineInstr &Root, SmallVectorImpl<MachineCombinerPattern> &Patterns,
  657. bool DoRegPressureReduce) const {
  658. // Using the machine combiner in this way is potentially expensive, so
  659. // restrict to when aggressive optimizations are desired.
  660. if (Subtarget.getTargetMachine().getOptLevel() != CodeGenOpt::Aggressive)
  661. return false;
  662. if (getFMAPatterns(Root, Patterns, DoRegPressureReduce))
  663. return true;
  664. return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns,
  665. DoRegPressureReduce);
  666. }
  667. void PPCInstrInfo::genAlternativeCodeSequence(
  668. MachineInstr &Root, MachineCombinerPattern Pattern,
  669. SmallVectorImpl<MachineInstr *> &InsInstrs,
  670. SmallVectorImpl<MachineInstr *> &DelInstrs,
  671. DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const {
  672. switch (Pattern) {
  673. case MachineCombinerPattern::REASSOC_XY_AMM_BMM:
  674. case MachineCombinerPattern::REASSOC_XMM_AMM_BMM:
  675. case MachineCombinerPattern::REASSOC_XY_BCA:
  676. case MachineCombinerPattern::REASSOC_XY_BAC:
  677. reassociateFMA(Root, Pattern, InsInstrs, DelInstrs, InstrIdxForVirtReg);
  678. break;
  679. default:
  680. // Reassociate default patterns.
  681. TargetInstrInfo::genAlternativeCodeSequence(Root, Pattern, InsInstrs,
  682. DelInstrs, InstrIdxForVirtReg);
  683. break;
  684. }
  685. }
  686. void PPCInstrInfo::reassociateFMA(
  687. MachineInstr &Root, MachineCombinerPattern Pattern,
  688. SmallVectorImpl<MachineInstr *> &InsInstrs,
  689. SmallVectorImpl<MachineInstr *> &DelInstrs,
  690. DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const {
  691. MachineFunction *MF = Root.getMF();
  692. MachineRegisterInfo &MRI = MF->getRegInfo();
  693. const TargetRegisterInfo *TRI = &getRegisterInfo();
  694. MachineOperand &OpC = Root.getOperand(0);
  695. Register RegC = OpC.getReg();
  696. const TargetRegisterClass *RC = MRI.getRegClass(RegC);
  697. MRI.constrainRegClass(RegC, RC);
  698. unsigned FmaOp = Root.getOpcode();
  699. int16_t Idx = getFMAOpIdxInfo(FmaOp);
  700. assert(Idx >= 0 && "Root must be a FMA instruction");
  701. bool IsILPReassociate =
  702. (Pattern == MachineCombinerPattern::REASSOC_XY_AMM_BMM) ||
  703. (Pattern == MachineCombinerPattern::REASSOC_XMM_AMM_BMM);
  704. uint16_t AddOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxAddOpIdx];
  705. uint16_t FirstMulOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxMULOpIdx];
  706. MachineInstr *Prev = nullptr;
  707. MachineInstr *Leaf = nullptr;
  708. switch (Pattern) {
  709. default:
  710. llvm_unreachable("not recognized pattern!");
  711. case MachineCombinerPattern::REASSOC_XY_AMM_BMM:
  712. case MachineCombinerPattern::REASSOC_XMM_AMM_BMM:
  713. Prev = MRI.getUniqueVRegDef(Root.getOperand(AddOpIdx).getReg());
  714. Leaf = MRI.getUniqueVRegDef(Prev->getOperand(AddOpIdx).getReg());
  715. break;
  716. case MachineCombinerPattern::REASSOC_XY_BAC: {
  717. Register MULReg =
  718. TRI->lookThruCopyLike(Root.getOperand(FirstMulOpIdx).getReg(), &MRI);
  719. Leaf = MRI.getVRegDef(MULReg);
  720. break;
  721. }
  722. case MachineCombinerPattern::REASSOC_XY_BCA: {
  723. Register MULReg = TRI->lookThruCopyLike(
  724. Root.getOperand(FirstMulOpIdx + 1).getReg(), &MRI);
  725. Leaf = MRI.getVRegDef(MULReg);
  726. break;
  727. }
  728. }
  729. uint16_t IntersectedFlags = 0;
  730. if (IsILPReassociate)
  731. IntersectedFlags = Root.getFlags() & Prev->getFlags() & Leaf->getFlags();
  732. else
  733. IntersectedFlags = Root.getFlags() & Leaf->getFlags();
  734. auto GetOperandInfo = [&](const MachineOperand &Operand, Register &Reg,
  735. bool &KillFlag) {
  736. Reg = Operand.getReg();
  737. MRI.constrainRegClass(Reg, RC);
  738. KillFlag = Operand.isKill();
  739. };
  740. auto GetFMAInstrInfo = [&](const MachineInstr &Instr, Register &MulOp1,
  741. Register &MulOp2, Register &AddOp,
  742. bool &MulOp1KillFlag, bool &MulOp2KillFlag,
  743. bool &AddOpKillFlag) {
  744. GetOperandInfo(Instr.getOperand(FirstMulOpIdx), MulOp1, MulOp1KillFlag);
  745. GetOperandInfo(Instr.getOperand(FirstMulOpIdx + 1), MulOp2, MulOp2KillFlag);
  746. GetOperandInfo(Instr.getOperand(AddOpIdx), AddOp, AddOpKillFlag);
  747. };
  748. Register RegM11, RegM12, RegX, RegY, RegM21, RegM22, RegM31, RegM32, RegA11,
  749. RegA21, RegB;
  750. bool KillX = false, KillY = false, KillM11 = false, KillM12 = false,
  751. KillM21 = false, KillM22 = false, KillM31 = false, KillM32 = false,
  752. KillA11 = false, KillA21 = false, KillB = false;
  753. GetFMAInstrInfo(Root, RegM31, RegM32, RegB, KillM31, KillM32, KillB);
  754. if (IsILPReassociate)
  755. GetFMAInstrInfo(*Prev, RegM21, RegM22, RegA21, KillM21, KillM22, KillA21);
  756. if (Pattern == MachineCombinerPattern::REASSOC_XMM_AMM_BMM) {
  757. GetFMAInstrInfo(*Leaf, RegM11, RegM12, RegA11, KillM11, KillM12, KillA11);
  758. GetOperandInfo(Leaf->getOperand(AddOpIdx), RegX, KillX);
  759. } else if (Pattern == MachineCombinerPattern::REASSOC_XY_AMM_BMM) {
  760. GetOperandInfo(Leaf->getOperand(1), RegX, KillX);
  761. GetOperandInfo(Leaf->getOperand(2), RegY, KillY);
  762. } else {
  763. // Get FSUB instruction info.
  764. GetOperandInfo(Leaf->getOperand(1), RegX, KillX);
  765. GetOperandInfo(Leaf->getOperand(2), RegY, KillY);
  766. }
  767. // Create new virtual registers for the new results instead of
  768. // recycling legacy ones because the MachineCombiner's computation of the
  769. // critical path requires a new register definition rather than an existing
  770. // one.
  771. // For register pressure reassociation, we only need create one virtual
  772. // register for the new fma.
  773. Register NewVRA = MRI.createVirtualRegister(RC);
  774. InstrIdxForVirtReg.insert(std::make_pair(NewVRA, 0));
  775. Register NewVRB = 0;
  776. if (IsILPReassociate) {
  777. NewVRB = MRI.createVirtualRegister(RC);
  778. InstrIdxForVirtReg.insert(std::make_pair(NewVRB, 1));
  779. }
  780. Register NewVRD = 0;
  781. if (Pattern == MachineCombinerPattern::REASSOC_XMM_AMM_BMM) {
  782. NewVRD = MRI.createVirtualRegister(RC);
  783. InstrIdxForVirtReg.insert(std::make_pair(NewVRD, 2));
  784. }
  785. auto AdjustOperandOrder = [&](MachineInstr *MI, Register RegAdd, bool KillAdd,
  786. Register RegMul1, bool KillRegMul1,
  787. Register RegMul2, bool KillRegMul2) {
  788. MI->getOperand(AddOpIdx).setReg(RegAdd);
  789. MI->getOperand(AddOpIdx).setIsKill(KillAdd);
  790. MI->getOperand(FirstMulOpIdx).setReg(RegMul1);
  791. MI->getOperand(FirstMulOpIdx).setIsKill(KillRegMul1);
  792. MI->getOperand(FirstMulOpIdx + 1).setReg(RegMul2);
  793. MI->getOperand(FirstMulOpIdx + 1).setIsKill(KillRegMul2);
  794. };
  795. MachineInstrBuilder NewARegPressure, NewCRegPressure;
  796. switch (Pattern) {
  797. default:
  798. llvm_unreachable("not recognized pattern!");
  799. case MachineCombinerPattern::REASSOC_XY_AMM_BMM: {
  800. // Create new instructions for insertion.
  801. MachineInstrBuilder MINewB =
  802. BuildMI(*MF, Prev->getDebugLoc(), get(FmaOp), NewVRB)
  803. .addReg(RegX, getKillRegState(KillX))
  804. .addReg(RegM21, getKillRegState(KillM21))
  805. .addReg(RegM22, getKillRegState(KillM22));
  806. MachineInstrBuilder MINewA =
  807. BuildMI(*MF, Root.getDebugLoc(), get(FmaOp), NewVRA)
  808. .addReg(RegY, getKillRegState(KillY))
  809. .addReg(RegM31, getKillRegState(KillM31))
  810. .addReg(RegM32, getKillRegState(KillM32));
  811. // If AddOpIdx is not 1, adjust the order.
  812. if (AddOpIdx != 1) {
  813. AdjustOperandOrder(MINewB, RegX, KillX, RegM21, KillM21, RegM22, KillM22);
  814. AdjustOperandOrder(MINewA, RegY, KillY, RegM31, KillM31, RegM32, KillM32);
  815. }
  816. MachineInstrBuilder MINewC =
  817. BuildMI(*MF, Root.getDebugLoc(),
  818. get(FMAOpIdxInfo[Idx][InfoArrayIdxFAddInst]), RegC)
  819. .addReg(NewVRB, getKillRegState(true))
  820. .addReg(NewVRA, getKillRegState(true));
  821. // Update flags for newly created instructions.
  822. setSpecialOperandAttr(*MINewA, IntersectedFlags);
  823. setSpecialOperandAttr(*MINewB, IntersectedFlags);
  824. setSpecialOperandAttr(*MINewC, IntersectedFlags);
  825. // Record new instructions for insertion.
  826. InsInstrs.push_back(MINewA);
  827. InsInstrs.push_back(MINewB);
  828. InsInstrs.push_back(MINewC);
  829. break;
  830. }
  831. case MachineCombinerPattern::REASSOC_XMM_AMM_BMM: {
  832. assert(NewVRD && "new FMA register not created!");
  833. // Create new instructions for insertion.
  834. MachineInstrBuilder MINewA =
  835. BuildMI(*MF, Leaf->getDebugLoc(),
  836. get(FMAOpIdxInfo[Idx][InfoArrayIdxFMULInst]), NewVRA)
  837. .addReg(RegM11, getKillRegState(KillM11))
  838. .addReg(RegM12, getKillRegState(KillM12));
  839. MachineInstrBuilder MINewB =
  840. BuildMI(*MF, Prev->getDebugLoc(), get(FmaOp), NewVRB)
  841. .addReg(RegX, getKillRegState(KillX))
  842. .addReg(RegM21, getKillRegState(KillM21))
  843. .addReg(RegM22, getKillRegState(KillM22));
  844. MachineInstrBuilder MINewD =
  845. BuildMI(*MF, Root.getDebugLoc(), get(FmaOp), NewVRD)
  846. .addReg(NewVRA, getKillRegState(true))
  847. .addReg(RegM31, getKillRegState(KillM31))
  848. .addReg(RegM32, getKillRegState(KillM32));
  849. // If AddOpIdx is not 1, adjust the order.
  850. if (AddOpIdx != 1) {
  851. AdjustOperandOrder(MINewB, RegX, KillX, RegM21, KillM21, RegM22, KillM22);
  852. AdjustOperandOrder(MINewD, NewVRA, true, RegM31, KillM31, RegM32,
  853. KillM32);
  854. }
  855. MachineInstrBuilder MINewC =
  856. BuildMI(*MF, Root.getDebugLoc(),
  857. get(FMAOpIdxInfo[Idx][InfoArrayIdxFAddInst]), RegC)
  858. .addReg(NewVRB, getKillRegState(true))
  859. .addReg(NewVRD, getKillRegState(true));
  860. // Update flags for newly created instructions.
  861. setSpecialOperandAttr(*MINewA, IntersectedFlags);
  862. setSpecialOperandAttr(*MINewB, IntersectedFlags);
  863. setSpecialOperandAttr(*MINewD, IntersectedFlags);
  864. setSpecialOperandAttr(*MINewC, IntersectedFlags);
  865. // Record new instructions for insertion.
  866. InsInstrs.push_back(MINewA);
  867. InsInstrs.push_back(MINewB);
  868. InsInstrs.push_back(MINewD);
  869. InsInstrs.push_back(MINewC);
  870. break;
  871. }
  872. case MachineCombinerPattern::REASSOC_XY_BAC:
  873. case MachineCombinerPattern::REASSOC_XY_BCA: {
  874. Register VarReg;
  875. bool KillVarReg = false;
  876. if (Pattern == MachineCombinerPattern::REASSOC_XY_BCA) {
  877. VarReg = RegM31;
  878. KillVarReg = KillM31;
  879. } else {
  880. VarReg = RegM32;
  881. KillVarReg = KillM32;
  882. }
  883. // We don't want to get negative const from memory pool too early, as the
  884. // created entry will not be deleted even if it has no users. Since all
  885. // operand of Leaf and Root are virtual register, we use zero register
  886. // here as a placeholder. When the InsInstrs is selected in
  887. // MachineCombiner, we call finalizeInsInstrs to replace the zero register
  888. // with a virtual register which is a load from constant pool.
  889. NewARegPressure = BuildMI(*MF, Root.getDebugLoc(), get(FmaOp), NewVRA)
  890. .addReg(RegB, getKillRegState(RegB))
  891. .addReg(RegY, getKillRegState(KillY))
  892. .addReg(PPC::ZERO8);
  893. NewCRegPressure = BuildMI(*MF, Root.getDebugLoc(), get(FmaOp), RegC)
  894. .addReg(NewVRA, getKillRegState(true))
  895. .addReg(RegX, getKillRegState(KillX))
  896. .addReg(VarReg, getKillRegState(KillVarReg));
  897. // For now, we only support xsmaddadp/xsmaddasp, their add operand are
  898. // both at index 1, no need to adjust.
  899. // FIXME: when add more fma instructions support, like fma/fmas, adjust
  900. // the operand index here.
  901. break;
  902. }
  903. }
  904. if (!IsILPReassociate) {
  905. setSpecialOperandAttr(*NewARegPressure, IntersectedFlags);
  906. setSpecialOperandAttr(*NewCRegPressure, IntersectedFlags);
  907. InsInstrs.push_back(NewARegPressure);
  908. InsInstrs.push_back(NewCRegPressure);
  909. }
  910. assert(!InsInstrs.empty() &&
  911. "Insertion instructions set should not be empty!");
  912. // Record old instructions for deletion.
  913. DelInstrs.push_back(Leaf);
  914. if (IsILPReassociate)
  915. DelInstrs.push_back(Prev);
  916. DelInstrs.push_back(&Root);
  917. }
  918. // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
  919. bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
  920. Register &SrcReg, Register &DstReg,
  921. unsigned &SubIdx) const {
  922. switch (MI.getOpcode()) {
  923. default: return false;
  924. case PPC::EXTSW:
  925. case PPC::EXTSW_32:
  926. case PPC::EXTSW_32_64:
  927. SrcReg = MI.getOperand(1).getReg();
  928. DstReg = MI.getOperand(0).getReg();
  929. SubIdx = PPC::sub_32;
  930. return true;
  931. }
  932. }
  933. unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
  934. int &FrameIndex) const {
  935. unsigned Opcode = MI.getOpcode();
  936. const unsigned *OpcodesForSpill = getLoadOpcodesForSpillArray();
  937. const unsigned *End = OpcodesForSpill + SOK_LastOpcodeSpill;
  938. if (End != std::find(OpcodesForSpill, End, Opcode)) {
  939. // Check for the operands added by addFrameReference (the immediate is the
  940. // offset which defaults to 0).
  941. if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() &&
  942. MI.getOperand(2).isFI()) {
  943. FrameIndex = MI.getOperand(2).getIndex();
  944. return MI.getOperand(0).getReg();
  945. }
  946. }
  947. return 0;
  948. }
  949. // For opcodes with the ReMaterializable flag set, this function is called to
  950. // verify the instruction is really rematable.
  951. bool PPCInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
  952. AliasAnalysis *AA) const {
  953. switch (MI.getOpcode()) {
  954. default:
  955. // This function should only be called for opcodes with the ReMaterializable
  956. // flag set.
  957. llvm_unreachable("Unknown rematerializable operation!");
  958. break;
  959. case PPC::LI:
  960. case PPC::LI8:
  961. case PPC::PLI:
  962. case PPC::PLI8:
  963. case PPC::LIS:
  964. case PPC::LIS8:
  965. case PPC::ADDIStocHA:
  966. case PPC::ADDIStocHA8:
  967. case PPC::ADDItocL:
  968. case PPC::LOAD_STACK_GUARD:
  969. case PPC::XXLXORz:
  970. case PPC::XXLXORspz:
  971. case PPC::XXLXORdpz:
  972. case PPC::XXLEQVOnes:
  973. case PPC::XXSPLTI32DX:
  974. case PPC::XXSPLTIW:
  975. case PPC::XXSPLTIDP:
  976. case PPC::V_SET0B:
  977. case PPC::V_SET0H:
  978. case PPC::V_SET0:
  979. case PPC::V_SETALLONESB:
  980. case PPC::V_SETALLONESH:
  981. case PPC::V_SETALLONES:
  982. case PPC::CRSET:
  983. case PPC::CRUNSET:
  984. case PPC::XXSETACCZ:
  985. return true;
  986. }
  987. return false;
  988. }
  989. unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
  990. int &FrameIndex) const {
  991. unsigned Opcode = MI.getOpcode();
  992. const unsigned *OpcodesForSpill = getStoreOpcodesForSpillArray();
  993. const unsigned *End = OpcodesForSpill + SOK_LastOpcodeSpill;
  994. if (End != std::find(OpcodesForSpill, End, Opcode)) {
  995. if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() &&
  996. MI.getOperand(2).isFI()) {
  997. FrameIndex = MI.getOperand(2).getIndex();
  998. return MI.getOperand(0).getReg();
  999. }
  1000. }
  1001. return 0;
  1002. }
  1003. MachineInstr *PPCInstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI,
  1004. unsigned OpIdx1,
  1005. unsigned OpIdx2) const {
  1006. MachineFunction &MF = *MI.getParent()->getParent();
  1007. // Normal instructions can be commuted the obvious way.
  1008. if (MI.getOpcode() != PPC::RLWIMI && MI.getOpcode() != PPC::RLWIMI_rec)
  1009. return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
  1010. // Note that RLWIMI can be commuted as a 32-bit instruction, but not as a
  1011. // 64-bit instruction (so we don't handle PPC::RLWIMI8 here), because
  1012. // changing the relative order of the mask operands might change what happens
  1013. // to the high-bits of the mask (and, thus, the result).
  1014. // Cannot commute if it has a non-zero rotate count.
  1015. if (MI.getOperand(3).getImm() != 0)
  1016. return nullptr;
  1017. // If we have a zero rotate count, we have:
  1018. // M = mask(MB,ME)
  1019. // Op0 = (Op1 & ~M) | (Op2 & M)
  1020. // Change this to:
  1021. // M = mask((ME+1)&31, (MB-1)&31)
  1022. // Op0 = (Op2 & ~M) | (Op1 & M)
  1023. // Swap op1/op2
  1024. assert(((OpIdx1 == 1 && OpIdx2 == 2) || (OpIdx1 == 2 && OpIdx2 == 1)) &&
  1025. "Only the operands 1 and 2 can be swapped in RLSIMI/RLWIMI_rec.");
  1026. Register Reg0 = MI.getOperand(0).getReg();
  1027. Register Reg1 = MI.getOperand(1).getReg();
  1028. Register Reg2 = MI.getOperand(2).getReg();
  1029. unsigned SubReg1 = MI.getOperand(1).getSubReg();
  1030. unsigned SubReg2 = MI.getOperand(2).getSubReg();
  1031. bool Reg1IsKill = MI.getOperand(1).isKill();
  1032. bool Reg2IsKill = MI.getOperand(2).isKill();
  1033. bool ChangeReg0 = false;
  1034. // If machine instrs are no longer in two-address forms, update
  1035. // destination register as well.
  1036. if (Reg0 == Reg1) {
  1037. // Must be two address instruction!
  1038. assert(MI.getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
  1039. "Expecting a two-address instruction!");
  1040. assert(MI.getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
  1041. Reg2IsKill = false;
  1042. ChangeReg0 = true;
  1043. }
  1044. // Masks.
  1045. unsigned MB = MI.getOperand(4).getImm();
  1046. unsigned ME = MI.getOperand(5).getImm();
  1047. // We can't commute a trivial mask (there is no way to represent an all-zero
  1048. // mask).
  1049. if (MB == 0 && ME == 31)
  1050. return nullptr;
  1051. if (NewMI) {
  1052. // Create a new instruction.
  1053. Register Reg0 = ChangeReg0 ? Reg2 : MI.getOperand(0).getReg();
  1054. bool Reg0IsDead = MI.getOperand(0).isDead();
  1055. return BuildMI(MF, MI.getDebugLoc(), MI.getDesc())
  1056. .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
  1057. .addReg(Reg2, getKillRegState(Reg2IsKill))
  1058. .addReg(Reg1, getKillRegState(Reg1IsKill))
  1059. .addImm((ME + 1) & 31)
  1060. .addImm((MB - 1) & 31);
  1061. }
  1062. if (ChangeReg0) {
  1063. MI.getOperand(0).setReg(Reg2);
  1064. MI.getOperand(0).setSubReg(SubReg2);
  1065. }
  1066. MI.getOperand(2).setReg(Reg1);
  1067. MI.getOperand(1).setReg(Reg2);
  1068. MI.getOperand(2).setSubReg(SubReg1);
  1069. MI.getOperand(1).setSubReg(SubReg2);
  1070. MI.getOperand(2).setIsKill(Reg1IsKill);
  1071. MI.getOperand(1).setIsKill(Reg2IsKill);
  1072. // Swap the mask around.
  1073. MI.getOperand(4).setImm((ME + 1) & 31);
  1074. MI.getOperand(5).setImm((MB - 1) & 31);
  1075. return &MI;
  1076. }
  1077. bool PPCInstrInfo::findCommutedOpIndices(const MachineInstr &MI,
  1078. unsigned &SrcOpIdx1,
  1079. unsigned &SrcOpIdx2) const {
  1080. // For VSX A-Type FMA instructions, it is the first two operands that can be
  1081. // commuted, however, because the non-encoded tied input operand is listed
  1082. // first, the operands to swap are actually the second and third.
  1083. int AltOpc = PPC::getAltVSXFMAOpcode(MI.getOpcode());
  1084. if (AltOpc == -1)
  1085. return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
  1086. // The commutable operand indices are 2 and 3. Return them in SrcOpIdx1
  1087. // and SrcOpIdx2.
  1088. return fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2, 2, 3);
  1089. }
  1090. void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
  1091. MachineBasicBlock::iterator MI) const {
  1092. // This function is used for scheduling, and the nop wanted here is the type
  1093. // that terminates dispatch groups on the POWER cores.
  1094. unsigned Directive = Subtarget.getCPUDirective();
  1095. unsigned Opcode;
  1096. switch (Directive) {
  1097. default: Opcode = PPC::NOP; break;
  1098. case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
  1099. case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
  1100. case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */
  1101. // FIXME: Update when POWER9 scheduling model is ready.
  1102. case PPC::DIR_PWR9: Opcode = PPC::NOP_GT_PWR7; break;
  1103. }
  1104. DebugLoc DL;
  1105. BuildMI(MBB, MI, DL, get(Opcode));
  1106. }
  1107. /// Return the noop instruction to use for a noop.
  1108. MCInst PPCInstrInfo::getNop() const {
  1109. MCInst Nop;
  1110. Nop.setOpcode(PPC::NOP);
  1111. return Nop;
  1112. }
  1113. // Branch analysis.
  1114. // Note: If the condition register is set to CTR or CTR8 then this is a
  1115. // BDNZ (imm == 1) or BDZ (imm == 0) branch.
  1116. bool PPCInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
  1117. MachineBasicBlock *&TBB,
  1118. MachineBasicBlock *&FBB,
  1119. SmallVectorImpl<MachineOperand> &Cond,
  1120. bool AllowModify) const {
  1121. bool isPPC64 = Subtarget.isPPC64();
  1122. // If the block has no terminators, it just falls into the block after it.
  1123. MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
  1124. if (I == MBB.end())
  1125. return false;
  1126. if (!isUnpredicatedTerminator(*I))
  1127. return false;
  1128. if (AllowModify) {
  1129. // If the BB ends with an unconditional branch to the fallthrough BB,
  1130. // we eliminate the branch instruction.
  1131. if (I->getOpcode() == PPC::B &&
  1132. MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
  1133. I->eraseFromParent();
  1134. // We update iterator after deleting the last branch.
  1135. I = MBB.getLastNonDebugInstr();
  1136. if (I == MBB.end() || !isUnpredicatedTerminator(*I))
  1137. return false;
  1138. }
  1139. }
  1140. // Get the last instruction in the block.
  1141. MachineInstr &LastInst = *I;
  1142. // If there is only one terminator instruction, process it.
  1143. if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
  1144. if (LastInst.getOpcode() == PPC::B) {
  1145. if (!LastInst.getOperand(0).isMBB())
  1146. return true;
  1147. TBB = LastInst.getOperand(0).getMBB();
  1148. return false;
  1149. } else if (LastInst.getOpcode() == PPC::BCC) {
  1150. if (!LastInst.getOperand(2).isMBB())
  1151. return true;
  1152. // Block ends with fall-through condbranch.
  1153. TBB = LastInst.getOperand(2).getMBB();
  1154. Cond.push_back(LastInst.getOperand(0));
  1155. Cond.push_back(LastInst.getOperand(1));
  1156. return false;
  1157. } else if (LastInst.getOpcode() == PPC::BC) {
  1158. if (!LastInst.getOperand(1).isMBB())
  1159. return true;
  1160. // Block ends with fall-through condbranch.
  1161. TBB = LastInst.getOperand(1).getMBB();
  1162. Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
  1163. Cond.push_back(LastInst.getOperand(0));
  1164. return false;
  1165. } else if (LastInst.getOpcode() == PPC::BCn) {
  1166. if (!LastInst.getOperand(1).isMBB())
  1167. return true;
  1168. // Block ends with fall-through condbranch.
  1169. TBB = LastInst.getOperand(1).getMBB();
  1170. Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
  1171. Cond.push_back(LastInst.getOperand(0));
  1172. return false;
  1173. } else if (LastInst.getOpcode() == PPC::BDNZ8 ||
  1174. LastInst.getOpcode() == PPC::BDNZ) {
  1175. if (!LastInst.getOperand(0).isMBB())
  1176. return true;
  1177. if (DisableCTRLoopAnal)
  1178. return true;
  1179. TBB = LastInst.getOperand(0).getMBB();
  1180. Cond.push_back(MachineOperand::CreateImm(1));
  1181. Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
  1182. true));
  1183. return false;
  1184. } else if (LastInst.getOpcode() == PPC::BDZ8 ||
  1185. LastInst.getOpcode() == PPC::BDZ) {
  1186. if (!LastInst.getOperand(0).isMBB())
  1187. return true;
  1188. if (DisableCTRLoopAnal)
  1189. return true;
  1190. TBB = LastInst.getOperand(0).getMBB();
  1191. Cond.push_back(MachineOperand::CreateImm(0));
  1192. Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
  1193. true));
  1194. return false;
  1195. }
  1196. // Otherwise, don't know what this is.
  1197. return true;
  1198. }
  1199. // Get the instruction before it if it's a terminator.
  1200. MachineInstr &SecondLastInst = *I;
  1201. // If there are three terminators, we don't know what sort of block this is.
  1202. if (I != MBB.begin() && isUnpredicatedTerminator(*--I))
  1203. return true;
  1204. // If the block ends with PPC::B and PPC:BCC, handle it.
  1205. if (SecondLastInst.getOpcode() == PPC::BCC &&
  1206. LastInst.getOpcode() == PPC::B) {
  1207. if (!SecondLastInst.getOperand(2).isMBB() ||
  1208. !LastInst.getOperand(0).isMBB())
  1209. return true;
  1210. TBB = SecondLastInst.getOperand(2).getMBB();
  1211. Cond.push_back(SecondLastInst.getOperand(0));
  1212. Cond.push_back(SecondLastInst.getOperand(1));
  1213. FBB = LastInst.getOperand(0).getMBB();
  1214. return false;
  1215. } else if (SecondLastInst.getOpcode() == PPC::BC &&
  1216. LastInst.getOpcode() == PPC::B) {
  1217. if (!SecondLastInst.getOperand(1).isMBB() ||
  1218. !LastInst.getOperand(0).isMBB())
  1219. return true;
  1220. TBB = SecondLastInst.getOperand(1).getMBB();
  1221. Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
  1222. Cond.push_back(SecondLastInst.getOperand(0));
  1223. FBB = LastInst.getOperand(0).getMBB();
  1224. return false;
  1225. } else if (SecondLastInst.getOpcode() == PPC::BCn &&
  1226. LastInst.getOpcode() == PPC::B) {
  1227. if (!SecondLastInst.getOperand(1).isMBB() ||
  1228. !LastInst.getOperand(0).isMBB())
  1229. return true;
  1230. TBB = SecondLastInst.getOperand(1).getMBB();
  1231. Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
  1232. Cond.push_back(SecondLastInst.getOperand(0));
  1233. FBB = LastInst.getOperand(0).getMBB();
  1234. return false;
  1235. } else if ((SecondLastInst.getOpcode() == PPC::BDNZ8 ||
  1236. SecondLastInst.getOpcode() == PPC::BDNZ) &&
  1237. LastInst.getOpcode() == PPC::B) {
  1238. if (!SecondLastInst.getOperand(0).isMBB() ||
  1239. !LastInst.getOperand(0).isMBB())
  1240. return true;
  1241. if (DisableCTRLoopAnal)
  1242. return true;
  1243. TBB = SecondLastInst.getOperand(0).getMBB();
  1244. Cond.push_back(MachineOperand::CreateImm(1));
  1245. Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
  1246. true));
  1247. FBB = LastInst.getOperand(0).getMBB();
  1248. return false;
  1249. } else if ((SecondLastInst.getOpcode() == PPC::BDZ8 ||
  1250. SecondLastInst.getOpcode() == PPC::BDZ) &&
  1251. LastInst.getOpcode() == PPC::B) {
  1252. if (!SecondLastInst.getOperand(0).isMBB() ||
  1253. !LastInst.getOperand(0).isMBB())
  1254. return true;
  1255. if (DisableCTRLoopAnal)
  1256. return true;
  1257. TBB = SecondLastInst.getOperand(0).getMBB();
  1258. Cond.push_back(MachineOperand::CreateImm(0));
  1259. Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
  1260. true));
  1261. FBB = LastInst.getOperand(0).getMBB();
  1262. return false;
  1263. }
  1264. // If the block ends with two PPC:Bs, handle it. The second one is not
  1265. // executed, so remove it.
  1266. if (SecondLastInst.getOpcode() == PPC::B && LastInst.getOpcode() == PPC::B) {
  1267. if (!SecondLastInst.getOperand(0).isMBB())
  1268. return true;
  1269. TBB = SecondLastInst.getOperand(0).getMBB();
  1270. I = LastInst;
  1271. if (AllowModify)
  1272. I->eraseFromParent();
  1273. return false;
  1274. }
  1275. // Otherwise, can't handle this.
  1276. return true;
  1277. }
  1278. unsigned PPCInstrInfo::removeBranch(MachineBasicBlock &MBB,
  1279. int *BytesRemoved) const {
  1280. assert(!BytesRemoved && "code size not handled");
  1281. MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
  1282. if (I == MBB.end())
  1283. return 0;
  1284. if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
  1285. I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
  1286. I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
  1287. I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
  1288. return 0;
  1289. // Remove the branch.
  1290. I->eraseFromParent();
  1291. I = MBB.end();
  1292. if (I == MBB.begin()) return 1;
  1293. --I;
  1294. if (I->getOpcode() != PPC::BCC &&
  1295. I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
  1296. I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
  1297. I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
  1298. return 1;
  1299. // Remove the branch.
  1300. I->eraseFromParent();
  1301. return 2;
  1302. }
  1303. unsigned PPCInstrInfo::insertBranch(MachineBasicBlock &MBB,
  1304. MachineBasicBlock *TBB,
  1305. MachineBasicBlock *FBB,
  1306. ArrayRef<MachineOperand> Cond,
  1307. const DebugLoc &DL,
  1308. int *BytesAdded) const {
  1309. // Shouldn't be a fall through.
  1310. assert(TBB && "insertBranch must not be told to insert a fallthrough");
  1311. assert((Cond.size() == 2 || Cond.size() == 0) &&
  1312. "PPC branch conditions have two components!");
  1313. assert(!BytesAdded && "code size not handled");
  1314. bool isPPC64 = Subtarget.isPPC64();
  1315. // One-way branch.
  1316. if (!FBB) {
  1317. if (Cond.empty()) // Unconditional branch
  1318. BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
  1319. else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
  1320. BuildMI(&MBB, DL, get(Cond[0].getImm() ?
  1321. (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
  1322. (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
  1323. else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
  1324. BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB);
  1325. else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
  1326. BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB);
  1327. else // Conditional branch
  1328. BuildMI(&MBB, DL, get(PPC::BCC))
  1329. .addImm(Cond[0].getImm())
  1330. .add(Cond[1])
  1331. .addMBB(TBB);
  1332. return 1;
  1333. }
  1334. // Two-way Conditional Branch.
  1335. if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
  1336. BuildMI(&MBB, DL, get(Cond[0].getImm() ?
  1337. (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
  1338. (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
  1339. else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
  1340. BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB);
  1341. else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
  1342. BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB);
  1343. else
  1344. BuildMI(&MBB, DL, get(PPC::BCC))
  1345. .addImm(Cond[0].getImm())
  1346. .add(Cond[1])
  1347. .addMBB(TBB);
  1348. BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
  1349. return 2;
  1350. }
  1351. // Select analysis.
  1352. bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
  1353. ArrayRef<MachineOperand> Cond,
  1354. Register DstReg, Register TrueReg,
  1355. Register FalseReg, int &CondCycles,
  1356. int &TrueCycles, int &FalseCycles) const {
  1357. if (Cond.size() != 2)
  1358. return false;
  1359. // If this is really a bdnz-like condition, then it cannot be turned into a
  1360. // select.
  1361. if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
  1362. return false;
  1363. // If the conditional branch uses a physical register, then it cannot be
  1364. // turned into a select.
  1365. if (Register::isPhysicalRegister(Cond[1].getReg()))
  1366. return false;
  1367. // Check register classes.
  1368. const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
  1369. const TargetRegisterClass *RC =
  1370. RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
  1371. if (!RC)
  1372. return false;
  1373. // isel is for regular integer GPRs only.
  1374. if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
  1375. !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
  1376. !PPC::G8RCRegClass.hasSubClassEq(RC) &&
  1377. !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
  1378. return false;
  1379. // FIXME: These numbers are for the A2, how well they work for other cores is
  1380. // an open question. On the A2, the isel instruction has a 2-cycle latency
  1381. // but single-cycle throughput. These numbers are used in combination with
  1382. // the MispredictPenalty setting from the active SchedMachineModel.
  1383. CondCycles = 1;
  1384. TrueCycles = 1;
  1385. FalseCycles = 1;
  1386. return true;
  1387. }
  1388. void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
  1389. MachineBasicBlock::iterator MI,
  1390. const DebugLoc &dl, Register DestReg,
  1391. ArrayRef<MachineOperand> Cond, Register TrueReg,
  1392. Register FalseReg) const {
  1393. assert(Cond.size() == 2 &&
  1394. "PPC branch conditions have two components!");
  1395. // Get the register classes.
  1396. MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
  1397. const TargetRegisterClass *RC =
  1398. RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
  1399. assert(RC && "TrueReg and FalseReg must have overlapping register classes");
  1400. bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
  1401. PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
  1402. assert((Is64Bit ||
  1403. PPC::GPRCRegClass.hasSubClassEq(RC) ||
  1404. PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
  1405. "isel is for regular integer GPRs only");
  1406. unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
  1407. auto SelectPred = static_cast<PPC::Predicate>(Cond[0].getImm());
  1408. unsigned SubIdx = 0;
  1409. bool SwapOps = false;
  1410. switch (SelectPred) {
  1411. case PPC::PRED_EQ:
  1412. case PPC::PRED_EQ_MINUS:
  1413. case PPC::PRED_EQ_PLUS:
  1414. SubIdx = PPC::sub_eq; SwapOps = false; break;
  1415. case PPC::PRED_NE:
  1416. case PPC::PRED_NE_MINUS:
  1417. case PPC::PRED_NE_PLUS:
  1418. SubIdx = PPC::sub_eq; SwapOps = true; break;
  1419. case PPC::PRED_LT:
  1420. case PPC::PRED_LT_MINUS:
  1421. case PPC::PRED_LT_PLUS:
  1422. SubIdx = PPC::sub_lt; SwapOps = false; break;
  1423. case PPC::PRED_GE:
  1424. case PPC::PRED_GE_MINUS:
  1425. case PPC::PRED_GE_PLUS:
  1426. SubIdx = PPC::sub_lt; SwapOps = true; break;
  1427. case PPC::PRED_GT:
  1428. case PPC::PRED_GT_MINUS:
  1429. case PPC::PRED_GT_PLUS:
  1430. SubIdx = PPC::sub_gt; SwapOps = false; break;
  1431. case PPC::PRED_LE:
  1432. case PPC::PRED_LE_MINUS:
  1433. case PPC::PRED_LE_PLUS:
  1434. SubIdx = PPC::sub_gt; SwapOps = true; break;
  1435. case PPC::PRED_UN:
  1436. case PPC::PRED_UN_MINUS:
  1437. case PPC::PRED_UN_PLUS:
  1438. SubIdx = PPC::sub_un; SwapOps = false; break;
  1439. case PPC::PRED_NU:
  1440. case PPC::PRED_NU_MINUS:
  1441. case PPC::PRED_NU_PLUS:
  1442. SubIdx = PPC::sub_un; SwapOps = true; break;
  1443. case PPC::PRED_BIT_SET: SubIdx = 0; SwapOps = false; break;
  1444. case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
  1445. }
  1446. Register FirstReg = SwapOps ? FalseReg : TrueReg,
  1447. SecondReg = SwapOps ? TrueReg : FalseReg;
  1448. // The first input register of isel cannot be r0. If it is a member
  1449. // of a register class that can be r0, then copy it first (the
  1450. // register allocator should eliminate the copy).
  1451. if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
  1452. MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
  1453. const TargetRegisterClass *FirstRC =
  1454. MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
  1455. &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
  1456. Register OldFirstReg = FirstReg;
  1457. FirstReg = MRI.createVirtualRegister(FirstRC);
  1458. BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
  1459. .addReg(OldFirstReg);
  1460. }
  1461. BuildMI(MBB, MI, dl, get(OpCode), DestReg)
  1462. .addReg(FirstReg).addReg(SecondReg)
  1463. .addReg(Cond[1].getReg(), 0, SubIdx);
  1464. }
  1465. static unsigned getCRBitValue(unsigned CRBit) {
  1466. unsigned Ret = 4;
  1467. if (CRBit == PPC::CR0LT || CRBit == PPC::CR1LT ||
  1468. CRBit == PPC::CR2LT || CRBit == PPC::CR3LT ||
  1469. CRBit == PPC::CR4LT || CRBit == PPC::CR5LT ||
  1470. CRBit == PPC::CR6LT || CRBit == PPC::CR7LT)
  1471. Ret = 3;
  1472. if (CRBit == PPC::CR0GT || CRBit == PPC::CR1GT ||
  1473. CRBit == PPC::CR2GT || CRBit == PPC::CR3GT ||
  1474. CRBit == PPC::CR4GT || CRBit == PPC::CR5GT ||
  1475. CRBit == PPC::CR6GT || CRBit == PPC::CR7GT)
  1476. Ret = 2;
  1477. if (CRBit == PPC::CR0EQ || CRBit == PPC::CR1EQ ||
  1478. CRBit == PPC::CR2EQ || CRBit == PPC::CR3EQ ||
  1479. CRBit == PPC::CR4EQ || CRBit == PPC::CR5EQ ||
  1480. CRBit == PPC::CR6EQ || CRBit == PPC::CR7EQ)
  1481. Ret = 1;
  1482. if (CRBit == PPC::CR0UN || CRBit == PPC::CR1UN ||
  1483. CRBit == PPC::CR2UN || CRBit == PPC::CR3UN ||
  1484. CRBit == PPC::CR4UN || CRBit == PPC::CR5UN ||
  1485. CRBit == PPC::CR6UN || CRBit == PPC::CR7UN)
  1486. Ret = 0;
  1487. assert(Ret != 4 && "Invalid CR bit register");
  1488. return Ret;
  1489. }
  1490. void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
  1491. MachineBasicBlock::iterator I,
  1492. const DebugLoc &DL, MCRegister DestReg,
  1493. MCRegister SrcReg, bool KillSrc) const {
  1494. // We can end up with self copies and similar things as a result of VSX copy
  1495. // legalization. Promote them here.
  1496. const TargetRegisterInfo *TRI = &getRegisterInfo();
  1497. if (PPC::F8RCRegClass.contains(DestReg) &&
  1498. PPC::VSRCRegClass.contains(SrcReg)) {
  1499. MCRegister SuperReg =
  1500. TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
  1501. if (VSXSelfCopyCrash && SrcReg == SuperReg)
  1502. llvm_unreachable("nop VSX copy");
  1503. DestReg = SuperReg;
  1504. } else if (PPC::F8RCRegClass.contains(SrcReg) &&
  1505. PPC::VSRCRegClass.contains(DestReg)) {
  1506. MCRegister SuperReg =
  1507. TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
  1508. if (VSXSelfCopyCrash && DestReg == SuperReg)
  1509. llvm_unreachable("nop VSX copy");
  1510. SrcReg = SuperReg;
  1511. }
  1512. // Different class register copy
  1513. if (PPC::CRBITRCRegClass.contains(SrcReg) &&
  1514. PPC::GPRCRegClass.contains(DestReg)) {
  1515. MCRegister CRReg = getCRFromCRBit(SrcReg);
  1516. BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg).addReg(CRReg);
  1517. getKillRegState(KillSrc);
  1518. // Rotate the CR bit in the CR fields to be the least significant bit and
  1519. // then mask with 0x1 (MB = ME = 31).
  1520. BuildMI(MBB, I, DL, get(PPC::RLWINM), DestReg)
  1521. .addReg(DestReg, RegState::Kill)
  1522. .addImm(TRI->getEncodingValue(CRReg) * 4 + (4 - getCRBitValue(SrcReg)))
  1523. .addImm(31)
  1524. .addImm(31);
  1525. return;
  1526. } else if (PPC::CRRCRegClass.contains(SrcReg) &&
  1527. (PPC::G8RCRegClass.contains(DestReg) ||
  1528. PPC::GPRCRegClass.contains(DestReg))) {
  1529. bool Is64Bit = PPC::G8RCRegClass.contains(DestReg);
  1530. unsigned MvCode = Is64Bit ? PPC::MFOCRF8 : PPC::MFOCRF;
  1531. unsigned ShCode = Is64Bit ? PPC::RLWINM8 : PPC::RLWINM;
  1532. unsigned CRNum = TRI->getEncodingValue(SrcReg);
  1533. BuildMI(MBB, I, DL, get(MvCode), DestReg).addReg(SrcReg);
  1534. getKillRegState(KillSrc);
  1535. if (CRNum == 7)
  1536. return;
  1537. // Shift the CR bits to make the CR field in the lowest 4 bits of GRC.
  1538. BuildMI(MBB, I, DL, get(ShCode), DestReg)
  1539. .addReg(DestReg, RegState::Kill)
  1540. .addImm(CRNum * 4 + 4)
  1541. .addImm(28)
  1542. .addImm(31);
  1543. return;
  1544. } else if (PPC::G8RCRegClass.contains(SrcReg) &&
  1545. PPC::VSFRCRegClass.contains(DestReg)) {
  1546. assert(Subtarget.hasDirectMove() &&
  1547. "Subtarget doesn't support directmove, don't know how to copy.");
  1548. BuildMI(MBB, I, DL, get(PPC::MTVSRD), DestReg).addReg(SrcReg);
  1549. NumGPRtoVSRSpill++;
  1550. getKillRegState(KillSrc);
  1551. return;
  1552. } else if (PPC::VSFRCRegClass.contains(SrcReg) &&
  1553. PPC::G8RCRegClass.contains(DestReg)) {
  1554. assert(Subtarget.hasDirectMove() &&
  1555. "Subtarget doesn't support directmove, don't know how to copy.");
  1556. BuildMI(MBB, I, DL, get(PPC::MFVSRD), DestReg).addReg(SrcReg);
  1557. getKillRegState(KillSrc);
  1558. return;
  1559. } else if (PPC::SPERCRegClass.contains(SrcReg) &&
  1560. PPC::GPRCRegClass.contains(DestReg)) {
  1561. BuildMI(MBB, I, DL, get(PPC::EFSCFD), DestReg).addReg(SrcReg);
  1562. getKillRegState(KillSrc);
  1563. return;
  1564. } else if (PPC::GPRCRegClass.contains(SrcReg) &&
  1565. PPC::SPERCRegClass.contains(DestReg)) {
  1566. BuildMI(MBB, I, DL, get(PPC::EFDCFS), DestReg).addReg(SrcReg);
  1567. getKillRegState(KillSrc);
  1568. return;
  1569. }
  1570. unsigned Opc;
  1571. if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
  1572. Opc = PPC::OR;
  1573. else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
  1574. Opc = PPC::OR8;
  1575. else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
  1576. Opc = PPC::FMR;
  1577. else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
  1578. Opc = PPC::MCRF;
  1579. else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
  1580. Opc = PPC::VOR;
  1581. else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
  1582. // There are two different ways this can be done:
  1583. // 1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
  1584. // issue in VSU pipeline 0.
  1585. // 2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
  1586. // can go to either pipeline.
  1587. // We'll always use xxlor here, because in practically all cases where
  1588. // copies are generated, they are close enough to some use that the
  1589. // lower-latency form is preferable.
  1590. Opc = PPC::XXLOR;
  1591. else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg) ||
  1592. PPC::VSSRCRegClass.contains(DestReg, SrcReg))
  1593. Opc = (Subtarget.hasP9Vector()) ? PPC::XSCPSGNDP : PPC::XXLORf;
  1594. else if (Subtarget.pairedVectorMemops() &&
  1595. PPC::VSRpRCRegClass.contains(DestReg, SrcReg)) {
  1596. if (SrcReg > PPC::VSRp15)
  1597. SrcReg = PPC::V0 + (SrcReg - PPC::VSRp16) * 2;
  1598. else
  1599. SrcReg = PPC::VSL0 + (SrcReg - PPC::VSRp0) * 2;
  1600. if (DestReg > PPC::VSRp15)
  1601. DestReg = PPC::V0 + (DestReg - PPC::VSRp16) * 2;
  1602. else
  1603. DestReg = PPC::VSL0 + (DestReg - PPC::VSRp0) * 2;
  1604. BuildMI(MBB, I, DL, get(PPC::XXLOR), DestReg).
  1605. addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
  1606. BuildMI(MBB, I, DL, get(PPC::XXLOR), DestReg + 1).
  1607. addReg(SrcReg + 1).addReg(SrcReg + 1, getKillRegState(KillSrc));
  1608. return;
  1609. }
  1610. else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
  1611. Opc = PPC::CROR;
  1612. else if (PPC::SPERCRegClass.contains(DestReg, SrcReg))
  1613. Opc = PPC::EVOR;
  1614. else if ((PPC::ACCRCRegClass.contains(DestReg) ||
  1615. PPC::UACCRCRegClass.contains(DestReg)) &&
  1616. (PPC::ACCRCRegClass.contains(SrcReg) ||
  1617. PPC::UACCRCRegClass.contains(SrcReg))) {
  1618. // If primed, de-prime the source register, copy the individual registers
  1619. // and prime the destination if needed. The vector subregisters are
  1620. // vs[(u)acc * 4] - vs[(u)acc * 4 + 3]. If the copy is not a kill and the
  1621. // source is primed, we need to re-prime it after the copy as well.
  1622. PPCRegisterInfo::emitAccCopyInfo(MBB, DestReg, SrcReg);
  1623. bool DestPrimed = PPC::ACCRCRegClass.contains(DestReg);
  1624. bool SrcPrimed = PPC::ACCRCRegClass.contains(SrcReg);
  1625. MCRegister VSLSrcReg =
  1626. PPC::VSL0 + (SrcReg - (SrcPrimed ? PPC::ACC0 : PPC::UACC0)) * 4;
  1627. MCRegister VSLDestReg =
  1628. PPC::VSL0 + (DestReg - (DestPrimed ? PPC::ACC0 : PPC::UACC0)) * 4;
  1629. if (SrcPrimed)
  1630. BuildMI(MBB, I, DL, get(PPC::XXMFACC), SrcReg).addReg(SrcReg);
  1631. for (unsigned Idx = 0; Idx < 4; Idx++)
  1632. BuildMI(MBB, I, DL, get(PPC::XXLOR), VSLDestReg + Idx)
  1633. .addReg(VSLSrcReg + Idx)
  1634. .addReg(VSLSrcReg + Idx, getKillRegState(KillSrc));
  1635. if (DestPrimed)
  1636. BuildMI(MBB, I, DL, get(PPC::XXMTACC), DestReg).addReg(DestReg);
  1637. if (SrcPrimed && !KillSrc)
  1638. BuildMI(MBB, I, DL, get(PPC::XXMTACC), SrcReg).addReg(SrcReg);
  1639. return;
  1640. } else if (PPC::G8pRCRegClass.contains(DestReg) &&
  1641. PPC::G8pRCRegClass.contains(SrcReg)) {
  1642. // TODO: Handle G8RC to G8pRC (and vice versa) copy.
  1643. unsigned DestRegIdx = DestReg - PPC::G8p0;
  1644. MCRegister DestRegSub0 = PPC::X0 + 2 * DestRegIdx;
  1645. MCRegister DestRegSub1 = PPC::X0 + 2 * DestRegIdx + 1;
  1646. unsigned SrcRegIdx = SrcReg - PPC::G8p0;
  1647. MCRegister SrcRegSub0 = PPC::X0 + 2 * SrcRegIdx;
  1648. MCRegister SrcRegSub1 = PPC::X0 + 2 * SrcRegIdx + 1;
  1649. BuildMI(MBB, I, DL, get(PPC::OR8), DestRegSub0)
  1650. .addReg(SrcRegSub0)
  1651. .addReg(SrcRegSub0, getKillRegState(KillSrc));
  1652. BuildMI(MBB, I, DL, get(PPC::OR8), DestRegSub1)
  1653. .addReg(SrcRegSub1)
  1654. .addReg(SrcRegSub1, getKillRegState(KillSrc));
  1655. return;
  1656. } else
  1657. llvm_unreachable("Impossible reg-to-reg copy");
  1658. const MCInstrDesc &MCID = get(Opc);
  1659. if (MCID.getNumOperands() == 3)
  1660. BuildMI(MBB, I, DL, MCID, DestReg)
  1661. .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
  1662. else
  1663. BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
  1664. }
  1665. unsigned PPCInstrInfo::getSpillIndex(const TargetRegisterClass *RC) const {
  1666. int OpcodeIndex = 0;
  1667. if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
  1668. PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
  1669. OpcodeIndex = SOK_Int4Spill;
  1670. } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
  1671. PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
  1672. OpcodeIndex = SOK_Int8Spill;
  1673. } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
  1674. OpcodeIndex = SOK_Float8Spill;
  1675. } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
  1676. OpcodeIndex = SOK_Float4Spill;
  1677. } else if (PPC::SPERCRegClass.hasSubClassEq(RC)) {
  1678. OpcodeIndex = SOK_SPESpill;
  1679. } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
  1680. OpcodeIndex = SOK_CRSpill;
  1681. } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
  1682. OpcodeIndex = SOK_CRBitSpill;
  1683. } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
  1684. OpcodeIndex = SOK_VRVectorSpill;
  1685. } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
  1686. OpcodeIndex = SOK_VSXVectorSpill;
  1687. } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
  1688. OpcodeIndex = SOK_VectorFloat8Spill;
  1689. } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
  1690. OpcodeIndex = SOK_VectorFloat4Spill;
  1691. } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) {
  1692. OpcodeIndex = SOK_SpillToVSR;
  1693. } else if (PPC::ACCRCRegClass.hasSubClassEq(RC)) {
  1694. assert(Subtarget.pairedVectorMemops() &&
  1695. "Register unexpected when paired memops are disabled.");
  1696. OpcodeIndex = SOK_AccumulatorSpill;
  1697. } else if (PPC::UACCRCRegClass.hasSubClassEq(RC)) {
  1698. assert(Subtarget.pairedVectorMemops() &&
  1699. "Register unexpected when paired memops are disabled.");
  1700. OpcodeIndex = SOK_UAccumulatorSpill;
  1701. } else if (PPC::VSRpRCRegClass.hasSubClassEq(RC)) {
  1702. assert(Subtarget.pairedVectorMemops() &&
  1703. "Register unexpected when paired memops are disabled.");
  1704. OpcodeIndex = SOK_PairedVecSpill;
  1705. } else if (PPC::G8pRCRegClass.hasSubClassEq(RC)) {
  1706. OpcodeIndex = SOK_PairedG8Spill;
  1707. } else {
  1708. llvm_unreachable("Unknown regclass!");
  1709. }
  1710. return OpcodeIndex;
  1711. }
  1712. unsigned
  1713. PPCInstrInfo::getStoreOpcodeForSpill(const TargetRegisterClass *RC) const {
  1714. const unsigned *OpcodesForSpill = getStoreOpcodesForSpillArray();
  1715. return OpcodesForSpill[getSpillIndex(RC)];
  1716. }
  1717. unsigned
  1718. PPCInstrInfo::getLoadOpcodeForSpill(const TargetRegisterClass *RC) const {
  1719. const unsigned *OpcodesForSpill = getLoadOpcodesForSpillArray();
  1720. return OpcodesForSpill[getSpillIndex(RC)];
  1721. }
  1722. void PPCInstrInfo::StoreRegToStackSlot(
  1723. MachineFunction &MF, unsigned SrcReg, bool isKill, int FrameIdx,
  1724. const TargetRegisterClass *RC,
  1725. SmallVectorImpl<MachineInstr *> &NewMIs) const {
  1726. unsigned Opcode = getStoreOpcodeForSpill(RC);
  1727. DebugLoc DL;
  1728. PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  1729. FuncInfo->setHasSpills();
  1730. NewMIs.push_back(addFrameReference(
  1731. BuildMI(MF, DL, get(Opcode)).addReg(SrcReg, getKillRegState(isKill)),
  1732. FrameIdx));
  1733. if (PPC::CRRCRegClass.hasSubClassEq(RC) ||
  1734. PPC::CRBITRCRegClass.hasSubClassEq(RC))
  1735. FuncInfo->setSpillsCR();
  1736. if (isXFormMemOp(Opcode))
  1737. FuncInfo->setHasNonRISpills();
  1738. }
  1739. void PPCInstrInfo::storeRegToStackSlotNoUpd(
  1740. MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned SrcReg,
  1741. bool isKill, int FrameIdx, const TargetRegisterClass *RC,
  1742. const TargetRegisterInfo *TRI) const {
  1743. MachineFunction &MF = *MBB.getParent();
  1744. SmallVector<MachineInstr *, 4> NewMIs;
  1745. StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs);
  1746. for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
  1747. MBB.insert(MI, NewMIs[i]);
  1748. const MachineFrameInfo &MFI = MF.getFrameInfo();
  1749. MachineMemOperand *MMO = MF.getMachineMemOperand(
  1750. MachinePointerInfo::getFixedStack(MF, FrameIdx),
  1751. MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
  1752. MFI.getObjectAlign(FrameIdx));
  1753. NewMIs.back()->addMemOperand(MF, MMO);
  1754. }
  1755. void PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
  1756. MachineBasicBlock::iterator MI,
  1757. Register SrcReg, bool isKill,
  1758. int FrameIdx,
  1759. const TargetRegisterClass *RC,
  1760. const TargetRegisterInfo *TRI) const {
  1761. // We need to avoid a situation in which the value from a VRRC register is
  1762. // spilled using an Altivec instruction and reloaded into a VSRC register
  1763. // using a VSX instruction. The issue with this is that the VSX
  1764. // load/store instructions swap the doublewords in the vector and the Altivec
  1765. // ones don't. The register classes on the spill/reload may be different if
  1766. // the register is defined using an Altivec instruction and is then used by a
  1767. // VSX instruction.
  1768. RC = updatedRC(RC);
  1769. storeRegToStackSlotNoUpd(MBB, MI, SrcReg, isKill, FrameIdx, RC, TRI);
  1770. }
  1771. void PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, const DebugLoc &DL,
  1772. unsigned DestReg, int FrameIdx,
  1773. const TargetRegisterClass *RC,
  1774. SmallVectorImpl<MachineInstr *> &NewMIs)
  1775. const {
  1776. unsigned Opcode = getLoadOpcodeForSpill(RC);
  1777. NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Opcode), DestReg),
  1778. FrameIdx));
  1779. PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  1780. if (PPC::CRRCRegClass.hasSubClassEq(RC) ||
  1781. PPC::CRBITRCRegClass.hasSubClassEq(RC))
  1782. FuncInfo->setSpillsCR();
  1783. if (isXFormMemOp(Opcode))
  1784. FuncInfo->setHasNonRISpills();
  1785. }
  1786. void PPCInstrInfo::loadRegFromStackSlotNoUpd(
  1787. MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned DestReg,
  1788. int FrameIdx, const TargetRegisterClass *RC,
  1789. const TargetRegisterInfo *TRI) const {
  1790. MachineFunction &MF = *MBB.getParent();
  1791. SmallVector<MachineInstr*, 4> NewMIs;
  1792. DebugLoc DL;
  1793. if (MI != MBB.end()) DL = MI->getDebugLoc();
  1794. PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  1795. FuncInfo->setHasSpills();
  1796. LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs);
  1797. for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
  1798. MBB.insert(MI, NewMIs[i]);
  1799. const MachineFrameInfo &MFI = MF.getFrameInfo();
  1800. MachineMemOperand *MMO = MF.getMachineMemOperand(
  1801. MachinePointerInfo::getFixedStack(MF, FrameIdx),
  1802. MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
  1803. MFI.getObjectAlign(FrameIdx));
  1804. NewMIs.back()->addMemOperand(MF, MMO);
  1805. }
  1806. void PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
  1807. MachineBasicBlock::iterator MI,
  1808. Register DestReg, int FrameIdx,
  1809. const TargetRegisterClass *RC,
  1810. const TargetRegisterInfo *TRI) const {
  1811. // We need to avoid a situation in which the value from a VRRC register is
  1812. // spilled using an Altivec instruction and reloaded into a VSRC register
  1813. // using a VSX instruction. The issue with this is that the VSX
  1814. // load/store instructions swap the doublewords in the vector and the Altivec
  1815. // ones don't. The register classes on the spill/reload may be different if
  1816. // the register is defined using an Altivec instruction and is then used by a
  1817. // VSX instruction.
  1818. RC = updatedRC(RC);
  1819. loadRegFromStackSlotNoUpd(MBB, MI, DestReg, FrameIdx, RC, TRI);
  1820. }
  1821. bool PPCInstrInfo::
  1822. reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
  1823. assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
  1824. if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
  1825. Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
  1826. else
  1827. // Leave the CR# the same, but invert the condition.
  1828. Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
  1829. return false;
  1830. }
  1831. // For some instructions, it is legal to fold ZERO into the RA register field.
  1832. // This function performs that fold by replacing the operand with PPC::ZERO,
  1833. // it does not consider whether the load immediate zero is no longer in use.
  1834. bool PPCInstrInfo::onlyFoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
  1835. Register Reg) const {
  1836. // A zero immediate should always be loaded with a single li.
  1837. unsigned DefOpc = DefMI.getOpcode();
  1838. if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
  1839. return false;
  1840. if (!DefMI.getOperand(1).isImm())
  1841. return false;
  1842. if (DefMI.getOperand(1).getImm() != 0)
  1843. return false;
  1844. // Note that we cannot here invert the arguments of an isel in order to fold
  1845. // a ZERO into what is presented as the second argument. All we have here
  1846. // is the condition bit, and that might come from a CR-logical bit operation.
  1847. const MCInstrDesc &UseMCID = UseMI.getDesc();
  1848. // Only fold into real machine instructions.
  1849. if (UseMCID.isPseudo())
  1850. return false;
  1851. // We need to find which of the User's operands is to be folded, that will be
  1852. // the operand that matches the given register ID.
  1853. unsigned UseIdx;
  1854. for (UseIdx = 0; UseIdx < UseMI.getNumOperands(); ++UseIdx)
  1855. if (UseMI.getOperand(UseIdx).isReg() &&
  1856. UseMI.getOperand(UseIdx).getReg() == Reg)
  1857. break;
  1858. assert(UseIdx < UseMI.getNumOperands() && "Cannot find Reg in UseMI");
  1859. assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
  1860. const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
  1861. // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
  1862. // register (which might also be specified as a pointer class kind).
  1863. if (UseInfo->isLookupPtrRegClass()) {
  1864. if (UseInfo->RegClass /* Kind */ != 1)
  1865. return false;
  1866. } else {
  1867. if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
  1868. UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
  1869. return false;
  1870. }
  1871. // Make sure this is not tied to an output register (or otherwise
  1872. // constrained). This is true for ST?UX registers, for example, which
  1873. // are tied to their output registers.
  1874. if (UseInfo->Constraints != 0)
  1875. return false;
  1876. MCRegister ZeroReg;
  1877. if (UseInfo->isLookupPtrRegClass()) {
  1878. bool isPPC64 = Subtarget.isPPC64();
  1879. ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
  1880. } else {
  1881. ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
  1882. PPC::ZERO8 : PPC::ZERO;
  1883. }
  1884. UseMI.getOperand(UseIdx).setReg(ZeroReg);
  1885. return true;
  1886. }
  1887. // Folds zero into instructions which have a load immediate zero as an operand
  1888. // but also recognize zero as immediate zero. If the definition of the load
  1889. // has no more users it is deleted.
  1890. bool PPCInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
  1891. Register Reg, MachineRegisterInfo *MRI) const {
  1892. bool Changed = onlyFoldImmediate(UseMI, DefMI, Reg);
  1893. if (MRI->use_nodbg_empty(Reg))
  1894. DefMI.eraseFromParent();
  1895. return Changed;
  1896. }
  1897. static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
  1898. for (MachineInstr &MI : MBB)
  1899. if (MI.definesRegister(PPC::CTR) || MI.definesRegister(PPC::CTR8))
  1900. return true;
  1901. return false;
  1902. }
  1903. // We should make sure that, if we're going to predicate both sides of a
  1904. // condition (a diamond), that both sides don't define the counter register. We
  1905. // can predicate counter-decrement-based branches, but while that predicates
  1906. // the branching, it does not predicate the counter decrement. If we tried to
  1907. // merge the triangle into one predicated block, we'd decrement the counter
  1908. // twice.
  1909. bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
  1910. unsigned NumT, unsigned ExtraT,
  1911. MachineBasicBlock &FMBB,
  1912. unsigned NumF, unsigned ExtraF,
  1913. BranchProbability Probability) const {
  1914. return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
  1915. }
  1916. bool PPCInstrInfo::isPredicated(const MachineInstr &MI) const {
  1917. // The predicated branches are identified by their type, not really by the
  1918. // explicit presence of a predicate. Furthermore, some of them can be
  1919. // predicated more than once. Because if conversion won't try to predicate
  1920. // any instruction which already claims to be predicated (by returning true
  1921. // here), always return false. In doing so, we let isPredicable() be the
  1922. // final word on whether not the instruction can be (further) predicated.
  1923. return false;
  1924. }
  1925. bool PPCInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
  1926. const MachineBasicBlock *MBB,
  1927. const MachineFunction &MF) const {
  1928. // Set MFFS and MTFSF as scheduling boundary to avoid unexpected code motion
  1929. // across them, since some FP operations may change content of FPSCR.
  1930. // TODO: Model FPSCR in PPC instruction definitions and remove the workaround
  1931. if (MI.getOpcode() == PPC::MFFS || MI.getOpcode() == PPC::MTFSF)
  1932. return true;
  1933. return TargetInstrInfo::isSchedulingBoundary(MI, MBB, MF);
  1934. }
  1935. bool PPCInstrInfo::PredicateInstruction(MachineInstr &MI,
  1936. ArrayRef<MachineOperand> Pred) const {
  1937. unsigned OpC = MI.getOpcode();
  1938. if (OpC == PPC::BLR || OpC == PPC::BLR8) {
  1939. if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
  1940. bool isPPC64 = Subtarget.isPPC64();
  1941. MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR)
  1942. : (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
  1943. // Need add Def and Use for CTR implicit operand.
  1944. MachineInstrBuilder(*MI.getParent()->getParent(), MI)
  1945. .addReg(Pred[1].getReg(), RegState::Implicit)
  1946. .addReg(Pred[1].getReg(), RegState::ImplicitDefine);
  1947. } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
  1948. MI.setDesc(get(PPC::BCLR));
  1949. MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
  1950. } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
  1951. MI.setDesc(get(PPC::BCLRn));
  1952. MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
  1953. } else {
  1954. MI.setDesc(get(PPC::BCCLR));
  1955. MachineInstrBuilder(*MI.getParent()->getParent(), MI)
  1956. .addImm(Pred[0].getImm())
  1957. .add(Pred[1]);
  1958. }
  1959. return true;
  1960. } else if (OpC == PPC::B) {
  1961. if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
  1962. bool isPPC64 = Subtarget.isPPC64();
  1963. MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
  1964. : (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
  1965. // Need add Def and Use for CTR implicit operand.
  1966. MachineInstrBuilder(*MI.getParent()->getParent(), MI)
  1967. .addReg(Pred[1].getReg(), RegState::Implicit)
  1968. .addReg(Pred[1].getReg(), RegState::ImplicitDefine);
  1969. } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
  1970. MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
  1971. MI.RemoveOperand(0);
  1972. MI.setDesc(get(PPC::BC));
  1973. MachineInstrBuilder(*MI.getParent()->getParent(), MI)
  1974. .add(Pred[1])
  1975. .addMBB(MBB);
  1976. } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
  1977. MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
  1978. MI.RemoveOperand(0);
  1979. MI.setDesc(get(PPC::BCn));
  1980. MachineInstrBuilder(*MI.getParent()->getParent(), MI)
  1981. .add(Pred[1])
  1982. .addMBB(MBB);
  1983. } else {
  1984. MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
  1985. MI.RemoveOperand(0);
  1986. MI.setDesc(get(PPC::BCC));
  1987. MachineInstrBuilder(*MI.getParent()->getParent(), MI)
  1988. .addImm(Pred[0].getImm())
  1989. .add(Pred[1])
  1990. .addMBB(MBB);
  1991. }
  1992. return true;
  1993. } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 || OpC == PPC::BCTRL ||
  1994. OpC == PPC::BCTRL8 || OpC == PPC::BCTRL_RM ||
  1995. OpC == PPC::BCTRL8_RM) {
  1996. if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
  1997. llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
  1998. bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8 ||
  1999. OpC == PPC::BCTRL_RM || OpC == PPC::BCTRL8_RM;
  2000. bool isPPC64 = Subtarget.isPPC64();
  2001. if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
  2002. MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8)
  2003. : (setLR ? PPC::BCCTRL : PPC::BCCTR)));
  2004. MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
  2005. } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
  2006. MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n)
  2007. : (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
  2008. MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
  2009. } else {
  2010. MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8)
  2011. : (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
  2012. MachineInstrBuilder(*MI.getParent()->getParent(), MI)
  2013. .addImm(Pred[0].getImm())
  2014. .add(Pred[1]);
  2015. }
  2016. // Need add Def and Use for LR implicit operand.
  2017. if (setLR)
  2018. MachineInstrBuilder(*MI.getParent()->getParent(), MI)
  2019. .addReg(isPPC64 ? PPC::LR8 : PPC::LR, RegState::Implicit)
  2020. .addReg(isPPC64 ? PPC::LR8 : PPC::LR, RegState::ImplicitDefine);
  2021. if (OpC == PPC::BCTRL_RM || OpC == PPC::BCTRL8_RM)
  2022. MachineInstrBuilder(*MI.getParent()->getParent(), MI)
  2023. .addReg(PPC::RM, RegState::ImplicitDefine);
  2024. return true;
  2025. }
  2026. return false;
  2027. }
  2028. bool PPCInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
  2029. ArrayRef<MachineOperand> Pred2) const {
  2030. assert(Pred1.size() == 2 && "Invalid PPC first predicate");
  2031. assert(Pred2.size() == 2 && "Invalid PPC second predicate");
  2032. if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
  2033. return false;
  2034. if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
  2035. return false;
  2036. // P1 can only subsume P2 if they test the same condition register.
  2037. if (Pred1[1].getReg() != Pred2[1].getReg())
  2038. return false;
  2039. PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
  2040. PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
  2041. if (P1 == P2)
  2042. return true;
  2043. // Does P1 subsume P2, e.g. GE subsumes GT.
  2044. if (P1 == PPC::PRED_LE &&
  2045. (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
  2046. return true;
  2047. if (P1 == PPC::PRED_GE &&
  2048. (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
  2049. return true;
  2050. return false;
  2051. }
  2052. bool PPCInstrInfo::ClobbersPredicate(MachineInstr &MI,
  2053. std::vector<MachineOperand> &Pred,
  2054. bool SkipDead) const {
  2055. // Note: At the present time, the contents of Pred from this function is
  2056. // unused by IfConversion. This implementation follows ARM by pushing the
  2057. // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
  2058. // predicate, instructions defining CTR or CTR8 are also included as
  2059. // predicate-defining instructions.
  2060. const TargetRegisterClass *RCs[] =
  2061. { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
  2062. &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
  2063. bool Found = false;
  2064. for (const MachineOperand &MO : MI.operands()) {
  2065. for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
  2066. const TargetRegisterClass *RC = RCs[c];
  2067. if (MO.isReg()) {
  2068. if (MO.isDef() && RC->contains(MO.getReg())) {
  2069. Pred.push_back(MO);
  2070. Found = true;
  2071. }
  2072. } else if (MO.isRegMask()) {
  2073. for (MCPhysReg R : *RC)
  2074. if (MO.clobbersPhysReg(R)) {
  2075. Pred.push_back(MO);
  2076. Found = true;
  2077. }
  2078. }
  2079. }
  2080. }
  2081. return Found;
  2082. }
  2083. bool PPCInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
  2084. Register &SrcReg2, int64_t &Mask,
  2085. int64_t &Value) const {
  2086. unsigned Opc = MI.getOpcode();
  2087. switch (Opc) {
  2088. default: return false;
  2089. case PPC::CMPWI:
  2090. case PPC::CMPLWI:
  2091. case PPC::CMPDI:
  2092. case PPC::CMPLDI:
  2093. SrcReg = MI.getOperand(1).getReg();
  2094. SrcReg2 = 0;
  2095. Value = MI.getOperand(2).getImm();
  2096. Mask = 0xFFFF;
  2097. return true;
  2098. case PPC::CMPW:
  2099. case PPC::CMPLW:
  2100. case PPC::CMPD:
  2101. case PPC::CMPLD:
  2102. case PPC::FCMPUS:
  2103. case PPC::FCMPUD:
  2104. SrcReg = MI.getOperand(1).getReg();
  2105. SrcReg2 = MI.getOperand(2).getReg();
  2106. Value = 0;
  2107. Mask = 0;
  2108. return true;
  2109. }
  2110. }
  2111. bool PPCInstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
  2112. Register SrcReg2, int64_t Mask,
  2113. int64_t Value,
  2114. const MachineRegisterInfo *MRI) const {
  2115. if (DisableCmpOpt)
  2116. return false;
  2117. int OpC = CmpInstr.getOpcode();
  2118. Register CRReg = CmpInstr.getOperand(0).getReg();
  2119. // FP record forms set CR1 based on the exception status bits, not a
  2120. // comparison with zero.
  2121. if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
  2122. return false;
  2123. const TargetRegisterInfo *TRI = &getRegisterInfo();
  2124. // The record forms set the condition register based on a signed comparison
  2125. // with zero (so says the ISA manual). This is not as straightforward as it
  2126. // seems, however, because this is always a 64-bit comparison on PPC64, even
  2127. // for instructions that are 32-bit in nature (like slw for example).
  2128. // So, on PPC32, for unsigned comparisons, we can use the record forms only
  2129. // for equality checks (as those don't depend on the sign). On PPC64,
  2130. // we are restricted to equality for unsigned 64-bit comparisons and for
  2131. // signed 32-bit comparisons the applicability is more restricted.
  2132. bool isPPC64 = Subtarget.isPPC64();
  2133. bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW;
  2134. bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
  2135. bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
  2136. // Look through copies unless that gets us to a physical register.
  2137. Register ActualSrc = TRI->lookThruCopyLike(SrcReg, MRI);
  2138. if (ActualSrc.isVirtual())
  2139. SrcReg = ActualSrc;
  2140. // Get the unique definition of SrcReg.
  2141. MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
  2142. if (!MI) return false;
  2143. bool equalityOnly = false;
  2144. bool noSub = false;
  2145. if (isPPC64) {
  2146. if (is32BitSignedCompare) {
  2147. // We can perform this optimization only if MI is sign-extending.
  2148. if (isSignExtended(*MI))
  2149. noSub = true;
  2150. else
  2151. return false;
  2152. } else if (is32BitUnsignedCompare) {
  2153. // We can perform this optimization, equality only, if MI is
  2154. // zero-extending.
  2155. if (isZeroExtended(*MI)) {
  2156. noSub = true;
  2157. equalityOnly = true;
  2158. } else
  2159. return false;
  2160. } else
  2161. equalityOnly = is64BitUnsignedCompare;
  2162. } else
  2163. equalityOnly = is32BitUnsignedCompare;
  2164. if (equalityOnly) {
  2165. // We need to check the uses of the condition register in order to reject
  2166. // non-equality comparisons.
  2167. for (MachineRegisterInfo::use_instr_iterator
  2168. I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
  2169. I != IE; ++I) {
  2170. MachineInstr *UseMI = &*I;
  2171. if (UseMI->getOpcode() == PPC::BCC) {
  2172. PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
  2173. unsigned PredCond = PPC::getPredicateCondition(Pred);
  2174. // We ignore hint bits when checking for non-equality comparisons.
  2175. if (PredCond != PPC::PRED_EQ && PredCond != PPC::PRED_NE)
  2176. return false;
  2177. } else if (UseMI->getOpcode() == PPC::ISEL ||
  2178. UseMI->getOpcode() == PPC::ISEL8) {
  2179. unsigned SubIdx = UseMI->getOperand(3).getSubReg();
  2180. if (SubIdx != PPC::sub_eq)
  2181. return false;
  2182. } else
  2183. return false;
  2184. }
  2185. }
  2186. MachineBasicBlock::iterator I = CmpInstr;
  2187. // Scan forward to find the first use of the compare.
  2188. for (MachineBasicBlock::iterator EL = CmpInstr.getParent()->end(); I != EL;
  2189. ++I) {
  2190. bool FoundUse = false;
  2191. for (MachineRegisterInfo::use_instr_iterator
  2192. J = MRI->use_instr_begin(CRReg), JE = MRI->use_instr_end();
  2193. J != JE; ++J)
  2194. if (&*J == &*I) {
  2195. FoundUse = true;
  2196. break;
  2197. }
  2198. if (FoundUse)
  2199. break;
  2200. }
  2201. SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
  2202. SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
  2203. // There are two possible candidates which can be changed to set CR[01].
  2204. // One is MI, the other is a SUB instruction.
  2205. // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
  2206. MachineInstr *Sub = nullptr;
  2207. if (SrcReg2 != 0)
  2208. // MI is not a candidate for CMPrr.
  2209. MI = nullptr;
  2210. // FIXME: Conservatively refuse to convert an instruction which isn't in the
  2211. // same BB as the comparison. This is to allow the check below to avoid calls
  2212. // (and other explicit clobbers); instead we should really check for these
  2213. // more explicitly (in at least a few predecessors).
  2214. else if (MI->getParent() != CmpInstr.getParent())
  2215. return false;
  2216. else if (Value != 0) {
  2217. // The record-form instructions set CR bit based on signed comparison
  2218. // against 0. We try to convert a compare against 1 or -1 into a compare
  2219. // against 0 to exploit record-form instructions. For example, we change
  2220. // the condition "greater than -1" into "greater than or equal to 0"
  2221. // and "less than 1" into "less than or equal to 0".
  2222. // Since we optimize comparison based on a specific branch condition,
  2223. // we don't optimize if condition code is used by more than once.
  2224. if (equalityOnly || !MRI->hasOneUse(CRReg))
  2225. return false;
  2226. MachineInstr *UseMI = &*MRI->use_instr_begin(CRReg);
  2227. if (UseMI->getOpcode() != PPC::BCC)
  2228. return false;
  2229. PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
  2230. unsigned PredCond = PPC::getPredicateCondition(Pred);
  2231. unsigned PredHint = PPC::getPredicateHint(Pred);
  2232. int16_t Immed = (int16_t)Value;
  2233. // When modifying the condition in the predicate, we propagate hint bits
  2234. // from the original predicate to the new one.
  2235. if (Immed == -1 && PredCond == PPC::PRED_GT)
  2236. // We convert "greater than -1" into "greater than or equal to 0",
  2237. // since we are assuming signed comparison by !equalityOnly
  2238. Pred = PPC::getPredicate(PPC::PRED_GE, PredHint);
  2239. else if (Immed == -1 && PredCond == PPC::PRED_LE)
  2240. // We convert "less than or equal to -1" into "less than 0".
  2241. Pred = PPC::getPredicate(PPC::PRED_LT, PredHint);
  2242. else if (Immed == 1 && PredCond == PPC::PRED_LT)
  2243. // We convert "less than 1" into "less than or equal to 0".
  2244. Pred = PPC::getPredicate(PPC::PRED_LE, PredHint);
  2245. else if (Immed == 1 && PredCond == PPC::PRED_GE)
  2246. // We convert "greater than or equal to 1" into "greater than 0".
  2247. Pred = PPC::getPredicate(PPC::PRED_GT, PredHint);
  2248. else
  2249. return false;
  2250. PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)), Pred));
  2251. }
  2252. // Search for Sub.
  2253. --I;
  2254. // Get ready to iterate backward from CmpInstr.
  2255. MachineBasicBlock::iterator E = MI, B = CmpInstr.getParent()->begin();
  2256. for (; I != E && !noSub; --I) {
  2257. const MachineInstr &Instr = *I;
  2258. unsigned IOpC = Instr.getOpcode();
  2259. if (&*I != &CmpInstr && (Instr.modifiesRegister(PPC::CR0, TRI) ||
  2260. Instr.readsRegister(PPC::CR0, TRI)))
  2261. // This instruction modifies or uses the record condition register after
  2262. // the one we want to change. While we could do this transformation, it
  2263. // would likely not be profitable. This transformation removes one
  2264. // instruction, and so even forcing RA to generate one move probably
  2265. // makes it unprofitable.
  2266. return false;
  2267. // Check whether CmpInstr can be made redundant by the current instruction.
  2268. if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
  2269. OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
  2270. (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
  2271. ((Instr.getOperand(1).getReg() == SrcReg &&
  2272. Instr.getOperand(2).getReg() == SrcReg2) ||
  2273. (Instr.getOperand(1).getReg() == SrcReg2 &&
  2274. Instr.getOperand(2).getReg() == SrcReg))) {
  2275. Sub = &*I;
  2276. break;
  2277. }
  2278. if (I == B)
  2279. // The 'and' is below the comparison instruction.
  2280. return false;
  2281. }
  2282. // Return false if no candidates exist.
  2283. if (!MI && !Sub)
  2284. return false;
  2285. // The single candidate is called MI.
  2286. if (!MI) MI = Sub;
  2287. int NewOpC = -1;
  2288. int MIOpC = MI->getOpcode();
  2289. if (MIOpC == PPC::ANDI_rec || MIOpC == PPC::ANDI8_rec ||
  2290. MIOpC == PPC::ANDIS_rec || MIOpC == PPC::ANDIS8_rec)
  2291. NewOpC = MIOpC;
  2292. else {
  2293. NewOpC = PPC::getRecordFormOpcode(MIOpC);
  2294. if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
  2295. NewOpC = MIOpC;
  2296. }
  2297. // FIXME: On the non-embedded POWER architectures, only some of the record
  2298. // forms are fast, and we should use only the fast ones.
  2299. // The defining instruction has a record form (or is already a record
  2300. // form). It is possible, however, that we'll need to reverse the condition
  2301. // code of the users.
  2302. if (NewOpC == -1)
  2303. return false;
  2304. // This transformation should not be performed if `nsw` is missing and is not
  2305. // `equalityOnly` comparison. Since if there is overflow, sub_lt, sub_gt in
  2306. // CRReg do not reflect correct order. If `equalityOnly` is true, sub_eq in
  2307. // CRReg can reflect if compared values are equal, this optz is still valid.
  2308. if (!equalityOnly && (NewOpC == PPC::SUBF_rec || NewOpC == PPC::SUBF8_rec) &&
  2309. Sub && !Sub->getFlag(MachineInstr::NoSWrap))
  2310. return false;
  2311. // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
  2312. // needs to be updated to be based on SUB. Push the condition code
  2313. // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the
  2314. // condition code of these operands will be modified.
  2315. // Here, Value == 0 means we haven't converted comparison against 1 or -1 to
  2316. // comparison against 0, which may modify predicate.
  2317. bool ShouldSwap = false;
  2318. if (Sub && Value == 0) {
  2319. ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
  2320. Sub->getOperand(2).getReg() == SrcReg;
  2321. // The operands to subf are the opposite of sub, so only in the fixed-point
  2322. // case, invert the order.
  2323. ShouldSwap = !ShouldSwap;
  2324. }
  2325. if (ShouldSwap)
  2326. for (MachineRegisterInfo::use_instr_iterator
  2327. I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
  2328. I != IE; ++I) {
  2329. MachineInstr *UseMI = &*I;
  2330. if (UseMI->getOpcode() == PPC::BCC) {
  2331. PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
  2332. unsigned PredCond = PPC::getPredicateCondition(Pred);
  2333. assert((!equalityOnly ||
  2334. PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE) &&
  2335. "Invalid predicate for equality-only optimization");
  2336. (void)PredCond; // To suppress warning in release build.
  2337. PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
  2338. PPC::getSwappedPredicate(Pred)));
  2339. } else if (UseMI->getOpcode() == PPC::ISEL ||
  2340. UseMI->getOpcode() == PPC::ISEL8) {
  2341. unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
  2342. assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
  2343. "Invalid CR bit for equality-only optimization");
  2344. if (NewSubReg == PPC::sub_lt)
  2345. NewSubReg = PPC::sub_gt;
  2346. else if (NewSubReg == PPC::sub_gt)
  2347. NewSubReg = PPC::sub_lt;
  2348. SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
  2349. NewSubReg));
  2350. } else // We need to abort on a user we don't understand.
  2351. return false;
  2352. }
  2353. assert(!(Value != 0 && ShouldSwap) &&
  2354. "Non-zero immediate support and ShouldSwap"
  2355. "may conflict in updating predicate");
  2356. // Create a new virtual register to hold the value of the CR set by the
  2357. // record-form instruction. If the instruction was not previously in
  2358. // record form, then set the kill flag on the CR.
  2359. CmpInstr.eraseFromParent();
  2360. MachineBasicBlock::iterator MII = MI;
  2361. BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
  2362. get(TargetOpcode::COPY), CRReg)
  2363. .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
  2364. // Even if CR0 register were dead before, it is alive now since the
  2365. // instruction we just built uses it.
  2366. MI->clearRegisterDeads(PPC::CR0);
  2367. if (MIOpC != NewOpC) {
  2368. // We need to be careful here: we're replacing one instruction with
  2369. // another, and we need to make sure that we get all of the right
  2370. // implicit uses and defs. On the other hand, the caller may be holding
  2371. // an iterator to this instruction, and so we can't delete it (this is
  2372. // specifically the case if this is the instruction directly after the
  2373. // compare).
  2374. // Rotates are expensive instructions. If we're emitting a record-form
  2375. // rotate that can just be an andi/andis, we should just emit that.
  2376. if (MIOpC == PPC::RLWINM || MIOpC == PPC::RLWINM8) {
  2377. Register GPRRes = MI->getOperand(0).getReg();
  2378. int64_t SH = MI->getOperand(2).getImm();
  2379. int64_t MB = MI->getOperand(3).getImm();
  2380. int64_t ME = MI->getOperand(4).getImm();
  2381. // We can only do this if both the start and end of the mask are in the
  2382. // same halfword.
  2383. bool MBInLoHWord = MB >= 16;
  2384. bool MEInLoHWord = ME >= 16;
  2385. uint64_t Mask = ~0LLU;
  2386. if (MB <= ME && MBInLoHWord == MEInLoHWord && SH == 0) {
  2387. Mask = ((1LLU << (32 - MB)) - 1) & ~((1LLU << (31 - ME)) - 1);
  2388. // The mask value needs to shift right 16 if we're emitting andis.
  2389. Mask >>= MBInLoHWord ? 0 : 16;
  2390. NewOpC = MIOpC == PPC::RLWINM
  2391. ? (MBInLoHWord ? PPC::ANDI_rec : PPC::ANDIS_rec)
  2392. : (MBInLoHWord ? PPC::ANDI8_rec : PPC::ANDIS8_rec);
  2393. } else if (MRI->use_empty(GPRRes) && (ME == 31) &&
  2394. (ME - MB + 1 == SH) && (MB >= 16)) {
  2395. // If we are rotating by the exact number of bits as are in the mask
  2396. // and the mask is in the least significant bits of the register,
  2397. // that's just an andis. (as long as the GPR result has no uses).
  2398. Mask = ((1LLU << 32) - 1) & ~((1LLU << (32 - SH)) - 1);
  2399. Mask >>= 16;
  2400. NewOpC = MIOpC == PPC::RLWINM ? PPC::ANDIS_rec : PPC::ANDIS8_rec;
  2401. }
  2402. // If we've set the mask, we can transform.
  2403. if (Mask != ~0LLU) {
  2404. MI->RemoveOperand(4);
  2405. MI->RemoveOperand(3);
  2406. MI->getOperand(2).setImm(Mask);
  2407. NumRcRotatesConvertedToRcAnd++;
  2408. }
  2409. } else if (MIOpC == PPC::RLDICL && MI->getOperand(2).getImm() == 0) {
  2410. int64_t MB = MI->getOperand(3).getImm();
  2411. if (MB >= 48) {
  2412. uint64_t Mask = (1LLU << (63 - MB + 1)) - 1;
  2413. NewOpC = PPC::ANDI8_rec;
  2414. MI->RemoveOperand(3);
  2415. MI->getOperand(2).setImm(Mask);
  2416. NumRcRotatesConvertedToRcAnd++;
  2417. }
  2418. }
  2419. const MCInstrDesc &NewDesc = get(NewOpC);
  2420. MI->setDesc(NewDesc);
  2421. if (NewDesc.ImplicitDefs)
  2422. for (const MCPhysReg *ImpDefs = NewDesc.getImplicitDefs();
  2423. *ImpDefs; ++ImpDefs)
  2424. if (!MI->definesRegister(*ImpDefs))
  2425. MI->addOperand(*MI->getParent()->getParent(),
  2426. MachineOperand::CreateReg(*ImpDefs, true, true));
  2427. if (NewDesc.ImplicitUses)
  2428. for (const MCPhysReg *ImpUses = NewDesc.getImplicitUses();
  2429. *ImpUses; ++ImpUses)
  2430. if (!MI->readsRegister(*ImpUses))
  2431. MI->addOperand(*MI->getParent()->getParent(),
  2432. MachineOperand::CreateReg(*ImpUses, false, true));
  2433. }
  2434. assert(MI->definesRegister(PPC::CR0) &&
  2435. "Record-form instruction does not define cr0?");
  2436. // Modify the condition code of operands in OperandsToUpdate.
  2437. // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
  2438. // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
  2439. for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
  2440. PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
  2441. for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
  2442. SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
  2443. return true;
  2444. }
  2445. bool PPCInstrInfo::getMemOperandsWithOffsetWidth(
  2446. const MachineInstr &LdSt, SmallVectorImpl<const MachineOperand *> &BaseOps,
  2447. int64_t &Offset, bool &OffsetIsScalable, unsigned &Width,
  2448. const TargetRegisterInfo *TRI) const {
  2449. const MachineOperand *BaseOp;
  2450. OffsetIsScalable = false;
  2451. if (!getMemOperandWithOffsetWidth(LdSt, BaseOp, Offset, Width, TRI))
  2452. return false;
  2453. BaseOps.push_back(BaseOp);
  2454. return true;
  2455. }
  2456. static bool isLdStSafeToCluster(const MachineInstr &LdSt,
  2457. const TargetRegisterInfo *TRI) {
  2458. // If this is a volatile load/store, don't mess with it.
  2459. if (LdSt.hasOrderedMemoryRef() || LdSt.getNumExplicitOperands() != 3)
  2460. return false;
  2461. if (LdSt.getOperand(2).isFI())
  2462. return true;
  2463. assert(LdSt.getOperand(2).isReg() && "Expected a reg operand.");
  2464. // Can't cluster if the instruction modifies the base register
  2465. // or it is update form. e.g. ld r2,3(r2)
  2466. if (LdSt.modifiesRegister(LdSt.getOperand(2).getReg(), TRI))
  2467. return false;
  2468. return true;
  2469. }
  2470. // Only cluster instruction pair that have the same opcode, and they are
  2471. // clusterable according to PowerPC specification.
  2472. static bool isClusterableLdStOpcPair(unsigned FirstOpc, unsigned SecondOpc,
  2473. const PPCSubtarget &Subtarget) {
  2474. switch (FirstOpc) {
  2475. default:
  2476. return false;
  2477. case PPC::STD:
  2478. case PPC::STFD:
  2479. case PPC::STXSD:
  2480. case PPC::DFSTOREf64:
  2481. return FirstOpc == SecondOpc;
  2482. // PowerPC backend has opcode STW/STW8 for instruction "stw" to deal with
  2483. // 32bit and 64bit instruction selection. They are clusterable pair though
  2484. // they are different opcode.
  2485. case PPC::STW:
  2486. case PPC::STW8:
  2487. return SecondOpc == PPC::STW || SecondOpc == PPC::STW8;
  2488. }
  2489. }
  2490. bool PPCInstrInfo::shouldClusterMemOps(
  2491. ArrayRef<const MachineOperand *> BaseOps1,
  2492. ArrayRef<const MachineOperand *> BaseOps2, unsigned NumLoads,
  2493. unsigned NumBytes) const {
  2494. assert(BaseOps1.size() == 1 && BaseOps2.size() == 1);
  2495. const MachineOperand &BaseOp1 = *BaseOps1.front();
  2496. const MachineOperand &BaseOp2 = *BaseOps2.front();
  2497. assert((BaseOp1.isReg() || BaseOp1.isFI()) &&
  2498. "Only base registers and frame indices are supported.");
  2499. // The NumLoads means the number of loads that has been clustered.
  2500. // Don't cluster memory op if there are already two ops clustered at least.
  2501. if (NumLoads > 2)
  2502. return false;
  2503. // Cluster the load/store only when they have the same base
  2504. // register or FI.
  2505. if ((BaseOp1.isReg() != BaseOp2.isReg()) ||
  2506. (BaseOp1.isReg() && BaseOp1.getReg() != BaseOp2.getReg()) ||
  2507. (BaseOp1.isFI() && BaseOp1.getIndex() != BaseOp2.getIndex()))
  2508. return false;
  2509. // Check if the load/store are clusterable according to the PowerPC
  2510. // specification.
  2511. const MachineInstr &FirstLdSt = *BaseOp1.getParent();
  2512. const MachineInstr &SecondLdSt = *BaseOp2.getParent();
  2513. unsigned FirstOpc = FirstLdSt.getOpcode();
  2514. unsigned SecondOpc = SecondLdSt.getOpcode();
  2515. const TargetRegisterInfo *TRI = &getRegisterInfo();
  2516. // Cluster the load/store only when they have the same opcode, and they are
  2517. // clusterable opcode according to PowerPC specification.
  2518. if (!isClusterableLdStOpcPair(FirstOpc, SecondOpc, Subtarget))
  2519. return false;
  2520. // Can't cluster load/store that have ordered or volatile memory reference.
  2521. if (!isLdStSafeToCluster(FirstLdSt, TRI) ||
  2522. !isLdStSafeToCluster(SecondLdSt, TRI))
  2523. return false;
  2524. int64_t Offset1 = 0, Offset2 = 0;
  2525. unsigned Width1 = 0, Width2 = 0;
  2526. const MachineOperand *Base1 = nullptr, *Base2 = nullptr;
  2527. if (!getMemOperandWithOffsetWidth(FirstLdSt, Base1, Offset1, Width1, TRI) ||
  2528. !getMemOperandWithOffsetWidth(SecondLdSt, Base2, Offset2, Width2, TRI) ||
  2529. Width1 != Width2)
  2530. return false;
  2531. assert(Base1 == &BaseOp1 && Base2 == &BaseOp2 &&
  2532. "getMemOperandWithOffsetWidth return incorrect base op");
  2533. // The caller should already have ordered FirstMemOp/SecondMemOp by offset.
  2534. assert(Offset1 <= Offset2 && "Caller should have ordered offsets.");
  2535. return Offset1 + Width1 == Offset2;
  2536. }
  2537. /// GetInstSize - Return the number of bytes of code the specified
  2538. /// instruction may be. This returns the maximum number of bytes.
  2539. ///
  2540. unsigned PPCInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
  2541. unsigned Opcode = MI.getOpcode();
  2542. if (Opcode == PPC::INLINEASM || Opcode == PPC::INLINEASM_BR) {
  2543. const MachineFunction *MF = MI.getParent()->getParent();
  2544. const char *AsmStr = MI.getOperand(0).getSymbolName();
  2545. return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
  2546. } else if (Opcode == TargetOpcode::STACKMAP) {
  2547. StackMapOpers Opers(&MI);
  2548. return Opers.getNumPatchBytes();
  2549. } else if (Opcode == TargetOpcode::PATCHPOINT) {
  2550. PatchPointOpers Opers(&MI);
  2551. return Opers.getNumPatchBytes();
  2552. } else {
  2553. return get(Opcode).getSize();
  2554. }
  2555. }
  2556. std::pair<unsigned, unsigned>
  2557. PPCInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
  2558. const unsigned Mask = PPCII::MO_ACCESS_MASK;
  2559. return std::make_pair(TF & Mask, TF & ~Mask);
  2560. }
  2561. ArrayRef<std::pair<unsigned, const char *>>
  2562. PPCInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
  2563. using namespace PPCII;
  2564. static const std::pair<unsigned, const char *> TargetFlags[] = {
  2565. {MO_LO, "ppc-lo"},
  2566. {MO_HA, "ppc-ha"},
  2567. {MO_TPREL_LO, "ppc-tprel-lo"},
  2568. {MO_TPREL_HA, "ppc-tprel-ha"},
  2569. {MO_DTPREL_LO, "ppc-dtprel-lo"},
  2570. {MO_TLSLD_LO, "ppc-tlsld-lo"},
  2571. {MO_TOC_LO, "ppc-toc-lo"},
  2572. {MO_TLS, "ppc-tls"}};
  2573. return makeArrayRef(TargetFlags);
  2574. }
  2575. ArrayRef<std::pair<unsigned, const char *>>
  2576. PPCInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
  2577. using namespace PPCII;
  2578. static const std::pair<unsigned, const char *> TargetFlags[] = {
  2579. {MO_PLT, "ppc-plt"},
  2580. {MO_PIC_FLAG, "ppc-pic"},
  2581. {MO_PCREL_FLAG, "ppc-pcrel"},
  2582. {MO_GOT_FLAG, "ppc-got"},
  2583. {MO_PCREL_OPT_FLAG, "ppc-opt-pcrel"},
  2584. {MO_TLSGD_FLAG, "ppc-tlsgd"},
  2585. {MO_TLSLD_FLAG, "ppc-tlsld"},
  2586. {MO_TPREL_FLAG, "ppc-tprel"},
  2587. {MO_TLSGDM_FLAG, "ppc-tlsgdm"},
  2588. {MO_GOT_TLSGD_PCREL_FLAG, "ppc-got-tlsgd-pcrel"},
  2589. {MO_GOT_TLSLD_PCREL_FLAG, "ppc-got-tlsld-pcrel"},
  2590. {MO_GOT_TPREL_PCREL_FLAG, "ppc-got-tprel-pcrel"}};
  2591. return makeArrayRef(TargetFlags);
  2592. }
  2593. // Expand VSX Memory Pseudo instruction to either a VSX or a FP instruction.
  2594. // The VSX versions have the advantage of a full 64-register target whereas
  2595. // the FP ones have the advantage of lower latency and higher throughput. So
  2596. // what we are after is using the faster instructions in low register pressure
  2597. // situations and using the larger register file in high register pressure
  2598. // situations.
  2599. bool PPCInstrInfo::expandVSXMemPseudo(MachineInstr &MI) const {
  2600. unsigned UpperOpcode, LowerOpcode;
  2601. switch (MI.getOpcode()) {
  2602. case PPC::DFLOADf32:
  2603. UpperOpcode = PPC::LXSSP;
  2604. LowerOpcode = PPC::LFS;
  2605. break;
  2606. case PPC::DFLOADf64:
  2607. UpperOpcode = PPC::LXSD;
  2608. LowerOpcode = PPC::LFD;
  2609. break;
  2610. case PPC::DFSTOREf32:
  2611. UpperOpcode = PPC::STXSSP;
  2612. LowerOpcode = PPC::STFS;
  2613. break;
  2614. case PPC::DFSTOREf64:
  2615. UpperOpcode = PPC::STXSD;
  2616. LowerOpcode = PPC::STFD;
  2617. break;
  2618. case PPC::XFLOADf32:
  2619. UpperOpcode = PPC::LXSSPX;
  2620. LowerOpcode = PPC::LFSX;
  2621. break;
  2622. case PPC::XFLOADf64:
  2623. UpperOpcode = PPC::LXSDX;
  2624. LowerOpcode = PPC::LFDX;
  2625. break;
  2626. case PPC::XFSTOREf32:
  2627. UpperOpcode = PPC::STXSSPX;
  2628. LowerOpcode = PPC::STFSX;
  2629. break;
  2630. case PPC::XFSTOREf64:
  2631. UpperOpcode = PPC::STXSDX;
  2632. LowerOpcode = PPC::STFDX;
  2633. break;
  2634. case PPC::LIWAX:
  2635. UpperOpcode = PPC::LXSIWAX;
  2636. LowerOpcode = PPC::LFIWAX;
  2637. break;
  2638. case PPC::LIWZX:
  2639. UpperOpcode = PPC::LXSIWZX;
  2640. LowerOpcode = PPC::LFIWZX;
  2641. break;
  2642. case PPC::STIWX:
  2643. UpperOpcode = PPC::STXSIWX;
  2644. LowerOpcode = PPC::STFIWX;
  2645. break;
  2646. default:
  2647. llvm_unreachable("Unknown Operation!");
  2648. }
  2649. Register TargetReg = MI.getOperand(0).getReg();
  2650. unsigned Opcode;
  2651. if ((TargetReg >= PPC::F0 && TargetReg <= PPC::F31) ||
  2652. (TargetReg >= PPC::VSL0 && TargetReg <= PPC::VSL31))
  2653. Opcode = LowerOpcode;
  2654. else
  2655. Opcode = UpperOpcode;
  2656. MI.setDesc(get(Opcode));
  2657. return true;
  2658. }
  2659. static bool isAnImmediateOperand(const MachineOperand &MO) {
  2660. return MO.isCPI() || MO.isGlobal() || MO.isImm();
  2661. }
  2662. bool PPCInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
  2663. auto &MBB = *MI.getParent();
  2664. auto DL = MI.getDebugLoc();
  2665. switch (MI.getOpcode()) {
  2666. case PPC::BUILD_UACC: {
  2667. MCRegister ACC = MI.getOperand(0).getReg();
  2668. MCRegister UACC = MI.getOperand(1).getReg();
  2669. if (ACC - PPC::ACC0 != UACC - PPC::UACC0) {
  2670. MCRegister SrcVSR = PPC::VSL0 + (UACC - PPC::UACC0) * 4;
  2671. MCRegister DstVSR = PPC::VSL0 + (ACC - PPC::ACC0) * 4;
  2672. // FIXME: This can easily be improved to look up to the top of the MBB
  2673. // to see if the inputs are XXLOR's. If they are and SrcReg is killed,
  2674. // we can just re-target any such XXLOR's to DstVSR + offset.
  2675. for (int VecNo = 0; VecNo < 4; VecNo++)
  2676. BuildMI(MBB, MI, DL, get(PPC::XXLOR), DstVSR + VecNo)
  2677. .addReg(SrcVSR + VecNo)
  2678. .addReg(SrcVSR + VecNo);
  2679. }
  2680. // BUILD_UACC is expanded to 4 copies of the underlying vsx registers.
  2681. // So after building the 4 copies, we can replace the BUILD_UACC instruction
  2682. // with a NOP.
  2683. LLVM_FALLTHROUGH;
  2684. }
  2685. case PPC::KILL_PAIR: {
  2686. MI.setDesc(get(PPC::UNENCODED_NOP));
  2687. MI.RemoveOperand(1);
  2688. MI.RemoveOperand(0);
  2689. return true;
  2690. }
  2691. case TargetOpcode::LOAD_STACK_GUARD: {
  2692. assert(Subtarget.isTargetLinux() &&
  2693. "Only Linux target is expected to contain LOAD_STACK_GUARD");
  2694. const int64_t Offset = Subtarget.isPPC64() ? -0x7010 : -0x7008;
  2695. const unsigned Reg = Subtarget.isPPC64() ? PPC::X13 : PPC::R2;
  2696. MI.setDesc(get(Subtarget.isPPC64() ? PPC::LD : PPC::LWZ));
  2697. MachineInstrBuilder(*MI.getParent()->getParent(), MI)
  2698. .addImm(Offset)
  2699. .addReg(Reg);
  2700. return true;
  2701. }
  2702. case PPC::DFLOADf32:
  2703. case PPC::DFLOADf64:
  2704. case PPC::DFSTOREf32:
  2705. case PPC::DFSTOREf64: {
  2706. assert(Subtarget.hasP9Vector() &&
  2707. "Invalid D-Form Pseudo-ops on Pre-P9 target.");
  2708. assert(MI.getOperand(2).isReg() &&
  2709. isAnImmediateOperand(MI.getOperand(1)) &&
  2710. "D-form op must have register and immediate operands");
  2711. return expandVSXMemPseudo(MI);
  2712. }
  2713. case PPC::XFLOADf32:
  2714. case PPC::XFSTOREf32:
  2715. case PPC::LIWAX:
  2716. case PPC::LIWZX:
  2717. case PPC::STIWX: {
  2718. assert(Subtarget.hasP8Vector() &&
  2719. "Invalid X-Form Pseudo-ops on Pre-P8 target.");
  2720. assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
  2721. "X-form op must have register and register operands");
  2722. return expandVSXMemPseudo(MI);
  2723. }
  2724. case PPC::XFLOADf64:
  2725. case PPC::XFSTOREf64: {
  2726. assert(Subtarget.hasVSX() &&
  2727. "Invalid X-Form Pseudo-ops on target that has no VSX.");
  2728. assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
  2729. "X-form op must have register and register operands");
  2730. return expandVSXMemPseudo(MI);
  2731. }
  2732. case PPC::SPILLTOVSR_LD: {
  2733. Register TargetReg = MI.getOperand(0).getReg();
  2734. if (PPC::VSFRCRegClass.contains(TargetReg)) {
  2735. MI.setDesc(get(PPC::DFLOADf64));
  2736. return expandPostRAPseudo(MI);
  2737. }
  2738. else
  2739. MI.setDesc(get(PPC::LD));
  2740. return true;
  2741. }
  2742. case PPC::SPILLTOVSR_ST: {
  2743. Register SrcReg = MI.getOperand(0).getReg();
  2744. if (PPC::VSFRCRegClass.contains(SrcReg)) {
  2745. NumStoreSPILLVSRRCAsVec++;
  2746. MI.setDesc(get(PPC::DFSTOREf64));
  2747. return expandPostRAPseudo(MI);
  2748. } else {
  2749. NumStoreSPILLVSRRCAsGpr++;
  2750. MI.setDesc(get(PPC::STD));
  2751. }
  2752. return true;
  2753. }
  2754. case PPC::SPILLTOVSR_LDX: {
  2755. Register TargetReg = MI.getOperand(0).getReg();
  2756. if (PPC::VSFRCRegClass.contains(TargetReg))
  2757. MI.setDesc(get(PPC::LXSDX));
  2758. else
  2759. MI.setDesc(get(PPC::LDX));
  2760. return true;
  2761. }
  2762. case PPC::SPILLTOVSR_STX: {
  2763. Register SrcReg = MI.getOperand(0).getReg();
  2764. if (PPC::VSFRCRegClass.contains(SrcReg)) {
  2765. NumStoreSPILLVSRRCAsVec++;
  2766. MI.setDesc(get(PPC::STXSDX));
  2767. } else {
  2768. NumStoreSPILLVSRRCAsGpr++;
  2769. MI.setDesc(get(PPC::STDX));
  2770. }
  2771. return true;
  2772. }
  2773. // FIXME: Maybe we can expand it in 'PowerPC Expand Atomic' pass.
  2774. case PPC::CFENCE8: {
  2775. auto Val = MI.getOperand(0).getReg();
  2776. BuildMI(MBB, MI, DL, get(PPC::CMPD), PPC::CR7).addReg(Val).addReg(Val);
  2777. BuildMI(MBB, MI, DL, get(PPC::CTRL_DEP))
  2778. .addImm(PPC::PRED_NE_MINUS)
  2779. .addReg(PPC::CR7)
  2780. .addImm(1);
  2781. MI.setDesc(get(PPC::ISYNC));
  2782. MI.RemoveOperand(0);
  2783. return true;
  2784. }
  2785. }
  2786. return false;
  2787. }
  2788. // Essentially a compile-time implementation of a compare->isel sequence.
  2789. // It takes two constants to compare, along with the true/false registers
  2790. // and the comparison type (as a subreg to a CR field) and returns one
  2791. // of the true/false registers, depending on the comparison results.
  2792. static unsigned selectReg(int64_t Imm1, int64_t Imm2, unsigned CompareOpc,
  2793. unsigned TrueReg, unsigned FalseReg,
  2794. unsigned CRSubReg) {
  2795. // Signed comparisons. The immediates are assumed to be sign-extended.
  2796. if (CompareOpc == PPC::CMPWI || CompareOpc == PPC::CMPDI) {
  2797. switch (CRSubReg) {
  2798. default: llvm_unreachable("Unknown integer comparison type.");
  2799. case PPC::sub_lt:
  2800. return Imm1 < Imm2 ? TrueReg : FalseReg;
  2801. case PPC::sub_gt:
  2802. return Imm1 > Imm2 ? TrueReg : FalseReg;
  2803. case PPC::sub_eq:
  2804. return Imm1 == Imm2 ? TrueReg : FalseReg;
  2805. }
  2806. }
  2807. // Unsigned comparisons.
  2808. else if (CompareOpc == PPC::CMPLWI || CompareOpc == PPC::CMPLDI) {
  2809. switch (CRSubReg) {
  2810. default: llvm_unreachable("Unknown integer comparison type.");
  2811. case PPC::sub_lt:
  2812. return (uint64_t)Imm1 < (uint64_t)Imm2 ? TrueReg : FalseReg;
  2813. case PPC::sub_gt:
  2814. return (uint64_t)Imm1 > (uint64_t)Imm2 ? TrueReg : FalseReg;
  2815. case PPC::sub_eq:
  2816. return Imm1 == Imm2 ? TrueReg : FalseReg;
  2817. }
  2818. }
  2819. return PPC::NoRegister;
  2820. }
  2821. void PPCInstrInfo::replaceInstrOperandWithImm(MachineInstr &MI,
  2822. unsigned OpNo,
  2823. int64_t Imm) const {
  2824. assert(MI.getOperand(OpNo).isReg() && "Operand must be a REG");
  2825. // Replace the REG with the Immediate.
  2826. Register InUseReg = MI.getOperand(OpNo).getReg();
  2827. MI.getOperand(OpNo).ChangeToImmediate(Imm);
  2828. // We need to make sure that the MI didn't have any implicit use
  2829. // of this REG any more. We don't call MI.implicit_operands().empty() to
  2830. // return early, since MI's MCID might be changed in calling context, as a
  2831. // result its number of explicit operands may be changed, thus the begin of
  2832. // implicit operand is changed.
  2833. const TargetRegisterInfo *TRI = &getRegisterInfo();
  2834. int UseOpIdx = MI.findRegisterUseOperandIdx(InUseReg, false, TRI);
  2835. if (UseOpIdx >= 0) {
  2836. MachineOperand &MO = MI.getOperand(UseOpIdx);
  2837. if (MO.isImplicit())
  2838. // The operands must always be in the following order:
  2839. // - explicit reg defs,
  2840. // - other explicit operands (reg uses, immediates, etc.),
  2841. // - implicit reg defs
  2842. // - implicit reg uses
  2843. // Therefore, removing the implicit operand won't change the explicit
  2844. // operands layout.
  2845. MI.RemoveOperand(UseOpIdx);
  2846. }
  2847. }
  2848. // Replace an instruction with one that materializes a constant (and sets
  2849. // CR0 if the original instruction was a record-form instruction).
  2850. void PPCInstrInfo::replaceInstrWithLI(MachineInstr &MI,
  2851. const LoadImmediateInfo &LII) const {
  2852. // Remove existing operands.
  2853. int OperandToKeep = LII.SetCR ? 1 : 0;
  2854. for (int i = MI.getNumOperands() - 1; i > OperandToKeep; i--)
  2855. MI.RemoveOperand(i);
  2856. // Replace the instruction.
  2857. if (LII.SetCR) {
  2858. MI.setDesc(get(LII.Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec));
  2859. // Set the immediate.
  2860. MachineInstrBuilder(*MI.getParent()->getParent(), MI)
  2861. .addImm(LII.Imm).addReg(PPC::CR0, RegState::ImplicitDefine);
  2862. return;
  2863. }
  2864. else
  2865. MI.setDesc(get(LII.Is64Bit ? PPC::LI8 : PPC::LI));
  2866. // Set the immediate.
  2867. MachineInstrBuilder(*MI.getParent()->getParent(), MI)
  2868. .addImm(LII.Imm);
  2869. }
  2870. MachineInstr *PPCInstrInfo::getDefMIPostRA(unsigned Reg, MachineInstr &MI,
  2871. bool &SeenIntermediateUse) const {
  2872. assert(!MI.getParent()->getParent()->getRegInfo().isSSA() &&
  2873. "Should be called after register allocation.");
  2874. const TargetRegisterInfo *TRI = &getRegisterInfo();
  2875. MachineBasicBlock::reverse_iterator E = MI.getParent()->rend(), It = MI;
  2876. It++;
  2877. SeenIntermediateUse = false;
  2878. for (; It != E; ++It) {
  2879. if (It->modifiesRegister(Reg, TRI))
  2880. return &*It;
  2881. if (It->readsRegister(Reg, TRI))
  2882. SeenIntermediateUse = true;
  2883. }
  2884. return nullptr;
  2885. }
  2886. MachineInstr *PPCInstrInfo::getForwardingDefMI(
  2887. MachineInstr &MI,
  2888. unsigned &OpNoForForwarding,
  2889. bool &SeenIntermediateUse) const {
  2890. OpNoForForwarding = ~0U;
  2891. MachineInstr *DefMI = nullptr;
  2892. MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
  2893. const TargetRegisterInfo *TRI = &getRegisterInfo();
  2894. // If we're in SSA, get the defs through the MRI. Otherwise, only look
  2895. // within the basic block to see if the register is defined using an
  2896. // LI/LI8/ADDI/ADDI8.
  2897. if (MRI->isSSA()) {
  2898. for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
  2899. if (!MI.getOperand(i).isReg())
  2900. continue;
  2901. Register Reg = MI.getOperand(i).getReg();
  2902. if (!Register::isVirtualRegister(Reg))
  2903. continue;
  2904. Register TrueReg = TRI->lookThruCopyLike(Reg, MRI);
  2905. if (Register::isVirtualRegister(TrueReg)) {
  2906. DefMI = MRI->getVRegDef(TrueReg);
  2907. if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8 ||
  2908. DefMI->getOpcode() == PPC::ADDI ||
  2909. DefMI->getOpcode() == PPC::ADDI8) {
  2910. OpNoForForwarding = i;
  2911. // The ADDI and LI operand maybe exist in one instruction at same
  2912. // time. we prefer to fold LI operand as LI only has one Imm operand
  2913. // and is more possible to be converted. So if current DefMI is
  2914. // ADDI/ADDI8, we continue to find possible LI/LI8.
  2915. if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8)
  2916. break;
  2917. }
  2918. }
  2919. }
  2920. } else {
  2921. // Looking back through the definition for each operand could be expensive,
  2922. // so exit early if this isn't an instruction that either has an immediate
  2923. // form or is already an immediate form that we can handle.
  2924. ImmInstrInfo III;
  2925. unsigned Opc = MI.getOpcode();
  2926. bool ConvertibleImmForm =
  2927. Opc == PPC::CMPWI || Opc == PPC::CMPLWI || Opc == PPC::CMPDI ||
  2928. Opc == PPC::CMPLDI || Opc == PPC::ADDI || Opc == PPC::ADDI8 ||
  2929. Opc == PPC::ORI || Opc == PPC::ORI8 || Opc == PPC::XORI ||
  2930. Opc == PPC::XORI8 || Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec ||
  2931. Opc == PPC::RLDICL_32 || Opc == PPC::RLDICL_32_64 ||
  2932. Opc == PPC::RLWINM || Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8 ||
  2933. Opc == PPC::RLWINM8_rec;
  2934. bool IsVFReg = (MI.getNumOperands() && MI.getOperand(0).isReg())
  2935. ? isVFRegister(MI.getOperand(0).getReg())
  2936. : false;
  2937. if (!ConvertibleImmForm && !instrHasImmForm(Opc, IsVFReg, III, true))
  2938. return nullptr;
  2939. // Don't convert or %X, %Y, %Y since that's just a register move.
  2940. if ((Opc == PPC::OR || Opc == PPC::OR8) &&
  2941. MI.getOperand(1).getReg() == MI.getOperand(2).getReg())
  2942. return nullptr;
  2943. for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
  2944. MachineOperand &MO = MI.getOperand(i);
  2945. SeenIntermediateUse = false;
  2946. if (MO.isReg() && MO.isUse() && !MO.isImplicit()) {
  2947. Register Reg = MI.getOperand(i).getReg();
  2948. // If we see another use of this reg between the def and the MI,
  2949. // we want to flat it so the def isn't deleted.
  2950. MachineInstr *DefMI = getDefMIPostRA(Reg, MI, SeenIntermediateUse);
  2951. if (DefMI) {
  2952. // Is this register defined by some form of add-immediate (including
  2953. // load-immediate) within this basic block?
  2954. switch (DefMI->getOpcode()) {
  2955. default:
  2956. break;
  2957. case PPC::LI:
  2958. case PPC::LI8:
  2959. case PPC::ADDItocL:
  2960. case PPC::ADDI:
  2961. case PPC::ADDI8:
  2962. OpNoForForwarding = i;
  2963. return DefMI;
  2964. }
  2965. }
  2966. }
  2967. }
  2968. }
  2969. return OpNoForForwarding == ~0U ? nullptr : DefMI;
  2970. }
  2971. unsigned PPCInstrInfo::getSpillTarget() const {
  2972. // With P10, we may need to spill paired vector registers or accumulator
  2973. // registers. MMA implies paired vectors, so we can just check that.
  2974. bool IsP10Variant = Subtarget.isISA3_1() || Subtarget.pairedVectorMemops();
  2975. return IsP10Variant ? 2 : Subtarget.hasP9Vector() ? 1 : 0;
  2976. }
  2977. const unsigned *PPCInstrInfo::getStoreOpcodesForSpillArray() const {
  2978. return StoreSpillOpcodesArray[getSpillTarget()];
  2979. }
  2980. const unsigned *PPCInstrInfo::getLoadOpcodesForSpillArray() const {
  2981. return LoadSpillOpcodesArray[getSpillTarget()];
  2982. }
  2983. void PPCInstrInfo::fixupIsDeadOrKill(MachineInstr *StartMI, MachineInstr *EndMI,
  2984. unsigned RegNo) const {
  2985. // Conservatively clear kill flag for the register if the instructions are in
  2986. // different basic blocks and in SSA form, because the kill flag may no longer
  2987. // be right. There is no need to bother with dead flags since defs with no
  2988. // uses will be handled by DCE.
  2989. MachineRegisterInfo &MRI = StartMI->getParent()->getParent()->getRegInfo();
  2990. if (MRI.isSSA() && (StartMI->getParent() != EndMI->getParent())) {
  2991. MRI.clearKillFlags(RegNo);
  2992. return;
  2993. }
  2994. // Instructions between [StartMI, EndMI] should be in same basic block.
  2995. assert((StartMI->getParent() == EndMI->getParent()) &&
  2996. "Instructions are not in same basic block");
  2997. // If before RA, StartMI may be def through COPY, we need to adjust it to the
  2998. // real def. See function getForwardingDefMI.
  2999. if (MRI.isSSA()) {
  3000. bool Reads, Writes;
  3001. std::tie(Reads, Writes) = StartMI->readsWritesVirtualRegister(RegNo);
  3002. if (!Reads && !Writes) {
  3003. assert(Register::isVirtualRegister(RegNo) &&
  3004. "Must be a virtual register");
  3005. // Get real def and ignore copies.
  3006. StartMI = MRI.getVRegDef(RegNo);
  3007. }
  3008. }
  3009. bool IsKillSet = false;
  3010. auto clearOperandKillInfo = [=] (MachineInstr &MI, unsigned Index) {
  3011. MachineOperand &MO = MI.getOperand(Index);
  3012. if (MO.isReg() && MO.isUse() && MO.isKill() &&
  3013. getRegisterInfo().regsOverlap(MO.getReg(), RegNo))
  3014. MO.setIsKill(false);
  3015. };
  3016. // Set killed flag for EndMI.
  3017. // No need to do anything if EndMI defines RegNo.
  3018. int UseIndex =
  3019. EndMI->findRegisterUseOperandIdx(RegNo, false, &getRegisterInfo());
  3020. if (UseIndex != -1) {
  3021. EndMI->getOperand(UseIndex).setIsKill(true);
  3022. IsKillSet = true;
  3023. // Clear killed flag for other EndMI operands related to RegNo. In some
  3024. // upexpected cases, killed may be set multiple times for same register
  3025. // operand in same MI.
  3026. for (int i = 0, e = EndMI->getNumOperands(); i != e; ++i)
  3027. if (i != UseIndex)
  3028. clearOperandKillInfo(*EndMI, i);
  3029. }
  3030. // Walking the inst in reverse order (EndMI -> StartMI].
  3031. MachineBasicBlock::reverse_iterator It = *EndMI;
  3032. MachineBasicBlock::reverse_iterator E = EndMI->getParent()->rend();
  3033. // EndMI has been handled above, skip it here.
  3034. It++;
  3035. MachineOperand *MO = nullptr;
  3036. for (; It != E; ++It) {
  3037. // Skip insturctions which could not be a def/use of RegNo.
  3038. if (It->isDebugInstr() || It->isPosition())
  3039. continue;
  3040. // Clear killed flag for all It operands related to RegNo. In some
  3041. // upexpected cases, killed may be set multiple times for same register
  3042. // operand in same MI.
  3043. for (int i = 0, e = It->getNumOperands(); i != e; ++i)
  3044. clearOperandKillInfo(*It, i);
  3045. // If killed is not set, set killed for its last use or set dead for its def
  3046. // if no use found.
  3047. if (!IsKillSet) {
  3048. if ((MO = It->findRegisterUseOperand(RegNo, false, &getRegisterInfo()))) {
  3049. // Use found, set it killed.
  3050. IsKillSet = true;
  3051. MO->setIsKill(true);
  3052. continue;
  3053. } else if ((MO = It->findRegisterDefOperand(RegNo, false, true,
  3054. &getRegisterInfo()))) {
  3055. // No use found, set dead for its def.
  3056. assert(&*It == StartMI && "No new def between StartMI and EndMI.");
  3057. MO->setIsDead(true);
  3058. break;
  3059. }
  3060. }
  3061. if ((&*It) == StartMI)
  3062. break;
  3063. }
  3064. // Ensure RegMo liveness is killed after EndMI.
  3065. assert((IsKillSet || (MO && MO->isDead())) &&
  3066. "RegNo should be killed or dead");
  3067. }
  3068. // This opt tries to convert the following imm form to an index form to save an
  3069. // add for stack variables.
  3070. // Return false if no such pattern found.
  3071. //
  3072. // ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, OffsetAddi
  3073. // ADD instr: ToBeDeletedReg = ADD ToBeChangedReg(killed), ScaleReg
  3074. // Imm instr: Reg = op OffsetImm, ToBeDeletedReg(killed)
  3075. //
  3076. // can be converted to:
  3077. //
  3078. // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, (OffsetAddi + OffsetImm)
  3079. // Index instr: Reg = opx ScaleReg, ToBeChangedReg(killed)
  3080. //
  3081. // In order to eliminate ADD instr, make sure that:
  3082. // 1: (OffsetAddi + OffsetImm) must be int16 since this offset will be used in
  3083. // new ADDI instr and ADDI can only take int16 Imm.
  3084. // 2: ToBeChangedReg must be killed in ADD instr and there is no other use
  3085. // between ADDI and ADD instr since its original def in ADDI will be changed
  3086. // in new ADDI instr. And also there should be no new def for it between
  3087. // ADD and Imm instr as ToBeChangedReg will be used in Index instr.
  3088. // 3: ToBeDeletedReg must be killed in Imm instr and there is no other use
  3089. // between ADD and Imm instr since ADD instr will be eliminated.
  3090. // 4: ScaleReg must not be redefined between ADD and Imm instr since it will be
  3091. // moved to Index instr.
  3092. bool PPCInstrInfo::foldFrameOffset(MachineInstr &MI) const {
  3093. MachineFunction *MF = MI.getParent()->getParent();
  3094. MachineRegisterInfo *MRI = &MF->getRegInfo();
  3095. bool PostRA = !MRI->isSSA();
  3096. // Do this opt after PEI which is after RA. The reason is stack slot expansion
  3097. // in PEI may expose such opportunities since in PEI, stack slot offsets to
  3098. // frame base(OffsetAddi) are determined.
  3099. if (!PostRA)
  3100. return false;
  3101. unsigned ToBeDeletedReg = 0;
  3102. int64_t OffsetImm = 0;
  3103. unsigned XFormOpcode = 0;
  3104. ImmInstrInfo III;
  3105. // Check if Imm instr meets requirement.
  3106. if (!isImmInstrEligibleForFolding(MI, ToBeDeletedReg, XFormOpcode, OffsetImm,
  3107. III))
  3108. return false;
  3109. bool OtherIntermediateUse = false;
  3110. MachineInstr *ADDMI = getDefMIPostRA(ToBeDeletedReg, MI, OtherIntermediateUse);
  3111. // Exit if there is other use between ADD and Imm instr or no def found.
  3112. if (OtherIntermediateUse || !ADDMI)
  3113. return false;
  3114. // Check if ADD instr meets requirement.
  3115. if (!isADDInstrEligibleForFolding(*ADDMI))
  3116. return false;
  3117. unsigned ScaleRegIdx = 0;
  3118. int64_t OffsetAddi = 0;
  3119. MachineInstr *ADDIMI = nullptr;
  3120. // Check if there is a valid ToBeChangedReg in ADDMI.
  3121. // 1: It must be killed.
  3122. // 2: Its definition must be a valid ADDIMI.
  3123. // 3: It must satify int16 offset requirement.
  3124. if (isValidToBeChangedReg(ADDMI, 1, ADDIMI, OffsetAddi, OffsetImm))
  3125. ScaleRegIdx = 2;
  3126. else if (isValidToBeChangedReg(ADDMI, 2, ADDIMI, OffsetAddi, OffsetImm))
  3127. ScaleRegIdx = 1;
  3128. else
  3129. return false;
  3130. assert(ADDIMI && "There should be ADDIMI for valid ToBeChangedReg.");
  3131. Register ToBeChangedReg = ADDIMI->getOperand(0).getReg();
  3132. Register ScaleReg = ADDMI->getOperand(ScaleRegIdx).getReg();
  3133. auto NewDefFor = [&](unsigned Reg, MachineBasicBlock::iterator Start,
  3134. MachineBasicBlock::iterator End) {
  3135. for (auto It = ++Start; It != End; It++)
  3136. if (It->modifiesRegister(Reg, &getRegisterInfo()))
  3137. return true;
  3138. return false;
  3139. };
  3140. // We are trying to replace the ImmOpNo with ScaleReg. Give up if it is
  3141. // treated as special zero when ScaleReg is R0/X0 register.
  3142. if (III.ZeroIsSpecialOrig == III.ImmOpNo &&
  3143. (ScaleReg == PPC::R0 || ScaleReg == PPC::X0))
  3144. return false;
  3145. // Make sure no other def for ToBeChangedReg and ScaleReg between ADD Instr
  3146. // and Imm Instr.
  3147. if (NewDefFor(ToBeChangedReg, *ADDMI, MI) || NewDefFor(ScaleReg, *ADDMI, MI))
  3148. return false;
  3149. // Now start to do the transformation.
  3150. LLVM_DEBUG(dbgs() << "Replace instruction: "
  3151. << "\n");
  3152. LLVM_DEBUG(ADDIMI->dump());
  3153. LLVM_DEBUG(ADDMI->dump());
  3154. LLVM_DEBUG(MI.dump());
  3155. LLVM_DEBUG(dbgs() << "with: "
  3156. << "\n");
  3157. // Update ADDI instr.
  3158. ADDIMI->getOperand(2).setImm(OffsetAddi + OffsetImm);
  3159. // Update Imm instr.
  3160. MI.setDesc(get(XFormOpcode));
  3161. MI.getOperand(III.ImmOpNo)
  3162. .ChangeToRegister(ScaleReg, false, false,
  3163. ADDMI->getOperand(ScaleRegIdx).isKill());
  3164. MI.getOperand(III.OpNoForForwarding)
  3165. .ChangeToRegister(ToBeChangedReg, false, false, true);
  3166. // Eliminate ADD instr.
  3167. ADDMI->eraseFromParent();
  3168. LLVM_DEBUG(ADDIMI->dump());
  3169. LLVM_DEBUG(MI.dump());
  3170. return true;
  3171. }
  3172. bool PPCInstrInfo::isADDIInstrEligibleForFolding(MachineInstr &ADDIMI,
  3173. int64_t &Imm) const {
  3174. unsigned Opc = ADDIMI.getOpcode();
  3175. // Exit if the instruction is not ADDI.
  3176. if (Opc != PPC::ADDI && Opc != PPC::ADDI8)
  3177. return false;
  3178. // The operand may not necessarily be an immediate - it could be a relocation.
  3179. if (!ADDIMI.getOperand(2).isImm())
  3180. return false;
  3181. Imm = ADDIMI.getOperand(2).getImm();
  3182. return true;
  3183. }
  3184. bool PPCInstrInfo::isADDInstrEligibleForFolding(MachineInstr &ADDMI) const {
  3185. unsigned Opc = ADDMI.getOpcode();
  3186. // Exit if the instruction is not ADD.
  3187. return Opc == PPC::ADD4 || Opc == PPC::ADD8;
  3188. }
  3189. bool PPCInstrInfo::isImmInstrEligibleForFolding(MachineInstr &MI,
  3190. unsigned &ToBeDeletedReg,
  3191. unsigned &XFormOpcode,
  3192. int64_t &OffsetImm,
  3193. ImmInstrInfo &III) const {
  3194. // Only handle load/store.
  3195. if (!MI.mayLoadOrStore())
  3196. return false;
  3197. unsigned Opc = MI.getOpcode();
  3198. XFormOpcode = RI.getMappedIdxOpcForImmOpc(Opc);
  3199. // Exit if instruction has no index form.
  3200. if (XFormOpcode == PPC::INSTRUCTION_LIST_END)
  3201. return false;
  3202. // TODO: sync the logic between instrHasImmForm() and ImmToIdxMap.
  3203. if (!instrHasImmForm(XFormOpcode, isVFRegister(MI.getOperand(0).getReg()),
  3204. III, true))
  3205. return false;
  3206. if (!III.IsSummingOperands)
  3207. return false;
  3208. MachineOperand ImmOperand = MI.getOperand(III.ImmOpNo);
  3209. MachineOperand RegOperand = MI.getOperand(III.OpNoForForwarding);
  3210. // Only support imm operands, not relocation slots or others.
  3211. if (!ImmOperand.isImm())
  3212. return false;
  3213. assert(RegOperand.isReg() && "Instruction format is not right");
  3214. // There are other use for ToBeDeletedReg after Imm instr, can not delete it.
  3215. if (!RegOperand.isKill())
  3216. return false;
  3217. ToBeDeletedReg = RegOperand.getReg();
  3218. OffsetImm = ImmOperand.getImm();
  3219. return true;
  3220. }
  3221. bool PPCInstrInfo::isValidToBeChangedReg(MachineInstr *ADDMI, unsigned Index,
  3222. MachineInstr *&ADDIMI,
  3223. int64_t &OffsetAddi,
  3224. int64_t OffsetImm) const {
  3225. assert((Index == 1 || Index == 2) && "Invalid operand index for add.");
  3226. MachineOperand &MO = ADDMI->getOperand(Index);
  3227. if (!MO.isKill())
  3228. return false;
  3229. bool OtherIntermediateUse = false;
  3230. ADDIMI = getDefMIPostRA(MO.getReg(), *ADDMI, OtherIntermediateUse);
  3231. // Currently handle only one "add + Imminstr" pair case, exit if other
  3232. // intermediate use for ToBeChangedReg found.
  3233. // TODO: handle the cases where there are other "add + Imminstr" pairs
  3234. // with same offset in Imminstr which is like:
  3235. //
  3236. // ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, OffsetAddi
  3237. // ADD instr1: ToBeDeletedReg1 = ADD ToBeChangedReg, ScaleReg1
  3238. // Imm instr1: Reg1 = op1 OffsetImm, ToBeDeletedReg1(killed)
  3239. // ADD instr2: ToBeDeletedReg2 = ADD ToBeChangedReg(killed), ScaleReg2
  3240. // Imm instr2: Reg2 = op2 OffsetImm, ToBeDeletedReg2(killed)
  3241. //
  3242. // can be converted to:
  3243. //
  3244. // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg,
  3245. // (OffsetAddi + OffsetImm)
  3246. // Index instr1: Reg1 = opx1 ScaleReg1, ToBeChangedReg
  3247. // Index instr2: Reg2 = opx2 ScaleReg2, ToBeChangedReg(killed)
  3248. if (OtherIntermediateUse || !ADDIMI)
  3249. return false;
  3250. // Check if ADDI instr meets requirement.
  3251. if (!isADDIInstrEligibleForFolding(*ADDIMI, OffsetAddi))
  3252. return false;
  3253. if (isInt<16>(OffsetAddi + OffsetImm))
  3254. return true;
  3255. return false;
  3256. }
  3257. // If this instruction has an immediate form and one of its operands is a
  3258. // result of a load-immediate or an add-immediate, convert it to
  3259. // the immediate form if the constant is in range.
  3260. bool PPCInstrInfo::convertToImmediateForm(MachineInstr &MI,
  3261. MachineInstr **KilledDef) const {
  3262. MachineFunction *MF = MI.getParent()->getParent();
  3263. MachineRegisterInfo *MRI = &MF->getRegInfo();
  3264. bool PostRA = !MRI->isSSA();
  3265. bool SeenIntermediateUse = true;
  3266. unsigned ForwardingOperand = ~0U;
  3267. MachineInstr *DefMI = getForwardingDefMI(MI, ForwardingOperand,
  3268. SeenIntermediateUse);
  3269. if (!DefMI)
  3270. return false;
  3271. assert(ForwardingOperand < MI.getNumOperands() &&
  3272. "The forwarding operand needs to be valid at this point");
  3273. bool IsForwardingOperandKilled = MI.getOperand(ForwardingOperand).isKill();
  3274. bool KillFwdDefMI = !SeenIntermediateUse && IsForwardingOperandKilled;
  3275. if (KilledDef && KillFwdDefMI)
  3276. *KilledDef = DefMI;
  3277. // If this is a imm instruction and its register operands is produced by ADDI,
  3278. // put the imm into imm inst directly.
  3279. if (RI.getMappedIdxOpcForImmOpc(MI.getOpcode()) !=
  3280. PPC::INSTRUCTION_LIST_END &&
  3281. transformToNewImmFormFedByAdd(MI, *DefMI, ForwardingOperand))
  3282. return true;
  3283. ImmInstrInfo III;
  3284. bool IsVFReg = MI.getOperand(0).isReg()
  3285. ? isVFRegister(MI.getOperand(0).getReg())
  3286. : false;
  3287. bool HasImmForm = instrHasImmForm(MI.getOpcode(), IsVFReg, III, PostRA);
  3288. // If this is a reg+reg instruction that has a reg+imm form,
  3289. // and one of the operands is produced by an add-immediate,
  3290. // try to convert it.
  3291. if (HasImmForm &&
  3292. transformToImmFormFedByAdd(MI, III, ForwardingOperand, *DefMI,
  3293. KillFwdDefMI))
  3294. return true;
  3295. // If this is a reg+reg instruction that has a reg+imm form,
  3296. // and one of the operands is produced by LI, convert it now.
  3297. if (HasImmForm &&
  3298. transformToImmFormFedByLI(MI, III, ForwardingOperand, *DefMI))
  3299. return true;
  3300. // If this is not a reg+reg, but the DefMI is LI/LI8, check if its user MI
  3301. // can be simpified to LI.
  3302. if (!HasImmForm && simplifyToLI(MI, *DefMI, ForwardingOperand, KilledDef))
  3303. return true;
  3304. return false;
  3305. }
  3306. bool PPCInstrInfo::combineRLWINM(MachineInstr &MI,
  3307. MachineInstr **ToErase) const {
  3308. MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
  3309. Register FoldingReg = MI.getOperand(1).getReg();
  3310. if (!Register::isVirtualRegister(FoldingReg))
  3311. return false;
  3312. MachineInstr *SrcMI = MRI->getVRegDef(FoldingReg);
  3313. if (SrcMI->getOpcode() != PPC::RLWINM &&
  3314. SrcMI->getOpcode() != PPC::RLWINM_rec &&
  3315. SrcMI->getOpcode() != PPC::RLWINM8 &&
  3316. SrcMI->getOpcode() != PPC::RLWINM8_rec)
  3317. return false;
  3318. assert((MI.getOperand(2).isImm() && MI.getOperand(3).isImm() &&
  3319. MI.getOperand(4).isImm() && SrcMI->getOperand(2).isImm() &&
  3320. SrcMI->getOperand(3).isImm() && SrcMI->getOperand(4).isImm()) &&
  3321. "Invalid PPC::RLWINM Instruction!");
  3322. uint64_t SHSrc = SrcMI->getOperand(2).getImm();
  3323. uint64_t SHMI = MI.getOperand(2).getImm();
  3324. uint64_t MBSrc = SrcMI->getOperand(3).getImm();
  3325. uint64_t MBMI = MI.getOperand(3).getImm();
  3326. uint64_t MESrc = SrcMI->getOperand(4).getImm();
  3327. uint64_t MEMI = MI.getOperand(4).getImm();
  3328. assert((MEMI < 32 && MESrc < 32 && MBMI < 32 && MBSrc < 32) &&
  3329. "Invalid PPC::RLWINM Instruction!");
  3330. // If MBMI is bigger than MEMI, we always can not get run of ones.
  3331. // RotatedSrcMask non-wrap:
  3332. // 0........31|32........63
  3333. // RotatedSrcMask: B---E B---E
  3334. // MaskMI: -----------|--E B------
  3335. // Result: ----- --- (Bad candidate)
  3336. //
  3337. // RotatedSrcMask wrap:
  3338. // 0........31|32........63
  3339. // RotatedSrcMask: --E B----|--E B----
  3340. // MaskMI: -----------|--E B------
  3341. // Result: --- -----|--- ----- (Bad candidate)
  3342. //
  3343. // One special case is RotatedSrcMask is a full set mask.
  3344. // RotatedSrcMask full:
  3345. // 0........31|32........63
  3346. // RotatedSrcMask: ------EB---|-------EB---
  3347. // MaskMI: -----------|--E B------
  3348. // Result: -----------|--- ------- (Good candidate)
  3349. // Mark special case.
  3350. bool SrcMaskFull = (MBSrc - MESrc == 1) || (MBSrc == 0 && MESrc == 31);
  3351. // For other MBMI > MEMI cases, just return.
  3352. if ((MBMI > MEMI) && !SrcMaskFull)
  3353. return false;
  3354. // Handle MBMI <= MEMI cases.
  3355. APInt MaskMI = APInt::getBitsSetWithWrap(32, 32 - MEMI - 1, 32 - MBMI);
  3356. // In MI, we only need low 32 bits of SrcMI, just consider about low 32
  3357. // bit of SrcMI mask. Note that in APInt, lowerest bit is at index 0,
  3358. // while in PowerPC ISA, lowerest bit is at index 63.
  3359. APInt MaskSrc = APInt::getBitsSetWithWrap(32, 32 - MESrc - 1, 32 - MBSrc);
  3360. APInt RotatedSrcMask = MaskSrc.rotl(SHMI);
  3361. APInt FinalMask = RotatedSrcMask & MaskMI;
  3362. uint32_t NewMB, NewME;
  3363. bool Simplified = false;
  3364. // If final mask is 0, MI result should be 0 too.
  3365. if (FinalMask.isZero()) {
  3366. bool Is64Bit =
  3367. (MI.getOpcode() == PPC::RLWINM8 || MI.getOpcode() == PPC::RLWINM8_rec);
  3368. Simplified = true;
  3369. LLVM_DEBUG(dbgs() << "Replace Instr: ");
  3370. LLVM_DEBUG(MI.dump());
  3371. if (MI.getOpcode() == PPC::RLWINM || MI.getOpcode() == PPC::RLWINM8) {
  3372. // Replace MI with "LI 0"
  3373. MI.RemoveOperand(4);
  3374. MI.RemoveOperand(3);
  3375. MI.RemoveOperand(2);
  3376. MI.getOperand(1).ChangeToImmediate(0);
  3377. MI.setDesc(get(Is64Bit ? PPC::LI8 : PPC::LI));
  3378. } else {
  3379. // Replace MI with "ANDI_rec reg, 0"
  3380. MI.RemoveOperand(4);
  3381. MI.RemoveOperand(3);
  3382. MI.getOperand(2).setImm(0);
  3383. MI.setDesc(get(Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec));
  3384. MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
  3385. if (SrcMI->getOperand(1).isKill()) {
  3386. MI.getOperand(1).setIsKill(true);
  3387. SrcMI->getOperand(1).setIsKill(false);
  3388. } else
  3389. // About to replace MI.getOperand(1), clear its kill flag.
  3390. MI.getOperand(1).setIsKill(false);
  3391. }
  3392. LLVM_DEBUG(dbgs() << "With: ");
  3393. LLVM_DEBUG(MI.dump());
  3394. } else if ((isRunOfOnes((unsigned)(FinalMask.getZExtValue()), NewMB, NewME) &&
  3395. NewMB <= NewME) ||
  3396. SrcMaskFull) {
  3397. // Here we only handle MBMI <= MEMI case, so NewMB must be no bigger
  3398. // than NewME. Otherwise we get a 64 bit value after folding, but MI
  3399. // return a 32 bit value.
  3400. Simplified = true;
  3401. LLVM_DEBUG(dbgs() << "Converting Instr: ");
  3402. LLVM_DEBUG(MI.dump());
  3403. uint16_t NewSH = (SHSrc + SHMI) % 32;
  3404. MI.getOperand(2).setImm(NewSH);
  3405. // If SrcMI mask is full, no need to update MBMI and MEMI.
  3406. if (!SrcMaskFull) {
  3407. MI.getOperand(3).setImm(NewMB);
  3408. MI.getOperand(4).setImm(NewME);
  3409. }
  3410. MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
  3411. if (SrcMI->getOperand(1).isKill()) {
  3412. MI.getOperand(1).setIsKill(true);
  3413. SrcMI->getOperand(1).setIsKill(false);
  3414. } else
  3415. // About to replace MI.getOperand(1), clear its kill flag.
  3416. MI.getOperand(1).setIsKill(false);
  3417. LLVM_DEBUG(dbgs() << "To: ");
  3418. LLVM_DEBUG(MI.dump());
  3419. }
  3420. if (Simplified & MRI->use_nodbg_empty(FoldingReg) &&
  3421. !SrcMI->hasImplicitDef()) {
  3422. // If FoldingReg has no non-debug use and it has no implicit def (it
  3423. // is not RLWINMO or RLWINM8o), it's safe to delete its def SrcMI.
  3424. // Otherwise keep it.
  3425. *ToErase = SrcMI;
  3426. LLVM_DEBUG(dbgs() << "Delete dead instruction: ");
  3427. LLVM_DEBUG(SrcMI->dump());
  3428. }
  3429. return Simplified;
  3430. }
  3431. bool PPCInstrInfo::instrHasImmForm(unsigned Opc, bool IsVFReg,
  3432. ImmInstrInfo &III, bool PostRA) const {
  3433. // The vast majority of the instructions would need their operand 2 replaced
  3434. // with an immediate when switching to the reg+imm form. A marked exception
  3435. // are the update form loads/stores for which a constant operand 2 would need
  3436. // to turn into a displacement and move operand 1 to the operand 2 position.
  3437. III.ImmOpNo = 2;
  3438. III.OpNoForForwarding = 2;
  3439. III.ImmWidth = 16;
  3440. III.ImmMustBeMultipleOf = 1;
  3441. III.TruncateImmTo = 0;
  3442. III.IsSummingOperands = false;
  3443. switch (Opc) {
  3444. default: return false;
  3445. case PPC::ADD4:
  3446. case PPC::ADD8:
  3447. III.SignedImm = true;
  3448. III.ZeroIsSpecialOrig = 0;
  3449. III.ZeroIsSpecialNew = 1;
  3450. III.IsCommutative = true;
  3451. III.IsSummingOperands = true;
  3452. III.ImmOpcode = Opc == PPC::ADD4 ? PPC::ADDI : PPC::ADDI8;
  3453. break;
  3454. case PPC::ADDC:
  3455. case PPC::ADDC8:
  3456. III.SignedImm = true;
  3457. III.ZeroIsSpecialOrig = 0;
  3458. III.ZeroIsSpecialNew = 0;
  3459. III.IsCommutative = true;
  3460. III.IsSummingOperands = true;
  3461. III.ImmOpcode = Opc == PPC::ADDC ? PPC::ADDIC : PPC::ADDIC8;
  3462. break;
  3463. case PPC::ADDC_rec:
  3464. III.SignedImm = true;
  3465. III.ZeroIsSpecialOrig = 0;
  3466. III.ZeroIsSpecialNew = 0;
  3467. III.IsCommutative = true;
  3468. III.IsSummingOperands = true;
  3469. III.ImmOpcode = PPC::ADDIC_rec;
  3470. break;
  3471. case PPC::SUBFC:
  3472. case PPC::SUBFC8:
  3473. III.SignedImm = true;
  3474. III.ZeroIsSpecialOrig = 0;
  3475. III.ZeroIsSpecialNew = 0;
  3476. III.IsCommutative = false;
  3477. III.ImmOpcode = Opc == PPC::SUBFC ? PPC::SUBFIC : PPC::SUBFIC8;
  3478. break;
  3479. case PPC::CMPW:
  3480. case PPC::CMPD:
  3481. III.SignedImm = true;
  3482. III.ZeroIsSpecialOrig = 0;
  3483. III.ZeroIsSpecialNew = 0;
  3484. III.IsCommutative = false;
  3485. III.ImmOpcode = Opc == PPC::CMPW ? PPC::CMPWI : PPC::CMPDI;
  3486. break;
  3487. case PPC::CMPLW:
  3488. case PPC::CMPLD:
  3489. III.SignedImm = false;
  3490. III.ZeroIsSpecialOrig = 0;
  3491. III.ZeroIsSpecialNew = 0;
  3492. III.IsCommutative = false;
  3493. III.ImmOpcode = Opc == PPC::CMPLW ? PPC::CMPLWI : PPC::CMPLDI;
  3494. break;
  3495. case PPC::AND_rec:
  3496. case PPC::AND8_rec:
  3497. case PPC::OR:
  3498. case PPC::OR8:
  3499. case PPC::XOR:
  3500. case PPC::XOR8:
  3501. III.SignedImm = false;
  3502. III.ZeroIsSpecialOrig = 0;
  3503. III.ZeroIsSpecialNew = 0;
  3504. III.IsCommutative = true;
  3505. switch(Opc) {
  3506. default: llvm_unreachable("Unknown opcode");
  3507. case PPC::AND_rec:
  3508. III.ImmOpcode = PPC::ANDI_rec;
  3509. break;
  3510. case PPC::AND8_rec:
  3511. III.ImmOpcode = PPC::ANDI8_rec;
  3512. break;
  3513. case PPC::OR: III.ImmOpcode = PPC::ORI; break;
  3514. case PPC::OR8: III.ImmOpcode = PPC::ORI8; break;
  3515. case PPC::XOR: III.ImmOpcode = PPC::XORI; break;
  3516. case PPC::XOR8: III.ImmOpcode = PPC::XORI8; break;
  3517. }
  3518. break;
  3519. case PPC::RLWNM:
  3520. case PPC::RLWNM8:
  3521. case PPC::RLWNM_rec:
  3522. case PPC::RLWNM8_rec:
  3523. case PPC::SLW:
  3524. case PPC::SLW8:
  3525. case PPC::SLW_rec:
  3526. case PPC::SLW8_rec:
  3527. case PPC::SRW:
  3528. case PPC::SRW8:
  3529. case PPC::SRW_rec:
  3530. case PPC::SRW8_rec:
  3531. case PPC::SRAW:
  3532. case PPC::SRAW_rec:
  3533. III.SignedImm = false;
  3534. III.ZeroIsSpecialOrig = 0;
  3535. III.ZeroIsSpecialNew = 0;
  3536. III.IsCommutative = false;
  3537. // This isn't actually true, but the instructions ignore any of the
  3538. // upper bits, so any immediate loaded with an LI is acceptable.
  3539. // This does not apply to shift right algebraic because a value
  3540. // out of range will produce a -1/0.
  3541. III.ImmWidth = 16;
  3542. if (Opc == PPC::RLWNM || Opc == PPC::RLWNM8 || Opc == PPC::RLWNM_rec ||
  3543. Opc == PPC::RLWNM8_rec)
  3544. III.TruncateImmTo = 5;
  3545. else
  3546. III.TruncateImmTo = 6;
  3547. switch(Opc) {
  3548. default: llvm_unreachable("Unknown opcode");
  3549. case PPC::RLWNM: III.ImmOpcode = PPC::RLWINM; break;
  3550. case PPC::RLWNM8: III.ImmOpcode = PPC::RLWINM8; break;
  3551. case PPC::RLWNM_rec:
  3552. III.ImmOpcode = PPC::RLWINM_rec;
  3553. break;
  3554. case PPC::RLWNM8_rec:
  3555. III.ImmOpcode = PPC::RLWINM8_rec;
  3556. break;
  3557. case PPC::SLW: III.ImmOpcode = PPC::RLWINM; break;
  3558. case PPC::SLW8: III.ImmOpcode = PPC::RLWINM8; break;
  3559. case PPC::SLW_rec:
  3560. III.ImmOpcode = PPC::RLWINM_rec;
  3561. break;
  3562. case PPC::SLW8_rec:
  3563. III.ImmOpcode = PPC::RLWINM8_rec;
  3564. break;
  3565. case PPC::SRW: III.ImmOpcode = PPC::RLWINM; break;
  3566. case PPC::SRW8: III.ImmOpcode = PPC::RLWINM8; break;
  3567. case PPC::SRW_rec:
  3568. III.ImmOpcode = PPC::RLWINM_rec;
  3569. break;
  3570. case PPC::SRW8_rec:
  3571. III.ImmOpcode = PPC::RLWINM8_rec;
  3572. break;
  3573. case PPC::SRAW:
  3574. III.ImmWidth = 5;
  3575. III.TruncateImmTo = 0;
  3576. III.ImmOpcode = PPC::SRAWI;
  3577. break;
  3578. case PPC::SRAW_rec:
  3579. III.ImmWidth = 5;
  3580. III.TruncateImmTo = 0;
  3581. III.ImmOpcode = PPC::SRAWI_rec;
  3582. break;
  3583. }
  3584. break;
  3585. case PPC::RLDCL:
  3586. case PPC::RLDCL_rec:
  3587. case PPC::RLDCR:
  3588. case PPC::RLDCR_rec:
  3589. case PPC::SLD:
  3590. case PPC::SLD_rec:
  3591. case PPC::SRD:
  3592. case PPC::SRD_rec:
  3593. case PPC::SRAD:
  3594. case PPC::SRAD_rec:
  3595. III.SignedImm = false;
  3596. III.ZeroIsSpecialOrig = 0;
  3597. III.ZeroIsSpecialNew = 0;
  3598. III.IsCommutative = false;
  3599. // This isn't actually true, but the instructions ignore any of the
  3600. // upper bits, so any immediate loaded with an LI is acceptable.
  3601. // This does not apply to shift right algebraic because a value
  3602. // out of range will produce a -1/0.
  3603. III.ImmWidth = 16;
  3604. if (Opc == PPC::RLDCL || Opc == PPC::RLDCL_rec || Opc == PPC::RLDCR ||
  3605. Opc == PPC::RLDCR_rec)
  3606. III.TruncateImmTo = 6;
  3607. else
  3608. III.TruncateImmTo = 7;
  3609. switch(Opc) {
  3610. default: llvm_unreachable("Unknown opcode");
  3611. case PPC::RLDCL: III.ImmOpcode = PPC::RLDICL; break;
  3612. case PPC::RLDCL_rec:
  3613. III.ImmOpcode = PPC::RLDICL_rec;
  3614. break;
  3615. case PPC::RLDCR: III.ImmOpcode = PPC::RLDICR; break;
  3616. case PPC::RLDCR_rec:
  3617. III.ImmOpcode = PPC::RLDICR_rec;
  3618. break;
  3619. case PPC::SLD: III.ImmOpcode = PPC::RLDICR; break;
  3620. case PPC::SLD_rec:
  3621. III.ImmOpcode = PPC::RLDICR_rec;
  3622. break;
  3623. case PPC::SRD: III.ImmOpcode = PPC::RLDICL; break;
  3624. case PPC::SRD_rec:
  3625. III.ImmOpcode = PPC::RLDICL_rec;
  3626. break;
  3627. case PPC::SRAD:
  3628. III.ImmWidth = 6;
  3629. III.TruncateImmTo = 0;
  3630. III.ImmOpcode = PPC::SRADI;
  3631. break;
  3632. case PPC::SRAD_rec:
  3633. III.ImmWidth = 6;
  3634. III.TruncateImmTo = 0;
  3635. III.ImmOpcode = PPC::SRADI_rec;
  3636. break;
  3637. }
  3638. break;
  3639. // Loads and stores:
  3640. case PPC::LBZX:
  3641. case PPC::LBZX8:
  3642. case PPC::LHZX:
  3643. case PPC::LHZX8:
  3644. case PPC::LHAX:
  3645. case PPC::LHAX8:
  3646. case PPC::LWZX:
  3647. case PPC::LWZX8:
  3648. case PPC::LWAX:
  3649. case PPC::LDX:
  3650. case PPC::LFSX:
  3651. case PPC::LFDX:
  3652. case PPC::STBX:
  3653. case PPC::STBX8:
  3654. case PPC::STHX:
  3655. case PPC::STHX8:
  3656. case PPC::STWX:
  3657. case PPC::STWX8:
  3658. case PPC::STDX:
  3659. case PPC::STFSX:
  3660. case PPC::STFDX:
  3661. III.SignedImm = true;
  3662. III.ZeroIsSpecialOrig = 1;
  3663. III.ZeroIsSpecialNew = 2;
  3664. III.IsCommutative = true;
  3665. III.IsSummingOperands = true;
  3666. III.ImmOpNo = 1;
  3667. III.OpNoForForwarding = 2;
  3668. switch(Opc) {
  3669. default: llvm_unreachable("Unknown opcode");
  3670. case PPC::LBZX: III.ImmOpcode = PPC::LBZ; break;
  3671. case PPC::LBZX8: III.ImmOpcode = PPC::LBZ8; break;
  3672. case PPC::LHZX: III.ImmOpcode = PPC::LHZ; break;
  3673. case PPC::LHZX8: III.ImmOpcode = PPC::LHZ8; break;
  3674. case PPC::LHAX: III.ImmOpcode = PPC::LHA; break;
  3675. case PPC::LHAX8: III.ImmOpcode = PPC::LHA8; break;
  3676. case PPC::LWZX: III.ImmOpcode = PPC::LWZ; break;
  3677. case PPC::LWZX8: III.ImmOpcode = PPC::LWZ8; break;
  3678. case PPC::LWAX:
  3679. III.ImmOpcode = PPC::LWA;
  3680. III.ImmMustBeMultipleOf = 4;
  3681. break;
  3682. case PPC::LDX: III.ImmOpcode = PPC::LD; III.ImmMustBeMultipleOf = 4; break;
  3683. case PPC::LFSX: III.ImmOpcode = PPC::LFS; break;
  3684. case PPC::LFDX: III.ImmOpcode = PPC::LFD; break;
  3685. case PPC::STBX: III.ImmOpcode = PPC::STB; break;
  3686. case PPC::STBX8: III.ImmOpcode = PPC::STB8; break;
  3687. case PPC::STHX: III.ImmOpcode = PPC::STH; break;
  3688. case PPC::STHX8: III.ImmOpcode = PPC::STH8; break;
  3689. case PPC::STWX: III.ImmOpcode = PPC::STW; break;
  3690. case PPC::STWX8: III.ImmOpcode = PPC::STW8; break;
  3691. case PPC::STDX:
  3692. III.ImmOpcode = PPC::STD;
  3693. III.ImmMustBeMultipleOf = 4;
  3694. break;
  3695. case PPC::STFSX: III.ImmOpcode = PPC::STFS; break;
  3696. case PPC::STFDX: III.ImmOpcode = PPC::STFD; break;
  3697. }
  3698. break;
  3699. case PPC::LBZUX:
  3700. case PPC::LBZUX8:
  3701. case PPC::LHZUX:
  3702. case PPC::LHZUX8:
  3703. case PPC::LHAUX:
  3704. case PPC::LHAUX8:
  3705. case PPC::LWZUX:
  3706. case PPC::LWZUX8:
  3707. case PPC::LDUX:
  3708. case PPC::LFSUX:
  3709. case PPC::LFDUX:
  3710. case PPC::STBUX:
  3711. case PPC::STBUX8:
  3712. case PPC::STHUX:
  3713. case PPC::STHUX8:
  3714. case PPC::STWUX:
  3715. case PPC::STWUX8:
  3716. case PPC::STDUX:
  3717. case PPC::STFSUX:
  3718. case PPC::STFDUX:
  3719. III.SignedImm = true;
  3720. III.ZeroIsSpecialOrig = 2;
  3721. III.ZeroIsSpecialNew = 3;
  3722. III.IsCommutative = false;
  3723. III.IsSummingOperands = true;
  3724. III.ImmOpNo = 2;
  3725. III.OpNoForForwarding = 3;
  3726. switch(Opc) {
  3727. default: llvm_unreachable("Unknown opcode");
  3728. case PPC::LBZUX: III.ImmOpcode = PPC::LBZU; break;
  3729. case PPC::LBZUX8: III.ImmOpcode = PPC::LBZU8; break;
  3730. case PPC::LHZUX: III.ImmOpcode = PPC::LHZU; break;
  3731. case PPC::LHZUX8: III.ImmOpcode = PPC::LHZU8; break;
  3732. case PPC::LHAUX: III.ImmOpcode = PPC::LHAU; break;
  3733. case PPC::LHAUX8: III.ImmOpcode = PPC::LHAU8; break;
  3734. case PPC::LWZUX: III.ImmOpcode = PPC::LWZU; break;
  3735. case PPC::LWZUX8: III.ImmOpcode = PPC::LWZU8; break;
  3736. case PPC::LDUX:
  3737. III.ImmOpcode = PPC::LDU;
  3738. III.ImmMustBeMultipleOf = 4;
  3739. break;
  3740. case PPC::LFSUX: III.ImmOpcode = PPC::LFSU; break;
  3741. case PPC::LFDUX: III.ImmOpcode = PPC::LFDU; break;
  3742. case PPC::STBUX: III.ImmOpcode = PPC::STBU; break;
  3743. case PPC::STBUX8: III.ImmOpcode = PPC::STBU8; break;
  3744. case PPC::STHUX: III.ImmOpcode = PPC::STHU; break;
  3745. case PPC::STHUX8: III.ImmOpcode = PPC::STHU8; break;
  3746. case PPC::STWUX: III.ImmOpcode = PPC::STWU; break;
  3747. case PPC::STWUX8: III.ImmOpcode = PPC::STWU8; break;
  3748. case PPC::STDUX:
  3749. III.ImmOpcode = PPC::STDU;
  3750. III.ImmMustBeMultipleOf = 4;
  3751. break;
  3752. case PPC::STFSUX: III.ImmOpcode = PPC::STFSU; break;
  3753. case PPC::STFDUX: III.ImmOpcode = PPC::STFDU; break;
  3754. }
  3755. break;
  3756. // Power9 and up only. For some of these, the X-Form version has access to all
  3757. // 64 VSR's whereas the D-Form only has access to the VR's. We replace those
  3758. // with pseudo-ops pre-ra and for post-ra, we check that the register loaded
  3759. // into or stored from is one of the VR registers.
  3760. case PPC::LXVX:
  3761. case PPC::LXSSPX:
  3762. case PPC::LXSDX:
  3763. case PPC::STXVX:
  3764. case PPC::STXSSPX:
  3765. case PPC::STXSDX:
  3766. case PPC::XFLOADf32:
  3767. case PPC::XFLOADf64:
  3768. case PPC::XFSTOREf32:
  3769. case PPC::XFSTOREf64:
  3770. if (!Subtarget.hasP9Vector())
  3771. return false;
  3772. III.SignedImm = true;
  3773. III.ZeroIsSpecialOrig = 1;
  3774. III.ZeroIsSpecialNew = 2;
  3775. III.IsCommutative = true;
  3776. III.IsSummingOperands = true;
  3777. III.ImmOpNo = 1;
  3778. III.OpNoForForwarding = 2;
  3779. III.ImmMustBeMultipleOf = 4;
  3780. switch(Opc) {
  3781. default: llvm_unreachable("Unknown opcode");
  3782. case PPC::LXVX:
  3783. III.ImmOpcode = PPC::LXV;
  3784. III.ImmMustBeMultipleOf = 16;
  3785. break;
  3786. case PPC::LXSSPX:
  3787. if (PostRA) {
  3788. if (IsVFReg)
  3789. III.ImmOpcode = PPC::LXSSP;
  3790. else {
  3791. III.ImmOpcode = PPC::LFS;
  3792. III.ImmMustBeMultipleOf = 1;
  3793. }
  3794. break;
  3795. }
  3796. LLVM_FALLTHROUGH;
  3797. case PPC::XFLOADf32:
  3798. III.ImmOpcode = PPC::DFLOADf32;
  3799. break;
  3800. case PPC::LXSDX:
  3801. if (PostRA) {
  3802. if (IsVFReg)
  3803. III.ImmOpcode = PPC::LXSD;
  3804. else {
  3805. III.ImmOpcode = PPC::LFD;
  3806. III.ImmMustBeMultipleOf = 1;
  3807. }
  3808. break;
  3809. }
  3810. LLVM_FALLTHROUGH;
  3811. case PPC::XFLOADf64:
  3812. III.ImmOpcode = PPC::DFLOADf64;
  3813. break;
  3814. case PPC::STXVX:
  3815. III.ImmOpcode = PPC::STXV;
  3816. III.ImmMustBeMultipleOf = 16;
  3817. break;
  3818. case PPC::STXSSPX:
  3819. if (PostRA) {
  3820. if (IsVFReg)
  3821. III.ImmOpcode = PPC::STXSSP;
  3822. else {
  3823. III.ImmOpcode = PPC::STFS;
  3824. III.ImmMustBeMultipleOf = 1;
  3825. }
  3826. break;
  3827. }
  3828. LLVM_FALLTHROUGH;
  3829. case PPC::XFSTOREf32:
  3830. III.ImmOpcode = PPC::DFSTOREf32;
  3831. break;
  3832. case PPC::STXSDX:
  3833. if (PostRA) {
  3834. if (IsVFReg)
  3835. III.ImmOpcode = PPC::STXSD;
  3836. else {
  3837. III.ImmOpcode = PPC::STFD;
  3838. III.ImmMustBeMultipleOf = 1;
  3839. }
  3840. break;
  3841. }
  3842. LLVM_FALLTHROUGH;
  3843. case PPC::XFSTOREf64:
  3844. III.ImmOpcode = PPC::DFSTOREf64;
  3845. break;
  3846. }
  3847. break;
  3848. }
  3849. return true;
  3850. }
  3851. // Utility function for swaping two arbitrary operands of an instruction.
  3852. static void swapMIOperands(MachineInstr &MI, unsigned Op1, unsigned Op2) {
  3853. assert(Op1 != Op2 && "Cannot swap operand with itself.");
  3854. unsigned MaxOp = std::max(Op1, Op2);
  3855. unsigned MinOp = std::min(Op1, Op2);
  3856. MachineOperand MOp1 = MI.getOperand(MinOp);
  3857. MachineOperand MOp2 = MI.getOperand(MaxOp);
  3858. MI.RemoveOperand(std::max(Op1, Op2));
  3859. MI.RemoveOperand(std::min(Op1, Op2));
  3860. // If the operands we are swapping are the two at the end (the common case)
  3861. // we can just remove both and add them in the opposite order.
  3862. if (MaxOp - MinOp == 1 && MI.getNumOperands() == MinOp) {
  3863. MI.addOperand(MOp2);
  3864. MI.addOperand(MOp1);
  3865. } else {
  3866. // Store all operands in a temporary vector, remove them and re-add in the
  3867. // right order.
  3868. SmallVector<MachineOperand, 2> MOps;
  3869. unsigned TotalOps = MI.getNumOperands() + 2; // We've already removed 2 ops.
  3870. for (unsigned i = MI.getNumOperands() - 1; i >= MinOp; i--) {
  3871. MOps.push_back(MI.getOperand(i));
  3872. MI.RemoveOperand(i);
  3873. }
  3874. // MOp2 needs to be added next.
  3875. MI.addOperand(MOp2);
  3876. // Now add the rest.
  3877. for (unsigned i = MI.getNumOperands(); i < TotalOps; i++) {
  3878. if (i == MaxOp)
  3879. MI.addOperand(MOp1);
  3880. else {
  3881. MI.addOperand(MOps.back());
  3882. MOps.pop_back();
  3883. }
  3884. }
  3885. }
  3886. }
  3887. // Check if the 'MI' that has the index OpNoForForwarding
  3888. // meets the requirement described in the ImmInstrInfo.
  3889. bool PPCInstrInfo::isUseMIElgibleForForwarding(MachineInstr &MI,
  3890. const ImmInstrInfo &III,
  3891. unsigned OpNoForForwarding
  3892. ) const {
  3893. // As the algorithm of checking for PPC::ZERO/PPC::ZERO8
  3894. // would not work pre-RA, we can only do the check post RA.
  3895. MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
  3896. if (MRI.isSSA())
  3897. return false;
  3898. // Cannot do the transform if MI isn't summing the operands.
  3899. if (!III.IsSummingOperands)
  3900. return false;
  3901. // The instruction we are trying to replace must have the ZeroIsSpecialOrig set.
  3902. if (!III.ZeroIsSpecialOrig)
  3903. return false;
  3904. // We cannot do the transform if the operand we are trying to replace
  3905. // isn't the same as the operand the instruction allows.
  3906. if (OpNoForForwarding != III.OpNoForForwarding)
  3907. return false;
  3908. // Check if the instruction we are trying to transform really has
  3909. // the special zero register as its operand.
  3910. if (MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO &&
  3911. MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO8)
  3912. return false;
  3913. // This machine instruction is convertible if it is,
  3914. // 1. summing the operands.
  3915. // 2. one of the operands is special zero register.
  3916. // 3. the operand we are trying to replace is allowed by the MI.
  3917. return true;
  3918. }
  3919. // Check if the DefMI is the add inst and set the ImmMO and RegMO
  3920. // accordingly.
  3921. bool PPCInstrInfo::isDefMIElgibleForForwarding(MachineInstr &DefMI,
  3922. const ImmInstrInfo &III,
  3923. MachineOperand *&ImmMO,
  3924. MachineOperand *&RegMO) const {
  3925. unsigned Opc = DefMI.getOpcode();
  3926. if (Opc != PPC::ADDItocL && Opc != PPC::ADDI && Opc != PPC::ADDI8)
  3927. return false;
  3928. assert(DefMI.getNumOperands() >= 3 &&
  3929. "Add inst must have at least three operands");
  3930. RegMO = &DefMI.getOperand(1);
  3931. ImmMO = &DefMI.getOperand(2);
  3932. // Before RA, ADDI first operand could be a frame index.
  3933. if (!RegMO->isReg())
  3934. return false;
  3935. // This DefMI is elgible for forwarding if it is:
  3936. // 1. add inst
  3937. // 2. one of the operands is Imm/CPI/Global.
  3938. return isAnImmediateOperand(*ImmMO);
  3939. }
  3940. bool PPCInstrInfo::isRegElgibleForForwarding(
  3941. const MachineOperand &RegMO, const MachineInstr &DefMI,
  3942. const MachineInstr &MI, bool KillDefMI,
  3943. bool &IsFwdFeederRegKilled) const {
  3944. // x = addi y, imm
  3945. // ...
  3946. // z = lfdx 0, x -> z = lfd imm(y)
  3947. // The Reg "y" can be forwarded to the MI(z) only when there is no DEF
  3948. // of "y" between the DEF of "x" and "z".
  3949. // The query is only valid post RA.
  3950. const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
  3951. if (MRI.isSSA())
  3952. return false;
  3953. Register Reg = RegMO.getReg();
  3954. // Walking the inst in reverse(MI-->DefMI) to get the last DEF of the Reg.
  3955. MachineBasicBlock::const_reverse_iterator It = MI;
  3956. MachineBasicBlock::const_reverse_iterator E = MI.getParent()->rend();
  3957. It++;
  3958. for (; It != E; ++It) {
  3959. if (It->modifiesRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
  3960. return false;
  3961. else if (It->killsRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
  3962. IsFwdFeederRegKilled = true;
  3963. // Made it to DefMI without encountering a clobber.
  3964. if ((&*It) == &DefMI)
  3965. break;
  3966. }
  3967. assert((&*It) == &DefMI && "DefMI is missing");
  3968. // If DefMI also defines the register to be forwarded, we can only forward it
  3969. // if DefMI is being erased.
  3970. if (DefMI.modifiesRegister(Reg, &getRegisterInfo()))
  3971. return KillDefMI;
  3972. return true;
  3973. }
  3974. bool PPCInstrInfo::isImmElgibleForForwarding(const MachineOperand &ImmMO,
  3975. const MachineInstr &DefMI,
  3976. const ImmInstrInfo &III,
  3977. int64_t &Imm,
  3978. int64_t BaseImm) const {
  3979. assert(isAnImmediateOperand(ImmMO) && "ImmMO is NOT an immediate");
  3980. if (DefMI.getOpcode() == PPC::ADDItocL) {
  3981. // The operand for ADDItocL is CPI, which isn't imm at compiling time,
  3982. // However, we know that, it is 16-bit width, and has the alignment of 4.
  3983. // Check if the instruction met the requirement.
  3984. if (III.ImmMustBeMultipleOf > 4 ||
  3985. III.TruncateImmTo || III.ImmWidth != 16)
  3986. return false;
  3987. // Going from XForm to DForm loads means that the displacement needs to be
  3988. // not just an immediate but also a multiple of 4, or 16 depending on the
  3989. // load. A DForm load cannot be represented if it is a multiple of say 2.
  3990. // XForm loads do not have this restriction.
  3991. if (ImmMO.isGlobal()) {
  3992. const DataLayout &DL = ImmMO.getGlobal()->getParent()->getDataLayout();
  3993. if (ImmMO.getGlobal()->getPointerAlignment(DL) < III.ImmMustBeMultipleOf)
  3994. return false;
  3995. }
  3996. return true;
  3997. }
  3998. if (ImmMO.isImm()) {
  3999. // It is Imm, we need to check if the Imm fit the range.
  4000. // Sign-extend to 64-bits.
  4001. // DefMI may be folded with another imm form instruction, the result Imm is
  4002. // the sum of Imm of DefMI and BaseImm which is from imm form instruction.
  4003. APInt ActualValue(64, ImmMO.getImm() + BaseImm, true);
  4004. if (III.SignedImm && !ActualValue.isSignedIntN(III.ImmWidth))
  4005. return false;
  4006. if (!III.SignedImm && !ActualValue.isIntN(III.ImmWidth))
  4007. return false;
  4008. Imm = SignExtend64<16>(ImmMO.getImm() + BaseImm);
  4009. if (Imm % III.ImmMustBeMultipleOf)
  4010. return false;
  4011. if (III.TruncateImmTo)
  4012. Imm &= ((1 << III.TruncateImmTo) - 1);
  4013. }
  4014. else
  4015. return false;
  4016. // This ImmMO is forwarded if it meets the requriement describle
  4017. // in ImmInstrInfo
  4018. return true;
  4019. }
  4020. bool PPCInstrInfo::simplifyToLI(MachineInstr &MI, MachineInstr &DefMI,
  4021. unsigned OpNoForForwarding,
  4022. MachineInstr **KilledDef) const {
  4023. if ((DefMI.getOpcode() != PPC::LI && DefMI.getOpcode() != PPC::LI8) ||
  4024. !DefMI.getOperand(1).isImm())
  4025. return false;
  4026. MachineFunction *MF = MI.getParent()->getParent();
  4027. MachineRegisterInfo *MRI = &MF->getRegInfo();
  4028. bool PostRA = !MRI->isSSA();
  4029. int64_t Immediate = DefMI.getOperand(1).getImm();
  4030. // Sign-extend to 64-bits.
  4031. int64_t SExtImm = SignExtend64<16>(Immediate);
  4032. bool IsForwardingOperandKilled = MI.getOperand(OpNoForForwarding).isKill();
  4033. Register ForwardingOperandReg = MI.getOperand(OpNoForForwarding).getReg();
  4034. bool ReplaceWithLI = false;
  4035. bool Is64BitLI = false;
  4036. int64_t NewImm = 0;
  4037. bool SetCR = false;
  4038. unsigned Opc = MI.getOpcode();
  4039. switch (Opc) {
  4040. default:
  4041. return false;
  4042. // FIXME: Any branches conditional on such a comparison can be made
  4043. // unconditional. At this time, this happens too infrequently to be worth
  4044. // the implementation effort, but if that ever changes, we could convert
  4045. // such a pattern here.
  4046. case PPC::CMPWI:
  4047. case PPC::CMPLWI:
  4048. case PPC::CMPDI:
  4049. case PPC::CMPLDI: {
  4050. // Doing this post-RA would require dataflow analysis to reliably find uses
  4051. // of the CR register set by the compare.
  4052. // No need to fixup killed/dead flag since this transformation is only valid
  4053. // before RA.
  4054. if (PostRA)
  4055. return false;
  4056. // If a compare-immediate is fed by an immediate and is itself an input of
  4057. // an ISEL (the most common case) into a COPY of the correct register.
  4058. bool Changed = false;
  4059. Register DefReg = MI.getOperand(0).getReg();
  4060. int64_t Comparand = MI.getOperand(2).getImm();
  4061. int64_t SExtComparand = ((uint64_t)Comparand & ~0x7FFFuLL) != 0
  4062. ? (Comparand | 0xFFFFFFFFFFFF0000)
  4063. : Comparand;
  4064. for (auto &CompareUseMI : MRI->use_instructions(DefReg)) {
  4065. unsigned UseOpc = CompareUseMI.getOpcode();
  4066. if (UseOpc != PPC::ISEL && UseOpc != PPC::ISEL8)
  4067. continue;
  4068. unsigned CRSubReg = CompareUseMI.getOperand(3).getSubReg();
  4069. Register TrueReg = CompareUseMI.getOperand(1).getReg();
  4070. Register FalseReg = CompareUseMI.getOperand(2).getReg();
  4071. unsigned RegToCopy =
  4072. selectReg(SExtImm, SExtComparand, Opc, TrueReg, FalseReg, CRSubReg);
  4073. if (RegToCopy == PPC::NoRegister)
  4074. continue;
  4075. // Can't use PPC::COPY to copy PPC::ZERO[8]. Convert it to LI[8] 0.
  4076. if (RegToCopy == PPC::ZERO || RegToCopy == PPC::ZERO8) {
  4077. CompareUseMI.setDesc(get(UseOpc == PPC::ISEL8 ? PPC::LI8 : PPC::LI));
  4078. replaceInstrOperandWithImm(CompareUseMI, 1, 0);
  4079. CompareUseMI.RemoveOperand(3);
  4080. CompareUseMI.RemoveOperand(2);
  4081. continue;
  4082. }
  4083. LLVM_DEBUG(
  4084. dbgs() << "Found LI -> CMPI -> ISEL, replacing with a copy.\n");
  4085. LLVM_DEBUG(DefMI.dump(); MI.dump(); CompareUseMI.dump());
  4086. LLVM_DEBUG(dbgs() << "Is converted to:\n");
  4087. // Convert to copy and remove unneeded operands.
  4088. CompareUseMI.setDesc(get(PPC::COPY));
  4089. CompareUseMI.RemoveOperand(3);
  4090. CompareUseMI.RemoveOperand(RegToCopy == TrueReg ? 2 : 1);
  4091. CmpIselsConverted++;
  4092. Changed = true;
  4093. LLVM_DEBUG(CompareUseMI.dump());
  4094. }
  4095. if (Changed)
  4096. return true;
  4097. // This may end up incremented multiple times since this function is called
  4098. // during a fixed-point transformation, but it is only meant to indicate the
  4099. // presence of this opportunity.
  4100. MissedConvertibleImmediateInstrs++;
  4101. return false;
  4102. }
  4103. // Immediate forms - may simply be convertable to an LI.
  4104. case PPC::ADDI:
  4105. case PPC::ADDI8: {
  4106. // Does the sum fit in a 16-bit signed field?
  4107. int64_t Addend = MI.getOperand(2).getImm();
  4108. if (isInt<16>(Addend + SExtImm)) {
  4109. ReplaceWithLI = true;
  4110. Is64BitLI = Opc == PPC::ADDI8;
  4111. NewImm = Addend + SExtImm;
  4112. break;
  4113. }
  4114. return false;
  4115. }
  4116. case PPC::SUBFIC:
  4117. case PPC::SUBFIC8: {
  4118. // Only transform this if the CARRY implicit operand is dead.
  4119. if (MI.getNumOperands() > 3 && !MI.getOperand(3).isDead())
  4120. return false;
  4121. int64_t Minuend = MI.getOperand(2).getImm();
  4122. if (isInt<16>(Minuend - SExtImm)) {
  4123. ReplaceWithLI = true;
  4124. Is64BitLI = Opc == PPC::SUBFIC8;
  4125. NewImm = Minuend - SExtImm;
  4126. break;
  4127. }
  4128. return false;
  4129. }
  4130. case PPC::RLDICL:
  4131. case PPC::RLDICL_rec:
  4132. case PPC::RLDICL_32:
  4133. case PPC::RLDICL_32_64: {
  4134. // Use APInt's rotate function.
  4135. int64_t SH = MI.getOperand(2).getImm();
  4136. int64_t MB = MI.getOperand(3).getImm();
  4137. APInt InVal((Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec) ? 64 : 32,
  4138. SExtImm, true);
  4139. InVal = InVal.rotl(SH);
  4140. uint64_t Mask = MB == 0 ? -1LLU : (1LLU << (63 - MB + 1)) - 1;
  4141. InVal &= Mask;
  4142. // Can't replace negative values with an LI as that will sign-extend
  4143. // and not clear the left bits. If we're setting the CR bit, we will use
  4144. // ANDI_rec which won't sign extend, so that's safe.
  4145. if (isUInt<15>(InVal.getSExtValue()) ||
  4146. (Opc == PPC::RLDICL_rec && isUInt<16>(InVal.getSExtValue()))) {
  4147. ReplaceWithLI = true;
  4148. Is64BitLI = Opc != PPC::RLDICL_32;
  4149. NewImm = InVal.getSExtValue();
  4150. SetCR = Opc == PPC::RLDICL_rec;
  4151. break;
  4152. }
  4153. return false;
  4154. }
  4155. case PPC::RLWINM:
  4156. case PPC::RLWINM8:
  4157. case PPC::RLWINM_rec:
  4158. case PPC::RLWINM8_rec: {
  4159. int64_t SH = MI.getOperand(2).getImm();
  4160. int64_t MB = MI.getOperand(3).getImm();
  4161. int64_t ME = MI.getOperand(4).getImm();
  4162. APInt InVal(32, SExtImm, true);
  4163. InVal = InVal.rotl(SH);
  4164. APInt Mask = APInt::getBitsSetWithWrap(32, 32 - ME - 1, 32 - MB);
  4165. InVal &= Mask;
  4166. // Can't replace negative values with an LI as that will sign-extend
  4167. // and not clear the left bits. If we're setting the CR bit, we will use
  4168. // ANDI_rec which won't sign extend, so that's safe.
  4169. bool ValueFits = isUInt<15>(InVal.getSExtValue());
  4170. ValueFits |= ((Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec) &&
  4171. isUInt<16>(InVal.getSExtValue()));
  4172. if (ValueFits) {
  4173. ReplaceWithLI = true;
  4174. Is64BitLI = Opc == PPC::RLWINM8 || Opc == PPC::RLWINM8_rec;
  4175. NewImm = InVal.getSExtValue();
  4176. SetCR = Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec;
  4177. break;
  4178. }
  4179. return false;
  4180. }
  4181. case PPC::ORI:
  4182. case PPC::ORI8:
  4183. case PPC::XORI:
  4184. case PPC::XORI8: {
  4185. int64_t LogicalImm = MI.getOperand(2).getImm();
  4186. int64_t Result = 0;
  4187. if (Opc == PPC::ORI || Opc == PPC::ORI8)
  4188. Result = LogicalImm | SExtImm;
  4189. else
  4190. Result = LogicalImm ^ SExtImm;
  4191. if (isInt<16>(Result)) {
  4192. ReplaceWithLI = true;
  4193. Is64BitLI = Opc == PPC::ORI8 || Opc == PPC::XORI8;
  4194. NewImm = Result;
  4195. break;
  4196. }
  4197. return false;
  4198. }
  4199. }
  4200. if (ReplaceWithLI) {
  4201. // We need to be careful with CR-setting instructions we're replacing.
  4202. if (SetCR) {
  4203. // We don't know anything about uses when we're out of SSA, so only
  4204. // replace if the new immediate will be reproduced.
  4205. bool ImmChanged = (SExtImm & NewImm) != NewImm;
  4206. if (PostRA && ImmChanged)
  4207. return false;
  4208. if (!PostRA) {
  4209. // If the defining load-immediate has no other uses, we can just replace
  4210. // the immediate with the new immediate.
  4211. if (MRI->hasOneUse(DefMI.getOperand(0).getReg()))
  4212. DefMI.getOperand(1).setImm(NewImm);
  4213. // If we're not using the GPR result of the CR-setting instruction, we
  4214. // just need to and with zero/non-zero depending on the new immediate.
  4215. else if (MRI->use_empty(MI.getOperand(0).getReg())) {
  4216. if (NewImm) {
  4217. assert(Immediate && "Transformation converted zero to non-zero?");
  4218. NewImm = Immediate;
  4219. }
  4220. } else if (ImmChanged)
  4221. return false;
  4222. }
  4223. }
  4224. LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
  4225. LLVM_DEBUG(MI.dump());
  4226. LLVM_DEBUG(dbgs() << "Fed by:\n");
  4227. LLVM_DEBUG(DefMI.dump());
  4228. LoadImmediateInfo LII;
  4229. LII.Imm = NewImm;
  4230. LII.Is64Bit = Is64BitLI;
  4231. LII.SetCR = SetCR;
  4232. // If we're setting the CR, the original load-immediate must be kept (as an
  4233. // operand to ANDI_rec/ANDI8_rec).
  4234. if (KilledDef && SetCR)
  4235. *KilledDef = nullptr;
  4236. replaceInstrWithLI(MI, LII);
  4237. // Fixup killed/dead flag after transformation.
  4238. // Pattern:
  4239. // ForwardingOperandReg = LI imm1
  4240. // y = op2 imm2, ForwardingOperandReg(killed)
  4241. if (IsForwardingOperandKilled)
  4242. fixupIsDeadOrKill(&DefMI, &MI, ForwardingOperandReg);
  4243. LLVM_DEBUG(dbgs() << "With:\n");
  4244. LLVM_DEBUG(MI.dump());
  4245. return true;
  4246. }
  4247. return false;
  4248. }
  4249. bool PPCInstrInfo::transformToNewImmFormFedByAdd(
  4250. MachineInstr &MI, MachineInstr &DefMI, unsigned OpNoForForwarding) const {
  4251. MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
  4252. bool PostRA = !MRI->isSSA();
  4253. // FIXME: extend this to post-ra. Need to do some change in getForwardingDefMI
  4254. // for post-ra.
  4255. if (PostRA)
  4256. return false;
  4257. // Only handle load/store.
  4258. if (!MI.mayLoadOrStore())
  4259. return false;
  4260. unsigned XFormOpcode = RI.getMappedIdxOpcForImmOpc(MI.getOpcode());
  4261. assert((XFormOpcode != PPC::INSTRUCTION_LIST_END) &&
  4262. "MI must have x-form opcode");
  4263. // get Imm Form info.
  4264. ImmInstrInfo III;
  4265. bool IsVFReg = MI.getOperand(0).isReg()
  4266. ? isVFRegister(MI.getOperand(0).getReg())
  4267. : false;
  4268. if (!instrHasImmForm(XFormOpcode, IsVFReg, III, PostRA))
  4269. return false;
  4270. if (!III.IsSummingOperands)
  4271. return false;
  4272. if (OpNoForForwarding != III.OpNoForForwarding)
  4273. return false;
  4274. MachineOperand ImmOperandMI = MI.getOperand(III.ImmOpNo);
  4275. if (!ImmOperandMI.isImm())
  4276. return false;
  4277. // Check DefMI.
  4278. MachineOperand *ImmMO = nullptr;
  4279. MachineOperand *RegMO = nullptr;
  4280. if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
  4281. return false;
  4282. assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
  4283. // Check Imm.
  4284. // Set ImmBase from imm instruction as base and get new Imm inside
  4285. // isImmElgibleForForwarding.
  4286. int64_t ImmBase = ImmOperandMI.getImm();
  4287. int64_t Imm = 0;
  4288. if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm, ImmBase))
  4289. return false;
  4290. // Get killed info in case fixup needed after transformation.
  4291. unsigned ForwardKilledOperandReg = ~0U;
  4292. if (MI.getOperand(III.OpNoForForwarding).isKill())
  4293. ForwardKilledOperandReg = MI.getOperand(III.OpNoForForwarding).getReg();
  4294. // Do the transform
  4295. LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
  4296. LLVM_DEBUG(MI.dump());
  4297. LLVM_DEBUG(dbgs() << "Fed by:\n");
  4298. LLVM_DEBUG(DefMI.dump());
  4299. MI.getOperand(III.OpNoForForwarding).setReg(RegMO->getReg());
  4300. if (RegMO->isKill()) {
  4301. MI.getOperand(III.OpNoForForwarding).setIsKill(true);
  4302. // Clear the killed flag in RegMO. Doing this here can handle some cases
  4303. // that DefMI and MI are not in same basic block.
  4304. RegMO->setIsKill(false);
  4305. }
  4306. MI.getOperand(III.ImmOpNo).setImm(Imm);
  4307. // FIXME: fix kill/dead flag if MI and DefMI are not in same basic block.
  4308. if (DefMI.getParent() == MI.getParent()) {
  4309. // Check if reg is killed between MI and DefMI.
  4310. auto IsKilledFor = [&](unsigned Reg) {
  4311. MachineBasicBlock::const_reverse_iterator It = MI;
  4312. MachineBasicBlock::const_reverse_iterator E = DefMI;
  4313. It++;
  4314. for (; It != E; ++It) {
  4315. if (It->killsRegister(Reg))
  4316. return true;
  4317. }
  4318. return false;
  4319. };
  4320. // Update kill flag
  4321. if (RegMO->isKill() || IsKilledFor(RegMO->getReg()))
  4322. fixupIsDeadOrKill(&DefMI, &MI, RegMO->getReg());
  4323. if (ForwardKilledOperandReg != ~0U)
  4324. fixupIsDeadOrKill(&DefMI, &MI, ForwardKilledOperandReg);
  4325. }
  4326. LLVM_DEBUG(dbgs() << "With:\n");
  4327. LLVM_DEBUG(MI.dump());
  4328. return true;
  4329. }
  4330. // If an X-Form instruction is fed by an add-immediate and one of its operands
  4331. // is the literal zero, attempt to forward the source of the add-immediate to
  4332. // the corresponding D-Form instruction with the displacement coming from
  4333. // the immediate being added.
  4334. bool PPCInstrInfo::transformToImmFormFedByAdd(
  4335. MachineInstr &MI, const ImmInstrInfo &III, unsigned OpNoForForwarding,
  4336. MachineInstr &DefMI, bool KillDefMI) const {
  4337. // RegMO ImmMO
  4338. // | |
  4339. // x = addi reg, imm <----- DefMI
  4340. // y = op 0 , x <----- MI
  4341. // |
  4342. // OpNoForForwarding
  4343. // Check if the MI meet the requirement described in the III.
  4344. if (!isUseMIElgibleForForwarding(MI, III, OpNoForForwarding))
  4345. return false;
  4346. // Check if the DefMI meet the requirement
  4347. // described in the III. If yes, set the ImmMO and RegMO accordingly.
  4348. MachineOperand *ImmMO = nullptr;
  4349. MachineOperand *RegMO = nullptr;
  4350. if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
  4351. return false;
  4352. assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
  4353. // As we get the Imm operand now, we need to check if the ImmMO meet
  4354. // the requirement described in the III. If yes set the Imm.
  4355. int64_t Imm = 0;
  4356. if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm))
  4357. return false;
  4358. bool IsFwdFeederRegKilled = false;
  4359. // Check if the RegMO can be forwarded to MI.
  4360. if (!isRegElgibleForForwarding(*RegMO, DefMI, MI, KillDefMI,
  4361. IsFwdFeederRegKilled))
  4362. return false;
  4363. // Get killed info in case fixup needed after transformation.
  4364. unsigned ForwardKilledOperandReg = ~0U;
  4365. MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
  4366. bool PostRA = !MRI.isSSA();
  4367. if (PostRA && MI.getOperand(OpNoForForwarding).isKill())
  4368. ForwardKilledOperandReg = MI.getOperand(OpNoForForwarding).getReg();
  4369. // We know that, the MI and DefMI both meet the pattern, and
  4370. // the Imm also meet the requirement with the new Imm-form.
  4371. // It is safe to do the transformation now.
  4372. LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
  4373. LLVM_DEBUG(MI.dump());
  4374. LLVM_DEBUG(dbgs() << "Fed by:\n");
  4375. LLVM_DEBUG(DefMI.dump());
  4376. // Update the base reg first.
  4377. MI.getOperand(III.OpNoForForwarding).ChangeToRegister(RegMO->getReg(),
  4378. false, false,
  4379. RegMO->isKill());
  4380. // Then, update the imm.
  4381. if (ImmMO->isImm()) {
  4382. // If the ImmMO is Imm, change the operand that has ZERO to that Imm
  4383. // directly.
  4384. replaceInstrOperandWithImm(MI, III.ZeroIsSpecialOrig, Imm);
  4385. }
  4386. else {
  4387. // Otherwise, it is Constant Pool Index(CPI) or Global,
  4388. // which is relocation in fact. We need to replace the special zero
  4389. // register with ImmMO.
  4390. // Before that, we need to fixup the target flags for imm.
  4391. // For some reason, we miss to set the flag for the ImmMO if it is CPI.
  4392. if (DefMI.getOpcode() == PPC::ADDItocL)
  4393. ImmMO->setTargetFlags(PPCII::MO_TOC_LO);
  4394. // MI didn't have the interface such as MI.setOperand(i) though
  4395. // it has MI.getOperand(i). To repalce the ZERO MachineOperand with
  4396. // ImmMO, we need to remove ZERO operand and all the operands behind it,
  4397. // and, add the ImmMO, then, move back all the operands behind ZERO.
  4398. SmallVector<MachineOperand, 2> MOps;
  4399. for (unsigned i = MI.getNumOperands() - 1; i >= III.ZeroIsSpecialOrig; i--) {
  4400. MOps.push_back(MI.getOperand(i));
  4401. MI.RemoveOperand(i);
  4402. }
  4403. // Remove the last MO in the list, which is ZERO operand in fact.
  4404. MOps.pop_back();
  4405. // Add the imm operand.
  4406. MI.addOperand(*ImmMO);
  4407. // Now add the rest back.
  4408. for (auto &MO : MOps)
  4409. MI.addOperand(MO);
  4410. }
  4411. // Update the opcode.
  4412. MI.setDesc(get(III.ImmOpcode));
  4413. // Fix up killed/dead flag after transformation.
  4414. // Pattern 1:
  4415. // x = ADD KilledFwdFeederReg, imm
  4416. // n = opn KilledFwdFeederReg(killed), regn
  4417. // y = XOP 0, x
  4418. // Pattern 2:
  4419. // x = ADD reg(killed), imm
  4420. // y = XOP 0, x
  4421. if (IsFwdFeederRegKilled || RegMO->isKill())
  4422. fixupIsDeadOrKill(&DefMI, &MI, RegMO->getReg());
  4423. // Pattern 3:
  4424. // ForwardKilledOperandReg = ADD reg, imm
  4425. // y = XOP 0, ForwardKilledOperandReg(killed)
  4426. if (ForwardKilledOperandReg != ~0U)
  4427. fixupIsDeadOrKill(&DefMI, &MI, ForwardKilledOperandReg);
  4428. LLVM_DEBUG(dbgs() << "With:\n");
  4429. LLVM_DEBUG(MI.dump());
  4430. return true;
  4431. }
  4432. bool PPCInstrInfo::transformToImmFormFedByLI(MachineInstr &MI,
  4433. const ImmInstrInfo &III,
  4434. unsigned ConstantOpNo,
  4435. MachineInstr &DefMI) const {
  4436. // DefMI must be LI or LI8.
  4437. if ((DefMI.getOpcode() != PPC::LI && DefMI.getOpcode() != PPC::LI8) ||
  4438. !DefMI.getOperand(1).isImm())
  4439. return false;
  4440. // Get Imm operand and Sign-extend to 64-bits.
  4441. int64_t Imm = SignExtend64<16>(DefMI.getOperand(1).getImm());
  4442. MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
  4443. bool PostRA = !MRI.isSSA();
  4444. // Exit early if we can't convert this.
  4445. if ((ConstantOpNo != III.OpNoForForwarding) && !III.IsCommutative)
  4446. return false;
  4447. if (Imm % III.ImmMustBeMultipleOf)
  4448. return false;
  4449. if (III.TruncateImmTo)
  4450. Imm &= ((1 << III.TruncateImmTo) - 1);
  4451. if (III.SignedImm) {
  4452. APInt ActualValue(64, Imm, true);
  4453. if (!ActualValue.isSignedIntN(III.ImmWidth))
  4454. return false;
  4455. } else {
  4456. uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
  4457. if ((uint64_t)Imm > UnsignedMax)
  4458. return false;
  4459. }
  4460. // If we're post-RA, the instructions don't agree on whether register zero is
  4461. // special, we can transform this as long as the register operand that will
  4462. // end up in the location where zero is special isn't R0.
  4463. if (PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
  4464. unsigned PosForOrigZero = III.ZeroIsSpecialOrig ? III.ZeroIsSpecialOrig :
  4465. III.ZeroIsSpecialNew + 1;
  4466. Register OrigZeroReg = MI.getOperand(PosForOrigZero).getReg();
  4467. Register NewZeroReg = MI.getOperand(III.ZeroIsSpecialNew).getReg();
  4468. // If R0 is in the operand where zero is special for the new instruction,
  4469. // it is unsafe to transform if the constant operand isn't that operand.
  4470. if ((NewZeroReg == PPC::R0 || NewZeroReg == PPC::X0) &&
  4471. ConstantOpNo != III.ZeroIsSpecialNew)
  4472. return false;
  4473. if ((OrigZeroReg == PPC::R0 || OrigZeroReg == PPC::X0) &&
  4474. ConstantOpNo != PosForOrigZero)
  4475. return false;
  4476. }
  4477. // Get killed info in case fixup needed after transformation.
  4478. unsigned ForwardKilledOperandReg = ~0U;
  4479. if (PostRA && MI.getOperand(ConstantOpNo).isKill())
  4480. ForwardKilledOperandReg = MI.getOperand(ConstantOpNo).getReg();
  4481. unsigned Opc = MI.getOpcode();
  4482. bool SpecialShift32 = Opc == PPC::SLW || Opc == PPC::SLW_rec ||
  4483. Opc == PPC::SRW || Opc == PPC::SRW_rec ||
  4484. Opc == PPC::SLW8 || Opc == PPC::SLW8_rec ||
  4485. Opc == PPC::SRW8 || Opc == PPC::SRW8_rec;
  4486. bool SpecialShift64 = Opc == PPC::SLD || Opc == PPC::SLD_rec ||
  4487. Opc == PPC::SRD || Opc == PPC::SRD_rec;
  4488. bool SetCR = Opc == PPC::SLW_rec || Opc == PPC::SRW_rec ||
  4489. Opc == PPC::SLD_rec || Opc == PPC::SRD_rec;
  4490. bool RightShift = Opc == PPC::SRW || Opc == PPC::SRW_rec || Opc == PPC::SRD ||
  4491. Opc == PPC::SRD_rec;
  4492. MI.setDesc(get(III.ImmOpcode));
  4493. if (ConstantOpNo == III.OpNoForForwarding) {
  4494. // Converting shifts to immediate form is a bit tricky since they may do
  4495. // one of three things:
  4496. // 1. If the shift amount is between OpSize and 2*OpSize, the result is zero
  4497. // 2. If the shift amount is zero, the result is unchanged (save for maybe
  4498. // setting CR0)
  4499. // 3. If the shift amount is in [1, OpSize), it's just a shift
  4500. if (SpecialShift32 || SpecialShift64) {
  4501. LoadImmediateInfo LII;
  4502. LII.Imm = 0;
  4503. LII.SetCR = SetCR;
  4504. LII.Is64Bit = SpecialShift64;
  4505. uint64_t ShAmt = Imm & (SpecialShift32 ? 0x1F : 0x3F);
  4506. if (Imm & (SpecialShift32 ? 0x20 : 0x40))
  4507. replaceInstrWithLI(MI, LII);
  4508. // Shifts by zero don't change the value. If we don't need to set CR0,
  4509. // just convert this to a COPY. Can't do this post-RA since we've already
  4510. // cleaned up the copies.
  4511. else if (!SetCR && ShAmt == 0 && !PostRA) {
  4512. MI.RemoveOperand(2);
  4513. MI.setDesc(get(PPC::COPY));
  4514. } else {
  4515. // The 32 bit and 64 bit instructions are quite different.
  4516. if (SpecialShift32) {
  4517. // Left shifts use (N, 0, 31-N).
  4518. // Right shifts use (32-N, N, 31) if 0 < N < 32.
  4519. // use (0, 0, 31) if N == 0.
  4520. uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 32 - ShAmt : ShAmt;
  4521. uint64_t MB = RightShift ? ShAmt : 0;
  4522. uint64_t ME = RightShift ? 31 : 31 - ShAmt;
  4523. replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH);
  4524. MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(MB)
  4525. .addImm(ME);
  4526. } else {
  4527. // Left shifts use (N, 63-N).
  4528. // Right shifts use (64-N, N) if 0 < N < 64.
  4529. // use (0, 0) if N == 0.
  4530. uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 64 - ShAmt : ShAmt;
  4531. uint64_t ME = RightShift ? ShAmt : 63 - ShAmt;
  4532. replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH);
  4533. MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(ME);
  4534. }
  4535. }
  4536. } else
  4537. replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
  4538. }
  4539. // Convert commutative instructions (switch the operands and convert the
  4540. // desired one to an immediate.
  4541. else if (III.IsCommutative) {
  4542. replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
  4543. swapMIOperands(MI, ConstantOpNo, III.OpNoForForwarding);
  4544. } else
  4545. llvm_unreachable("Should have exited early!");
  4546. // For instructions for which the constant register replaces a different
  4547. // operand than where the immediate goes, we need to swap them.
  4548. if (III.OpNoForForwarding != III.ImmOpNo)
  4549. swapMIOperands(MI, III.OpNoForForwarding, III.ImmOpNo);
  4550. // If the special R0/X0 register index are different for original instruction
  4551. // and new instruction, we need to fix up the register class in new
  4552. // instruction.
  4553. if (!PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
  4554. if (III.ZeroIsSpecialNew) {
  4555. // If operand at III.ZeroIsSpecialNew is physical reg(eg: ZERO/ZERO8), no
  4556. // need to fix up register class.
  4557. Register RegToModify = MI.getOperand(III.ZeroIsSpecialNew).getReg();
  4558. if (Register::isVirtualRegister(RegToModify)) {
  4559. const TargetRegisterClass *NewRC =
  4560. MRI.getRegClass(RegToModify)->hasSuperClassEq(&PPC::GPRCRegClass) ?
  4561. &PPC::GPRC_and_GPRC_NOR0RegClass : &PPC::G8RC_and_G8RC_NOX0RegClass;
  4562. MRI.setRegClass(RegToModify, NewRC);
  4563. }
  4564. }
  4565. }
  4566. // Fix up killed/dead flag after transformation.
  4567. // Pattern:
  4568. // ForwardKilledOperandReg = LI imm
  4569. // y = XOP reg, ForwardKilledOperandReg(killed)
  4570. if (ForwardKilledOperandReg != ~0U)
  4571. fixupIsDeadOrKill(&DefMI, &MI, ForwardKilledOperandReg);
  4572. return true;
  4573. }
  4574. const TargetRegisterClass *
  4575. PPCInstrInfo::updatedRC(const TargetRegisterClass *RC) const {
  4576. if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass)
  4577. return &PPC::VSRCRegClass;
  4578. return RC;
  4579. }
  4580. int PPCInstrInfo::getRecordFormOpcode(unsigned Opcode) {
  4581. return PPC::getRecordFormOpcode(Opcode);
  4582. }
  4583. // This function returns true if the machine instruction
  4584. // always outputs a value by sign-extending a 32 bit value,
  4585. // i.e. 0 to 31-th bits are same as 32-th bit.
  4586. static bool isSignExtendingOp(const MachineInstr &MI) {
  4587. int Opcode = MI.getOpcode();
  4588. if (Opcode == PPC::LI || Opcode == PPC::LI8 || Opcode == PPC::LIS ||
  4589. Opcode == PPC::LIS8 || Opcode == PPC::SRAW || Opcode == PPC::SRAW_rec ||
  4590. Opcode == PPC::SRAWI || Opcode == PPC::SRAWI_rec || Opcode == PPC::LWA ||
  4591. Opcode == PPC::LWAX || Opcode == PPC::LWA_32 || Opcode == PPC::LWAX_32 ||
  4592. Opcode == PPC::LHA || Opcode == PPC::LHAX || Opcode == PPC::LHA8 ||
  4593. Opcode == PPC::LHAX8 || Opcode == PPC::LBZ || Opcode == PPC::LBZX ||
  4594. Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 || Opcode == PPC::LBZU ||
  4595. Opcode == PPC::LBZUX || Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 ||
  4596. Opcode == PPC::LHZ || Opcode == PPC::LHZX || Opcode == PPC::LHZ8 ||
  4597. Opcode == PPC::LHZX8 || Opcode == PPC::LHZU || Opcode == PPC::LHZUX ||
  4598. Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8 || Opcode == PPC::EXTSB ||
  4599. Opcode == PPC::EXTSB_rec || Opcode == PPC::EXTSH ||
  4600. Opcode == PPC::EXTSH_rec || Opcode == PPC::EXTSB8 ||
  4601. Opcode == PPC::EXTSH8 || Opcode == PPC::EXTSW ||
  4602. Opcode == PPC::EXTSW_rec || Opcode == PPC::SETB || Opcode == PPC::SETB8 ||
  4603. Opcode == PPC::EXTSH8_32_64 || Opcode == PPC::EXTSW_32_64 ||
  4604. Opcode == PPC::EXTSB8_32_64)
  4605. return true;
  4606. if (Opcode == PPC::RLDICL && MI.getOperand(3).getImm() >= 33)
  4607. return true;
  4608. if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
  4609. Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec) &&
  4610. MI.getOperand(3).getImm() > 0 &&
  4611. MI.getOperand(3).getImm() <= MI.getOperand(4).getImm())
  4612. return true;
  4613. return false;
  4614. }
  4615. // This function returns true if the machine instruction
  4616. // always outputs zeros in higher 32 bits.
  4617. static bool isZeroExtendingOp(const MachineInstr &MI) {
  4618. int Opcode = MI.getOpcode();
  4619. // The 16-bit immediate is sign-extended in li/lis.
  4620. // If the most significant bit is zero, all higher bits are zero.
  4621. if (Opcode == PPC::LI || Opcode == PPC::LI8 ||
  4622. Opcode == PPC::LIS || Opcode == PPC::LIS8) {
  4623. int64_t Imm = MI.getOperand(1).getImm();
  4624. if (((uint64_t)Imm & ~0x7FFFuLL) == 0)
  4625. return true;
  4626. }
  4627. // We have some variations of rotate-and-mask instructions
  4628. // that clear higher 32-bits.
  4629. if ((Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec ||
  4630. Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec ||
  4631. Opcode == PPC::RLDICL_32_64) &&
  4632. MI.getOperand(3).getImm() >= 32)
  4633. return true;
  4634. if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) &&
  4635. MI.getOperand(3).getImm() >= 32 &&
  4636. MI.getOperand(3).getImm() <= 63 - MI.getOperand(2).getImm())
  4637. return true;
  4638. if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
  4639. Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec ||
  4640. Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
  4641. MI.getOperand(3).getImm() <= MI.getOperand(4).getImm())
  4642. return true;
  4643. // There are other instructions that clear higher 32-bits.
  4644. if (Opcode == PPC::CNTLZW || Opcode == PPC::CNTLZW_rec ||
  4645. Opcode == PPC::CNTTZW || Opcode == PPC::CNTTZW_rec ||
  4646. Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8 ||
  4647. Opcode == PPC::CNTLZD || Opcode == PPC::CNTLZD_rec ||
  4648. Opcode == PPC::CNTTZD || Opcode == PPC::CNTTZD_rec ||
  4649. Opcode == PPC::POPCNTD || Opcode == PPC::POPCNTW || Opcode == PPC::SLW ||
  4650. Opcode == PPC::SLW_rec || Opcode == PPC::SRW || Opcode == PPC::SRW_rec ||
  4651. Opcode == PPC::SLW8 || Opcode == PPC::SRW8 || Opcode == PPC::SLWI ||
  4652. Opcode == PPC::SLWI_rec || Opcode == PPC::SRWI ||
  4653. Opcode == PPC::SRWI_rec || Opcode == PPC::LWZ || Opcode == PPC::LWZX ||
  4654. Opcode == PPC::LWZU || Opcode == PPC::LWZUX || Opcode == PPC::LWBRX ||
  4655. Opcode == PPC::LHBRX || Opcode == PPC::LHZ || Opcode == PPC::LHZX ||
  4656. Opcode == PPC::LHZU || Opcode == PPC::LHZUX || Opcode == PPC::LBZ ||
  4657. Opcode == PPC::LBZX || Opcode == PPC::LBZU || Opcode == PPC::LBZUX ||
  4658. Opcode == PPC::LWZ8 || Opcode == PPC::LWZX8 || Opcode == PPC::LWZU8 ||
  4659. Opcode == PPC::LWZUX8 || Opcode == PPC::LWBRX8 || Opcode == PPC::LHBRX8 ||
  4660. Opcode == PPC::LHZ8 || Opcode == PPC::LHZX8 || Opcode == PPC::LHZU8 ||
  4661. Opcode == PPC::LHZUX8 || Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 ||
  4662. Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 ||
  4663. Opcode == PPC::ANDI_rec || Opcode == PPC::ANDIS_rec ||
  4664. Opcode == PPC::ROTRWI || Opcode == PPC::ROTRWI_rec ||
  4665. Opcode == PPC::EXTLWI || Opcode == PPC::EXTLWI_rec ||
  4666. Opcode == PPC::MFVSRWZ)
  4667. return true;
  4668. return false;
  4669. }
  4670. // This function returns true if the input MachineInstr is a TOC save
  4671. // instruction.
  4672. bool PPCInstrInfo::isTOCSaveMI(const MachineInstr &MI) const {
  4673. if (!MI.getOperand(1).isImm() || !MI.getOperand(2).isReg())
  4674. return false;
  4675. unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
  4676. unsigned StackOffset = MI.getOperand(1).getImm();
  4677. Register StackReg = MI.getOperand(2).getReg();
  4678. Register SPReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
  4679. if (StackReg == SPReg && StackOffset == TOCSaveOffset)
  4680. return true;
  4681. return false;
  4682. }
  4683. // We limit the max depth to track incoming values of PHIs or binary ops
  4684. // (e.g. AND) to avoid excessive cost.
  4685. const unsigned MAX_DEPTH = 1;
  4686. bool
  4687. PPCInstrInfo::isSignOrZeroExtended(const MachineInstr &MI, bool SignExt,
  4688. const unsigned Depth) const {
  4689. const MachineFunction *MF = MI.getParent()->getParent();
  4690. const MachineRegisterInfo *MRI = &MF->getRegInfo();
  4691. // If we know this instruction returns sign- or zero-extended result,
  4692. // return true.
  4693. if (SignExt ? isSignExtendingOp(MI):
  4694. isZeroExtendingOp(MI))
  4695. return true;
  4696. switch (MI.getOpcode()) {
  4697. case PPC::COPY: {
  4698. Register SrcReg = MI.getOperand(1).getReg();
  4699. // In both ELFv1 and v2 ABI, method parameters and the return value
  4700. // are sign- or zero-extended.
  4701. if (MF->getSubtarget<PPCSubtarget>().isSVR4ABI()) {
  4702. const PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
  4703. // We check the ZExt/SExt flags for a method parameter.
  4704. if (MI.getParent()->getBasicBlock() ==
  4705. &MF->getFunction().getEntryBlock()) {
  4706. Register VReg = MI.getOperand(0).getReg();
  4707. if (MF->getRegInfo().isLiveIn(VReg))
  4708. return SignExt ? FuncInfo->isLiveInSExt(VReg) :
  4709. FuncInfo->isLiveInZExt(VReg);
  4710. }
  4711. // For a method return value, we check the ZExt/SExt flags in attribute.
  4712. // We assume the following code sequence for method call.
  4713. // ADJCALLSTACKDOWN 32, implicit dead %r1, implicit %r1
  4714. // BL8_NOP @func,...
  4715. // ADJCALLSTACKUP 32, 0, implicit dead %r1, implicit %r1
  4716. // %5 = COPY %x3; G8RC:%5
  4717. if (SrcReg == PPC::X3) {
  4718. const MachineBasicBlock *MBB = MI.getParent();
  4719. MachineBasicBlock::const_instr_iterator II =
  4720. MachineBasicBlock::const_instr_iterator(&MI);
  4721. if (II != MBB->instr_begin() &&
  4722. (--II)->getOpcode() == PPC::ADJCALLSTACKUP) {
  4723. const MachineInstr &CallMI = *(--II);
  4724. if (CallMI.isCall() && CallMI.getOperand(0).isGlobal()) {
  4725. const Function *CalleeFn =
  4726. dyn_cast<Function>(CallMI.getOperand(0).getGlobal());
  4727. if (!CalleeFn)
  4728. return false;
  4729. const IntegerType *IntTy =
  4730. dyn_cast<IntegerType>(CalleeFn->getReturnType());
  4731. const AttributeSet &Attrs = CalleeFn->getAttributes().getRetAttrs();
  4732. if (IntTy && IntTy->getBitWidth() <= 32)
  4733. return Attrs.hasAttribute(SignExt ? Attribute::SExt :
  4734. Attribute::ZExt);
  4735. }
  4736. }
  4737. }
  4738. }
  4739. // If this is a copy from another register, we recursively check source.
  4740. if (!Register::isVirtualRegister(SrcReg))
  4741. return false;
  4742. const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
  4743. if (SrcMI != nullptr)
  4744. return isSignOrZeroExtended(*SrcMI, SignExt, Depth);
  4745. return false;
  4746. }
  4747. case PPC::ANDI_rec:
  4748. case PPC::ANDIS_rec:
  4749. case PPC::ORI:
  4750. case PPC::ORIS:
  4751. case PPC::XORI:
  4752. case PPC::XORIS:
  4753. case PPC::ANDI8_rec:
  4754. case PPC::ANDIS8_rec:
  4755. case PPC::ORI8:
  4756. case PPC::ORIS8:
  4757. case PPC::XORI8:
  4758. case PPC::XORIS8: {
  4759. // logical operation with 16-bit immediate does not change the upper bits.
  4760. // So, we track the operand register as we do for register copy.
  4761. Register SrcReg = MI.getOperand(1).getReg();
  4762. if (!Register::isVirtualRegister(SrcReg))
  4763. return false;
  4764. const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
  4765. if (SrcMI != nullptr)
  4766. return isSignOrZeroExtended(*SrcMI, SignExt, Depth);
  4767. return false;
  4768. }
  4769. // If all incoming values are sign-/zero-extended,
  4770. // the output of OR, ISEL or PHI is also sign-/zero-extended.
  4771. case PPC::OR:
  4772. case PPC::OR8:
  4773. case PPC::ISEL:
  4774. case PPC::PHI: {
  4775. if (Depth >= MAX_DEPTH)
  4776. return false;
  4777. // The input registers for PHI are operand 1, 3, ...
  4778. // The input registers for others are operand 1 and 2.
  4779. unsigned E = 3, D = 1;
  4780. if (MI.getOpcode() == PPC::PHI) {
  4781. E = MI.getNumOperands();
  4782. D = 2;
  4783. }
  4784. for (unsigned I = 1; I != E; I += D) {
  4785. if (MI.getOperand(I).isReg()) {
  4786. Register SrcReg = MI.getOperand(I).getReg();
  4787. if (!Register::isVirtualRegister(SrcReg))
  4788. return false;
  4789. const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
  4790. if (SrcMI == nullptr ||
  4791. !isSignOrZeroExtended(*SrcMI, SignExt, Depth + 1))
  4792. return false;
  4793. }
  4794. else
  4795. return false;
  4796. }
  4797. return true;
  4798. }
  4799. // If at least one of the incoming values of an AND is zero extended
  4800. // then the output is also zero-extended. If both of the incoming values
  4801. // are sign-extended then the output is also sign extended.
  4802. case PPC::AND:
  4803. case PPC::AND8: {
  4804. if (Depth >= MAX_DEPTH)
  4805. return false;
  4806. assert(MI.getOperand(1).isReg() && MI.getOperand(2).isReg());
  4807. Register SrcReg1 = MI.getOperand(1).getReg();
  4808. Register SrcReg2 = MI.getOperand(2).getReg();
  4809. if (!Register::isVirtualRegister(SrcReg1) ||
  4810. !Register::isVirtualRegister(SrcReg2))
  4811. return false;
  4812. const MachineInstr *MISrc1 = MRI->getVRegDef(SrcReg1);
  4813. const MachineInstr *MISrc2 = MRI->getVRegDef(SrcReg2);
  4814. if (!MISrc1 || !MISrc2)
  4815. return false;
  4816. if(SignExt)
  4817. return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) &&
  4818. isSignOrZeroExtended(*MISrc2, SignExt, Depth+1);
  4819. else
  4820. return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) ||
  4821. isSignOrZeroExtended(*MISrc2, SignExt, Depth+1);
  4822. }
  4823. default:
  4824. break;
  4825. }
  4826. return false;
  4827. }
  4828. bool PPCInstrInfo::isBDNZ(unsigned Opcode) const {
  4829. return (Opcode == (Subtarget.isPPC64() ? PPC::BDNZ8 : PPC::BDNZ));
  4830. }
  4831. namespace {
  4832. class PPCPipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
  4833. MachineInstr *Loop, *EndLoop, *LoopCount;
  4834. MachineFunction *MF;
  4835. const TargetInstrInfo *TII;
  4836. int64_t TripCount;
  4837. public:
  4838. PPCPipelinerLoopInfo(MachineInstr *Loop, MachineInstr *EndLoop,
  4839. MachineInstr *LoopCount)
  4840. : Loop(Loop), EndLoop(EndLoop), LoopCount(LoopCount),
  4841. MF(Loop->getParent()->getParent()),
  4842. TII(MF->getSubtarget().getInstrInfo()) {
  4843. // Inspect the Loop instruction up-front, as it may be deleted when we call
  4844. // createTripCountGreaterCondition.
  4845. if (LoopCount->getOpcode() == PPC::LI8 || LoopCount->getOpcode() == PPC::LI)
  4846. TripCount = LoopCount->getOperand(1).getImm();
  4847. else
  4848. TripCount = -1;
  4849. }
  4850. bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
  4851. // Only ignore the terminator.
  4852. return MI == EndLoop;
  4853. }
  4854. Optional<bool>
  4855. createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB,
  4856. SmallVectorImpl<MachineOperand> &Cond) override {
  4857. if (TripCount == -1) {
  4858. // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
  4859. // so we don't need to generate any thing here.
  4860. Cond.push_back(MachineOperand::CreateImm(0));
  4861. Cond.push_back(MachineOperand::CreateReg(
  4862. MF->getSubtarget<PPCSubtarget>().isPPC64() ? PPC::CTR8 : PPC::CTR,
  4863. true));
  4864. return {};
  4865. }
  4866. return TripCount > TC;
  4867. }
  4868. void setPreheader(MachineBasicBlock *NewPreheader) override {
  4869. // Do nothing. We want the LOOP setup instruction to stay in the *old*
  4870. // preheader, so we can use BDZ in the prologs to adapt the loop trip count.
  4871. }
  4872. void adjustTripCount(int TripCountAdjust) override {
  4873. // If the loop trip count is a compile-time value, then just change the
  4874. // value.
  4875. if (LoopCount->getOpcode() == PPC::LI8 ||
  4876. LoopCount->getOpcode() == PPC::LI) {
  4877. int64_t TripCount = LoopCount->getOperand(1).getImm() + TripCountAdjust;
  4878. LoopCount->getOperand(1).setImm(TripCount);
  4879. return;
  4880. }
  4881. // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
  4882. // so we don't need to generate any thing here.
  4883. }
  4884. void disposed() override {
  4885. Loop->eraseFromParent();
  4886. // Ensure the loop setup instruction is deleted too.
  4887. LoopCount->eraseFromParent();
  4888. }
  4889. };
  4890. } // namespace
  4891. std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
  4892. PPCInstrInfo::analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const {
  4893. // We really "analyze" only hardware loops right now.
  4894. MachineBasicBlock::iterator I = LoopBB->getFirstTerminator();
  4895. MachineBasicBlock *Preheader = *LoopBB->pred_begin();
  4896. if (Preheader == LoopBB)
  4897. Preheader = *std::next(LoopBB->pred_begin());
  4898. MachineFunction *MF = Preheader->getParent();
  4899. if (I != LoopBB->end() && isBDNZ(I->getOpcode())) {
  4900. SmallPtrSet<MachineBasicBlock *, 8> Visited;
  4901. if (MachineInstr *LoopInst = findLoopInstr(*Preheader, Visited)) {
  4902. Register LoopCountReg = LoopInst->getOperand(0).getReg();
  4903. MachineRegisterInfo &MRI = MF->getRegInfo();
  4904. MachineInstr *LoopCount = MRI.getUniqueVRegDef(LoopCountReg);
  4905. return std::make_unique<PPCPipelinerLoopInfo>(LoopInst, &*I, LoopCount);
  4906. }
  4907. }
  4908. return nullptr;
  4909. }
  4910. MachineInstr *PPCInstrInfo::findLoopInstr(
  4911. MachineBasicBlock &PreHeader,
  4912. SmallPtrSet<MachineBasicBlock *, 8> &Visited) const {
  4913. unsigned LOOPi = (Subtarget.isPPC64() ? PPC::MTCTR8loop : PPC::MTCTRloop);
  4914. // The loop set-up instruction should be in preheader
  4915. for (auto &I : PreHeader.instrs())
  4916. if (I.getOpcode() == LOOPi)
  4917. return &I;
  4918. return nullptr;
  4919. }
  4920. // Return true if get the base operand, byte offset of an instruction and the
  4921. // memory width. Width is the size of memory that is being loaded/stored.
  4922. bool PPCInstrInfo::getMemOperandWithOffsetWidth(
  4923. const MachineInstr &LdSt, const MachineOperand *&BaseReg, int64_t &Offset,
  4924. unsigned &Width, const TargetRegisterInfo *TRI) const {
  4925. if (!LdSt.mayLoadOrStore() || LdSt.getNumExplicitOperands() != 3)
  4926. return false;
  4927. // Handle only loads/stores with base register followed by immediate offset.
  4928. if (!LdSt.getOperand(1).isImm() ||
  4929. (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()))
  4930. return false;
  4931. if (!LdSt.getOperand(1).isImm() ||
  4932. (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()))
  4933. return false;
  4934. if (!LdSt.hasOneMemOperand())
  4935. return false;
  4936. Width = (*LdSt.memoperands_begin())->getSize();
  4937. Offset = LdSt.getOperand(1).getImm();
  4938. BaseReg = &LdSt.getOperand(2);
  4939. return true;
  4940. }
  4941. bool PPCInstrInfo::areMemAccessesTriviallyDisjoint(
  4942. const MachineInstr &MIa, const MachineInstr &MIb) const {
  4943. assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
  4944. assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
  4945. if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() ||
  4946. MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
  4947. return false;
  4948. // Retrieve the base register, offset from the base register and width. Width
  4949. // is the size of memory that is being loaded/stored (e.g. 1, 2, 4). If
  4950. // base registers are identical, and the offset of a lower memory access +
  4951. // the width doesn't overlap the offset of a higher memory access,
  4952. // then the memory accesses are different.
  4953. const TargetRegisterInfo *TRI = &getRegisterInfo();
  4954. const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
  4955. int64_t OffsetA = 0, OffsetB = 0;
  4956. unsigned int WidthA = 0, WidthB = 0;
  4957. if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, WidthA, TRI) &&
  4958. getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, WidthB, TRI)) {
  4959. if (BaseOpA->isIdenticalTo(*BaseOpB)) {
  4960. int LowOffset = std::min(OffsetA, OffsetB);
  4961. int HighOffset = std::max(OffsetA, OffsetB);
  4962. int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
  4963. if (LowOffset + LowWidth <= HighOffset)
  4964. return true;
  4965. }
  4966. }
  4967. return false;
  4968. }