ARMBaseInstrInfo.cpp 248 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052
  1. //===-- ARMBaseInstrInfo.cpp - ARM 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 Base ARM implementation of the TargetInstrInfo class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "ARMBaseInstrInfo.h"
  13. #include "ARMBaseRegisterInfo.h"
  14. #include "ARMConstantPoolValue.h"
  15. #include "ARMFeatures.h"
  16. #include "ARMHazardRecognizer.h"
  17. #include "ARMMachineFunctionInfo.h"
  18. #include "ARMSubtarget.h"
  19. #include "MCTargetDesc/ARMAddressingModes.h"
  20. #include "MCTargetDesc/ARMBaseInfo.h"
  21. #include "MVETailPredUtils.h"
  22. #include "llvm/ADT/DenseMap.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/SmallSet.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/Triple.h"
  27. #include "llvm/CodeGen/DFAPacketizer.h"
  28. #include "llvm/CodeGen/LiveVariables.h"
  29. #include "llvm/CodeGen/MachineBasicBlock.h"
  30. #include "llvm/CodeGen/MachineConstantPool.h"
  31. #include "llvm/CodeGen/MachineFrameInfo.h"
  32. #include "llvm/CodeGen/MachineFunction.h"
  33. #include "llvm/CodeGen/MachineInstr.h"
  34. #include "llvm/CodeGen/MachineInstrBuilder.h"
  35. #include "llvm/CodeGen/MachineMemOperand.h"
  36. #include "llvm/CodeGen/MachineModuleInfo.h"
  37. #include "llvm/CodeGen/MachineOperand.h"
  38. #include "llvm/CodeGen/MachinePipeliner.h"
  39. #include "llvm/CodeGen/MachineRegisterInfo.h"
  40. #include "llvm/CodeGen/MachineScheduler.h"
  41. #include "llvm/CodeGen/MultiHazardRecognizer.h"
  42. #include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
  43. #include "llvm/CodeGen/SelectionDAGNodes.h"
  44. #include "llvm/CodeGen/TargetInstrInfo.h"
  45. #include "llvm/CodeGen/TargetRegisterInfo.h"
  46. #include "llvm/CodeGen/TargetSchedule.h"
  47. #include "llvm/IR/Attributes.h"
  48. #include "llvm/IR/Constants.h"
  49. #include "llvm/IR/DebugLoc.h"
  50. #include "llvm/IR/Function.h"
  51. #include "llvm/IR/GlobalValue.h"
  52. #include "llvm/MC/MCAsmInfo.h"
  53. #include "llvm/MC/MCInstrDesc.h"
  54. #include "llvm/MC/MCInstrItineraries.h"
  55. #include "llvm/Support/BranchProbability.h"
  56. #include "llvm/Support/Casting.h"
  57. #include "llvm/Support/CommandLine.h"
  58. #include "llvm/Support/Compiler.h"
  59. #include "llvm/Support/Debug.h"
  60. #include "llvm/Support/ErrorHandling.h"
  61. #include "llvm/Support/raw_ostream.h"
  62. #include "llvm/Target/TargetMachine.h"
  63. #include <algorithm>
  64. #include <cassert>
  65. #include <cstdint>
  66. #include <iterator>
  67. #include <new>
  68. #include <utility>
  69. #include <vector>
  70. using namespace llvm;
  71. #define DEBUG_TYPE "arm-instrinfo"
  72. #define GET_INSTRINFO_CTOR_DTOR
  73. #include "ARMGenInstrInfo.inc"
  74. static cl::opt<bool>
  75. EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
  76. cl::desc("Enable ARM 2-addr to 3-addr conv"));
  77. /// ARM_MLxEntry - Record information about MLA / MLS instructions.
  78. struct ARM_MLxEntry {
  79. uint16_t MLxOpc; // MLA / MLS opcode
  80. uint16_t MulOpc; // Expanded multiplication opcode
  81. uint16_t AddSubOpc; // Expanded add / sub opcode
  82. bool NegAcc; // True if the acc is negated before the add / sub.
  83. bool HasLane; // True if instruction has an extra "lane" operand.
  84. };
  85. static const ARM_MLxEntry ARM_MLxTable[] = {
  86. // MLxOpc, MulOpc, AddSubOpc, NegAcc, HasLane
  87. // fp scalar ops
  88. { ARM::VMLAS, ARM::VMULS, ARM::VADDS, false, false },
  89. { ARM::VMLSS, ARM::VMULS, ARM::VSUBS, false, false },
  90. { ARM::VMLAD, ARM::VMULD, ARM::VADDD, false, false },
  91. { ARM::VMLSD, ARM::VMULD, ARM::VSUBD, false, false },
  92. { ARM::VNMLAS, ARM::VNMULS, ARM::VSUBS, true, false },
  93. { ARM::VNMLSS, ARM::VMULS, ARM::VSUBS, true, false },
  94. { ARM::VNMLAD, ARM::VNMULD, ARM::VSUBD, true, false },
  95. { ARM::VNMLSD, ARM::VMULD, ARM::VSUBD, true, false },
  96. // fp SIMD ops
  97. { ARM::VMLAfd, ARM::VMULfd, ARM::VADDfd, false, false },
  98. { ARM::VMLSfd, ARM::VMULfd, ARM::VSUBfd, false, false },
  99. { ARM::VMLAfq, ARM::VMULfq, ARM::VADDfq, false, false },
  100. { ARM::VMLSfq, ARM::VMULfq, ARM::VSUBfq, false, false },
  101. { ARM::VMLAslfd, ARM::VMULslfd, ARM::VADDfd, false, true },
  102. { ARM::VMLSslfd, ARM::VMULslfd, ARM::VSUBfd, false, true },
  103. { ARM::VMLAslfq, ARM::VMULslfq, ARM::VADDfq, false, true },
  104. { ARM::VMLSslfq, ARM::VMULslfq, ARM::VSUBfq, false, true },
  105. };
  106. ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI)
  107. : ARMGenInstrInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
  108. Subtarget(STI) {
  109. for (unsigned i = 0, e = std::size(ARM_MLxTable); i != e; ++i) {
  110. if (!MLxEntryMap.insert(std::make_pair(ARM_MLxTable[i].MLxOpc, i)).second)
  111. llvm_unreachable("Duplicated entries?");
  112. MLxHazardOpcodes.insert(ARM_MLxTable[i].AddSubOpc);
  113. MLxHazardOpcodes.insert(ARM_MLxTable[i].MulOpc);
  114. }
  115. }
  116. // Use a ScoreboardHazardRecognizer for prepass ARM scheduling. TargetInstrImpl
  117. // currently defaults to no prepass hazard recognizer.
  118. ScheduleHazardRecognizer *
  119. ARMBaseInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
  120. const ScheduleDAG *DAG) const {
  121. if (usePreRAHazardRecognizer()) {
  122. const InstrItineraryData *II =
  123. static_cast<const ARMSubtarget *>(STI)->getInstrItineraryData();
  124. return new ScoreboardHazardRecognizer(II, DAG, "pre-RA-sched");
  125. }
  126. return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
  127. }
  128. // Called during:
  129. // - pre-RA scheduling
  130. // - post-RA scheduling when FeatureUseMISched is set
  131. ScheduleHazardRecognizer *ARMBaseInstrInfo::CreateTargetMIHazardRecognizer(
  132. const InstrItineraryData *II, const ScheduleDAGMI *DAG) const {
  133. MultiHazardRecognizer *MHR = new MultiHazardRecognizer();
  134. // We would like to restrict this hazard recognizer to only
  135. // post-RA scheduling; we can tell that we're post-RA because we don't
  136. // track VRegLiveness.
  137. // Cortex-M7: TRM indicates that there is a single ITCM bank and two DTCM
  138. // banks banked on bit 2. Assume that TCMs are in use.
  139. if (Subtarget.isCortexM7() && !DAG->hasVRegLiveness())
  140. MHR->AddHazardRecognizer(
  141. std::make_unique<ARMBankConflictHazardRecognizer>(DAG, 0x4, true));
  142. // Not inserting ARMHazardRecognizerFPMLx because that would change
  143. // legacy behavior
  144. auto BHR = TargetInstrInfo::CreateTargetMIHazardRecognizer(II, DAG);
  145. MHR->AddHazardRecognizer(std::unique_ptr<ScheduleHazardRecognizer>(BHR));
  146. return MHR;
  147. }
  148. // Called during post-RA scheduling when FeatureUseMISched is not set
  149. ScheduleHazardRecognizer *ARMBaseInstrInfo::
  150. CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
  151. const ScheduleDAG *DAG) const {
  152. MultiHazardRecognizer *MHR = new MultiHazardRecognizer();
  153. if (Subtarget.isThumb2() || Subtarget.hasVFP2Base())
  154. MHR->AddHazardRecognizer(std::make_unique<ARMHazardRecognizerFPMLx>());
  155. auto BHR = TargetInstrInfo::CreateTargetPostRAHazardRecognizer(II, DAG);
  156. if (BHR)
  157. MHR->AddHazardRecognizer(std::unique_ptr<ScheduleHazardRecognizer>(BHR));
  158. return MHR;
  159. }
  160. MachineInstr *
  161. ARMBaseInstrInfo::convertToThreeAddress(MachineInstr &MI, LiveVariables *LV,
  162. LiveIntervals *LIS) const {
  163. // FIXME: Thumb2 support.
  164. if (!EnableARM3Addr)
  165. return nullptr;
  166. MachineFunction &MF = *MI.getParent()->getParent();
  167. uint64_t TSFlags = MI.getDesc().TSFlags;
  168. bool isPre = false;
  169. switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
  170. default: return nullptr;
  171. case ARMII::IndexModePre:
  172. isPre = true;
  173. break;
  174. case ARMII::IndexModePost:
  175. break;
  176. }
  177. // Try splitting an indexed load/store to an un-indexed one plus an add/sub
  178. // operation.
  179. unsigned MemOpc = getUnindexedOpcode(MI.getOpcode());
  180. if (MemOpc == 0)
  181. return nullptr;
  182. MachineInstr *UpdateMI = nullptr;
  183. MachineInstr *MemMI = nullptr;
  184. unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
  185. const MCInstrDesc &MCID = MI.getDesc();
  186. unsigned NumOps = MCID.getNumOperands();
  187. bool isLoad = !MI.mayStore();
  188. const MachineOperand &WB = isLoad ? MI.getOperand(1) : MI.getOperand(0);
  189. const MachineOperand &Base = MI.getOperand(2);
  190. const MachineOperand &Offset = MI.getOperand(NumOps - 3);
  191. Register WBReg = WB.getReg();
  192. Register BaseReg = Base.getReg();
  193. Register OffReg = Offset.getReg();
  194. unsigned OffImm = MI.getOperand(NumOps - 2).getImm();
  195. ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI.getOperand(NumOps - 1).getImm();
  196. switch (AddrMode) {
  197. default: llvm_unreachable("Unknown indexed op!");
  198. case ARMII::AddrMode2: {
  199. bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
  200. unsigned Amt = ARM_AM::getAM2Offset(OffImm);
  201. if (OffReg == 0) {
  202. if (ARM_AM::getSOImmVal(Amt) == -1)
  203. // Can't encode it in a so_imm operand. This transformation will
  204. // add more than 1 instruction. Abandon!
  205. return nullptr;
  206. UpdateMI = BuildMI(MF, MI.getDebugLoc(),
  207. get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
  208. .addReg(BaseReg)
  209. .addImm(Amt)
  210. .add(predOps(Pred))
  211. .add(condCodeOp());
  212. } else if (Amt != 0) {
  213. ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
  214. unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
  215. UpdateMI = BuildMI(MF, MI.getDebugLoc(),
  216. get(isSub ? ARM::SUBrsi : ARM::ADDrsi), WBReg)
  217. .addReg(BaseReg)
  218. .addReg(OffReg)
  219. .addReg(0)
  220. .addImm(SOOpc)
  221. .add(predOps(Pred))
  222. .add(condCodeOp());
  223. } else
  224. UpdateMI = BuildMI(MF, MI.getDebugLoc(),
  225. get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
  226. .addReg(BaseReg)
  227. .addReg(OffReg)
  228. .add(predOps(Pred))
  229. .add(condCodeOp());
  230. break;
  231. }
  232. case ARMII::AddrMode3 : {
  233. bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
  234. unsigned Amt = ARM_AM::getAM3Offset(OffImm);
  235. if (OffReg == 0)
  236. // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
  237. UpdateMI = BuildMI(MF, MI.getDebugLoc(),
  238. get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
  239. .addReg(BaseReg)
  240. .addImm(Amt)
  241. .add(predOps(Pred))
  242. .add(condCodeOp());
  243. else
  244. UpdateMI = BuildMI(MF, MI.getDebugLoc(),
  245. get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
  246. .addReg(BaseReg)
  247. .addReg(OffReg)
  248. .add(predOps(Pred))
  249. .add(condCodeOp());
  250. break;
  251. }
  252. }
  253. std::vector<MachineInstr*> NewMIs;
  254. if (isPre) {
  255. if (isLoad)
  256. MemMI =
  257. BuildMI(MF, MI.getDebugLoc(), get(MemOpc), MI.getOperand(0).getReg())
  258. .addReg(WBReg)
  259. .addImm(0)
  260. .addImm(Pred);
  261. else
  262. MemMI = BuildMI(MF, MI.getDebugLoc(), get(MemOpc))
  263. .addReg(MI.getOperand(1).getReg())
  264. .addReg(WBReg)
  265. .addReg(0)
  266. .addImm(0)
  267. .addImm(Pred);
  268. NewMIs.push_back(MemMI);
  269. NewMIs.push_back(UpdateMI);
  270. } else {
  271. if (isLoad)
  272. MemMI =
  273. BuildMI(MF, MI.getDebugLoc(), get(MemOpc), MI.getOperand(0).getReg())
  274. .addReg(BaseReg)
  275. .addImm(0)
  276. .addImm(Pred);
  277. else
  278. MemMI = BuildMI(MF, MI.getDebugLoc(), get(MemOpc))
  279. .addReg(MI.getOperand(1).getReg())
  280. .addReg(BaseReg)
  281. .addReg(0)
  282. .addImm(0)
  283. .addImm(Pred);
  284. if (WB.isDead())
  285. UpdateMI->getOperand(0).setIsDead();
  286. NewMIs.push_back(UpdateMI);
  287. NewMIs.push_back(MemMI);
  288. }
  289. // Transfer LiveVariables states, kill / dead info.
  290. if (LV) {
  291. for (const MachineOperand &MO : MI.operands()) {
  292. if (MO.isReg() && MO.getReg().isVirtual()) {
  293. Register Reg = MO.getReg();
  294. LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
  295. if (MO.isDef()) {
  296. MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
  297. if (MO.isDead())
  298. LV->addVirtualRegisterDead(Reg, *NewMI);
  299. }
  300. if (MO.isUse() && MO.isKill()) {
  301. for (unsigned j = 0; j < 2; ++j) {
  302. // Look at the two new MI's in reverse order.
  303. MachineInstr *NewMI = NewMIs[j];
  304. if (!NewMI->readsRegister(Reg))
  305. continue;
  306. LV->addVirtualRegisterKilled(Reg, *NewMI);
  307. if (VI.removeKill(MI))
  308. VI.Kills.push_back(NewMI);
  309. break;
  310. }
  311. }
  312. }
  313. }
  314. }
  315. MachineBasicBlock &MBB = *MI.getParent();
  316. MBB.insert(MI, NewMIs[1]);
  317. MBB.insert(MI, NewMIs[0]);
  318. return NewMIs[0];
  319. }
  320. // Branch analysis.
  321. // Cond vector output format:
  322. // 0 elements indicates an unconditional branch
  323. // 2 elements indicates a conditional branch; the elements are
  324. // the condition to check and the CPSR.
  325. // 3 elements indicates a hardware loop end; the elements
  326. // are the opcode, the operand value to test, and a dummy
  327. // operand used to pad out to 3 operands.
  328. bool ARMBaseInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
  329. MachineBasicBlock *&TBB,
  330. MachineBasicBlock *&FBB,
  331. SmallVectorImpl<MachineOperand> &Cond,
  332. bool AllowModify) const {
  333. TBB = nullptr;
  334. FBB = nullptr;
  335. MachineBasicBlock::instr_iterator I = MBB.instr_end();
  336. if (I == MBB.instr_begin())
  337. return false; // Empty blocks are easy.
  338. --I;
  339. // Walk backwards from the end of the basic block until the branch is
  340. // analyzed or we give up.
  341. while (isPredicated(*I) || I->isTerminator() || I->isDebugValue()) {
  342. // Flag to be raised on unanalyzeable instructions. This is useful in cases
  343. // where we want to clean up on the end of the basic block before we bail
  344. // out.
  345. bool CantAnalyze = false;
  346. // Skip over DEBUG values, predicated nonterminators and speculation
  347. // barrier terminators.
  348. while (I->isDebugInstr() || !I->isTerminator() ||
  349. isSpeculationBarrierEndBBOpcode(I->getOpcode()) ||
  350. I->getOpcode() == ARM::t2DoLoopStartTP){
  351. if (I == MBB.instr_begin())
  352. return false;
  353. --I;
  354. }
  355. if (isIndirectBranchOpcode(I->getOpcode()) ||
  356. isJumpTableBranchOpcode(I->getOpcode())) {
  357. // Indirect branches and jump tables can't be analyzed, but we still want
  358. // to clean up any instructions at the tail of the basic block.
  359. CantAnalyze = true;
  360. } else if (isUncondBranchOpcode(I->getOpcode())) {
  361. TBB = I->getOperand(0).getMBB();
  362. } else if (isCondBranchOpcode(I->getOpcode())) {
  363. // Bail out if we encounter multiple conditional branches.
  364. if (!Cond.empty())
  365. return true;
  366. assert(!FBB && "FBB should have been null.");
  367. FBB = TBB;
  368. TBB = I->getOperand(0).getMBB();
  369. Cond.push_back(I->getOperand(1));
  370. Cond.push_back(I->getOperand(2));
  371. } else if (I->isReturn()) {
  372. // Returns can't be analyzed, but we should run cleanup.
  373. CantAnalyze = true;
  374. } else if (I->getOpcode() == ARM::t2LoopEnd &&
  375. MBB.getParent()
  376. ->getSubtarget<ARMSubtarget>()
  377. .enableMachinePipeliner()) {
  378. if (!Cond.empty())
  379. return true;
  380. FBB = TBB;
  381. TBB = I->getOperand(1).getMBB();
  382. Cond.push_back(MachineOperand::CreateImm(I->getOpcode()));
  383. Cond.push_back(I->getOperand(0));
  384. Cond.push_back(MachineOperand::CreateImm(0));
  385. } else {
  386. // We encountered other unrecognized terminator. Bail out immediately.
  387. return true;
  388. }
  389. // Cleanup code - to be run for unpredicated unconditional branches and
  390. // returns.
  391. if (!isPredicated(*I) &&
  392. (isUncondBranchOpcode(I->getOpcode()) ||
  393. isIndirectBranchOpcode(I->getOpcode()) ||
  394. isJumpTableBranchOpcode(I->getOpcode()) ||
  395. I->isReturn())) {
  396. // Forget any previous condition branch information - it no longer applies.
  397. Cond.clear();
  398. FBB = nullptr;
  399. // If we can modify the function, delete everything below this
  400. // unconditional branch.
  401. if (AllowModify) {
  402. MachineBasicBlock::iterator DI = std::next(I);
  403. while (DI != MBB.instr_end()) {
  404. MachineInstr &InstToDelete = *DI;
  405. ++DI;
  406. // Speculation barriers must not be deleted.
  407. if (isSpeculationBarrierEndBBOpcode(InstToDelete.getOpcode()))
  408. continue;
  409. InstToDelete.eraseFromParent();
  410. }
  411. }
  412. }
  413. if (CantAnalyze) {
  414. // We may not be able to analyze the block, but we could still have
  415. // an unconditional branch as the last instruction in the block, which
  416. // just branches to layout successor. If this is the case, then just
  417. // remove it if we're allowed to make modifications.
  418. if (AllowModify && !isPredicated(MBB.back()) &&
  419. isUncondBranchOpcode(MBB.back().getOpcode()) &&
  420. TBB && MBB.isLayoutSuccessor(TBB))
  421. removeBranch(MBB);
  422. return true;
  423. }
  424. if (I == MBB.instr_begin())
  425. return false;
  426. --I;
  427. }
  428. // We made it past the terminators without bailing out - we must have
  429. // analyzed this branch successfully.
  430. return false;
  431. }
  432. unsigned ARMBaseInstrInfo::removeBranch(MachineBasicBlock &MBB,
  433. int *BytesRemoved) const {
  434. assert(!BytesRemoved && "code size not handled");
  435. MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
  436. if (I == MBB.end())
  437. return 0;
  438. if (!isUncondBranchOpcode(I->getOpcode()) &&
  439. !isCondBranchOpcode(I->getOpcode()) && I->getOpcode() != ARM::t2LoopEnd)
  440. return 0;
  441. // Remove the branch.
  442. I->eraseFromParent();
  443. I = MBB.end();
  444. if (I == MBB.begin()) return 1;
  445. --I;
  446. if (!isCondBranchOpcode(I->getOpcode()) && I->getOpcode() != ARM::t2LoopEnd)
  447. return 1;
  448. // Remove the branch.
  449. I->eraseFromParent();
  450. return 2;
  451. }
  452. unsigned ARMBaseInstrInfo::insertBranch(MachineBasicBlock &MBB,
  453. MachineBasicBlock *TBB,
  454. MachineBasicBlock *FBB,
  455. ArrayRef<MachineOperand> Cond,
  456. const DebugLoc &DL,
  457. int *BytesAdded) const {
  458. assert(!BytesAdded && "code size not handled");
  459. ARMFunctionInfo *AFI = MBB.getParent()->getInfo<ARMFunctionInfo>();
  460. int BOpc = !AFI->isThumbFunction()
  461. ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB);
  462. int BccOpc = !AFI->isThumbFunction()
  463. ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc);
  464. bool isThumb = AFI->isThumbFunction() || AFI->isThumb2Function();
  465. // Shouldn't be a fall through.
  466. assert(TBB && "insertBranch must not be told to insert a fallthrough");
  467. assert((Cond.size() == 2 || Cond.size() == 0 || Cond.size() == 3) &&
  468. "ARM branch conditions have two or three components!");
  469. // For conditional branches, we use addOperand to preserve CPSR flags.
  470. if (!FBB) {
  471. if (Cond.empty()) { // Unconditional branch?
  472. if (isThumb)
  473. BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB).add(predOps(ARMCC::AL));
  474. else
  475. BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
  476. } else if (Cond.size() == 2) {
  477. BuildMI(&MBB, DL, get(BccOpc))
  478. .addMBB(TBB)
  479. .addImm(Cond[0].getImm())
  480. .add(Cond[1]);
  481. } else
  482. BuildMI(&MBB, DL, get(Cond[0].getImm())).add(Cond[1]).addMBB(TBB);
  483. return 1;
  484. }
  485. // Two-way conditional branch.
  486. if (Cond.size() == 2)
  487. BuildMI(&MBB, DL, get(BccOpc))
  488. .addMBB(TBB)
  489. .addImm(Cond[0].getImm())
  490. .add(Cond[1]);
  491. else if (Cond.size() == 3)
  492. BuildMI(&MBB, DL, get(Cond[0].getImm())).add(Cond[1]).addMBB(TBB);
  493. if (isThumb)
  494. BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB).add(predOps(ARMCC::AL));
  495. else
  496. BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
  497. return 2;
  498. }
  499. bool ARMBaseInstrInfo::
  500. reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
  501. if (Cond.size() == 2) {
  502. ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
  503. Cond[0].setImm(ARMCC::getOppositeCondition(CC));
  504. return false;
  505. }
  506. return true;
  507. }
  508. bool ARMBaseInstrInfo::isPredicated(const MachineInstr &MI) const {
  509. if (MI.isBundle()) {
  510. MachineBasicBlock::const_instr_iterator I = MI.getIterator();
  511. MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
  512. while (++I != E && I->isInsideBundle()) {
  513. int PIdx = I->findFirstPredOperandIdx();
  514. if (PIdx != -1 && I->getOperand(PIdx).getImm() != ARMCC::AL)
  515. return true;
  516. }
  517. return false;
  518. }
  519. int PIdx = MI.findFirstPredOperandIdx();
  520. return PIdx != -1 && MI.getOperand(PIdx).getImm() != ARMCC::AL;
  521. }
  522. std::string ARMBaseInstrInfo::createMIROperandComment(
  523. const MachineInstr &MI, const MachineOperand &Op, unsigned OpIdx,
  524. const TargetRegisterInfo *TRI) const {
  525. // First, let's see if there is a generic comment for this operand
  526. std::string GenericComment =
  527. TargetInstrInfo::createMIROperandComment(MI, Op, OpIdx, TRI);
  528. if (!GenericComment.empty())
  529. return GenericComment;
  530. // If not, check if we have an immediate operand.
  531. if (!Op.isImm())
  532. return std::string();
  533. // And print its corresponding condition code if the immediate is a
  534. // predicate.
  535. int FirstPredOp = MI.findFirstPredOperandIdx();
  536. if (FirstPredOp != (int) OpIdx)
  537. return std::string();
  538. std::string CC = "CC::";
  539. CC += ARMCondCodeToString((ARMCC::CondCodes)Op.getImm());
  540. return CC;
  541. }
  542. bool ARMBaseInstrInfo::PredicateInstruction(
  543. MachineInstr &MI, ArrayRef<MachineOperand> Pred) const {
  544. unsigned Opc = MI.getOpcode();
  545. if (isUncondBranchOpcode(Opc)) {
  546. MI.setDesc(get(getMatchingCondBranchOpcode(Opc)));
  547. MachineInstrBuilder(*MI.getParent()->getParent(), MI)
  548. .addImm(Pred[0].getImm())
  549. .addReg(Pred[1].getReg());
  550. return true;
  551. }
  552. int PIdx = MI.findFirstPredOperandIdx();
  553. if (PIdx != -1) {
  554. MachineOperand &PMO = MI.getOperand(PIdx);
  555. PMO.setImm(Pred[0].getImm());
  556. MI.getOperand(PIdx+1).setReg(Pred[1].getReg());
  557. // Thumb 1 arithmetic instructions do not set CPSR when executed inside an
  558. // IT block. This affects how they are printed.
  559. const MCInstrDesc &MCID = MI.getDesc();
  560. if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
  561. assert(MCID.operands()[1].isOptionalDef() &&
  562. "CPSR def isn't expected operand");
  563. assert((MI.getOperand(1).isDead() ||
  564. MI.getOperand(1).getReg() != ARM::CPSR) &&
  565. "if conversion tried to stop defining used CPSR");
  566. MI.getOperand(1).setReg(ARM::NoRegister);
  567. }
  568. return true;
  569. }
  570. return false;
  571. }
  572. bool ARMBaseInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
  573. ArrayRef<MachineOperand> Pred2) const {
  574. if (Pred1.size() > 2 || Pred2.size() > 2)
  575. return false;
  576. ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
  577. ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
  578. if (CC1 == CC2)
  579. return true;
  580. switch (CC1) {
  581. default:
  582. return false;
  583. case ARMCC::AL:
  584. return true;
  585. case ARMCC::HS:
  586. return CC2 == ARMCC::HI;
  587. case ARMCC::LS:
  588. return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
  589. case ARMCC::GE:
  590. return CC2 == ARMCC::GT;
  591. case ARMCC::LE:
  592. return CC2 == ARMCC::LT;
  593. }
  594. }
  595. bool ARMBaseInstrInfo::ClobbersPredicate(MachineInstr &MI,
  596. std::vector<MachineOperand> &Pred,
  597. bool SkipDead) const {
  598. bool Found = false;
  599. for (const MachineOperand &MO : MI.operands()) {
  600. bool ClobbersCPSR = MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR);
  601. bool IsCPSR = MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR;
  602. if (ClobbersCPSR || IsCPSR) {
  603. // Filter out T1 instructions that have a dead CPSR,
  604. // allowing IT blocks to be generated containing T1 instructions
  605. const MCInstrDesc &MCID = MI.getDesc();
  606. if (MCID.TSFlags & ARMII::ThumbArithFlagSetting && MO.isDead() &&
  607. SkipDead)
  608. continue;
  609. Pred.push_back(MO);
  610. Found = true;
  611. }
  612. }
  613. return Found;
  614. }
  615. bool ARMBaseInstrInfo::isCPSRDefined(const MachineInstr &MI) {
  616. for (const auto &MO : MI.operands())
  617. if (MO.isReg() && MO.getReg() == ARM::CPSR && MO.isDef() && !MO.isDead())
  618. return true;
  619. return false;
  620. }
  621. static bool isEligibleForITBlock(const MachineInstr *MI) {
  622. switch (MI->getOpcode()) {
  623. default: return true;
  624. case ARM::tADC: // ADC (register) T1
  625. case ARM::tADDi3: // ADD (immediate) T1
  626. case ARM::tADDi8: // ADD (immediate) T2
  627. case ARM::tADDrr: // ADD (register) T1
  628. case ARM::tAND: // AND (register) T1
  629. case ARM::tASRri: // ASR (immediate) T1
  630. case ARM::tASRrr: // ASR (register) T1
  631. case ARM::tBIC: // BIC (register) T1
  632. case ARM::tEOR: // EOR (register) T1
  633. case ARM::tLSLri: // LSL (immediate) T1
  634. case ARM::tLSLrr: // LSL (register) T1
  635. case ARM::tLSRri: // LSR (immediate) T1
  636. case ARM::tLSRrr: // LSR (register) T1
  637. case ARM::tMUL: // MUL T1
  638. case ARM::tMVN: // MVN (register) T1
  639. case ARM::tORR: // ORR (register) T1
  640. case ARM::tROR: // ROR (register) T1
  641. case ARM::tRSB: // RSB (immediate) T1
  642. case ARM::tSBC: // SBC (register) T1
  643. case ARM::tSUBi3: // SUB (immediate) T1
  644. case ARM::tSUBi8: // SUB (immediate) T2
  645. case ARM::tSUBrr: // SUB (register) T1
  646. return !ARMBaseInstrInfo::isCPSRDefined(*MI);
  647. }
  648. }
  649. /// isPredicable - Return true if the specified instruction can be predicated.
  650. /// By default, this returns true for every instruction with a
  651. /// PredicateOperand.
  652. bool ARMBaseInstrInfo::isPredicable(const MachineInstr &MI) const {
  653. if (!MI.isPredicable())
  654. return false;
  655. if (MI.isBundle())
  656. return false;
  657. if (!isEligibleForITBlock(&MI))
  658. return false;
  659. const MachineFunction *MF = MI.getParent()->getParent();
  660. const ARMFunctionInfo *AFI =
  661. MF->getInfo<ARMFunctionInfo>();
  662. // Neon instructions in Thumb2 IT blocks are deprecated, see ARMARM.
  663. // In their ARM encoding, they can't be encoded in a conditional form.
  664. if ((MI.getDesc().TSFlags & ARMII::DomainMask) == ARMII::DomainNEON)
  665. return false;
  666. // Make indirect control flow changes unpredicable when SLS mitigation is
  667. // enabled.
  668. const ARMSubtarget &ST = MF->getSubtarget<ARMSubtarget>();
  669. if (ST.hardenSlsRetBr() && isIndirectControlFlowNotComingBack(MI))
  670. return false;
  671. if (ST.hardenSlsBlr() && isIndirectCall(MI))
  672. return false;
  673. if (AFI->isThumb2Function()) {
  674. if (getSubtarget().restrictIT())
  675. return isV8EligibleForIT(&MI);
  676. }
  677. return true;
  678. }
  679. namespace llvm {
  680. template <> bool IsCPSRDead<MachineInstr>(const MachineInstr *MI) {
  681. for (const MachineOperand &MO : MI->operands()) {
  682. if (!MO.isReg() || MO.isUndef() || MO.isUse())
  683. continue;
  684. if (MO.getReg() != ARM::CPSR)
  685. continue;
  686. if (!MO.isDead())
  687. return false;
  688. }
  689. // all definitions of CPSR are dead
  690. return true;
  691. }
  692. } // end namespace llvm
  693. /// GetInstSize - Return the size of the specified MachineInstr.
  694. ///
  695. unsigned ARMBaseInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
  696. const MachineBasicBlock &MBB = *MI.getParent();
  697. const MachineFunction *MF = MBB.getParent();
  698. const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
  699. const MCInstrDesc &MCID = MI.getDesc();
  700. switch (MI.getOpcode()) {
  701. default:
  702. // Return the size specified in .td file. If there's none, return 0, as we
  703. // can't define a default size (Thumb1 instructions are 2 bytes, Thumb2
  704. // instructions are 2-4 bytes, and ARM instructions are 4 bytes), in
  705. // contrast to AArch64 instructions which have a default size of 4 bytes for
  706. // example.
  707. return MCID.getSize();
  708. case TargetOpcode::BUNDLE:
  709. return getInstBundleLength(MI);
  710. case ARM::CONSTPOOL_ENTRY:
  711. case ARM::JUMPTABLE_INSTS:
  712. case ARM::JUMPTABLE_ADDRS:
  713. case ARM::JUMPTABLE_TBB:
  714. case ARM::JUMPTABLE_TBH:
  715. // If this machine instr is a constant pool entry, its size is recorded as
  716. // operand #2.
  717. return MI.getOperand(2).getImm();
  718. case ARM::SPACE:
  719. return MI.getOperand(1).getImm();
  720. case ARM::INLINEASM:
  721. case ARM::INLINEASM_BR: {
  722. // If this machine instr is an inline asm, measure it.
  723. unsigned Size = getInlineAsmLength(MI.getOperand(0).getSymbolName(), *MAI);
  724. if (!MF->getInfo<ARMFunctionInfo>()->isThumbFunction())
  725. Size = alignTo(Size, 4);
  726. return Size;
  727. }
  728. }
  729. }
  730. unsigned ARMBaseInstrInfo::getInstBundleLength(const MachineInstr &MI) const {
  731. unsigned Size = 0;
  732. MachineBasicBlock::const_instr_iterator I = MI.getIterator();
  733. MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
  734. while (++I != E && I->isInsideBundle()) {
  735. assert(!I->isBundle() && "No nested bundle!");
  736. Size += getInstSizeInBytes(*I);
  737. }
  738. return Size;
  739. }
  740. void ARMBaseInstrInfo::copyFromCPSR(MachineBasicBlock &MBB,
  741. MachineBasicBlock::iterator I,
  742. unsigned DestReg, bool KillSrc,
  743. const ARMSubtarget &Subtarget) const {
  744. unsigned Opc = Subtarget.isThumb()
  745. ? (Subtarget.isMClass() ? ARM::t2MRS_M : ARM::t2MRS_AR)
  746. : ARM::MRS;
  747. MachineInstrBuilder MIB =
  748. BuildMI(MBB, I, I->getDebugLoc(), get(Opc), DestReg);
  749. // There is only 1 A/R class MRS instruction, and it always refers to
  750. // APSR. However, there are lots of other possibilities on M-class cores.
  751. if (Subtarget.isMClass())
  752. MIB.addImm(0x800);
  753. MIB.add(predOps(ARMCC::AL))
  754. .addReg(ARM::CPSR, RegState::Implicit | getKillRegState(KillSrc));
  755. }
  756. void ARMBaseInstrInfo::copyToCPSR(MachineBasicBlock &MBB,
  757. MachineBasicBlock::iterator I,
  758. unsigned SrcReg, bool KillSrc,
  759. const ARMSubtarget &Subtarget) const {
  760. unsigned Opc = Subtarget.isThumb()
  761. ? (Subtarget.isMClass() ? ARM::t2MSR_M : ARM::t2MSR_AR)
  762. : ARM::MSR;
  763. MachineInstrBuilder MIB = BuildMI(MBB, I, I->getDebugLoc(), get(Opc));
  764. if (Subtarget.isMClass())
  765. MIB.addImm(0x800);
  766. else
  767. MIB.addImm(8);
  768. MIB.addReg(SrcReg, getKillRegState(KillSrc))
  769. .add(predOps(ARMCC::AL))
  770. .addReg(ARM::CPSR, RegState::Implicit | RegState::Define);
  771. }
  772. void llvm::addUnpredicatedMveVpredNOp(MachineInstrBuilder &MIB) {
  773. MIB.addImm(ARMVCC::None);
  774. MIB.addReg(0);
  775. MIB.addReg(0); // tp_reg
  776. }
  777. void llvm::addUnpredicatedMveVpredROp(MachineInstrBuilder &MIB,
  778. Register DestReg) {
  779. addUnpredicatedMveVpredNOp(MIB);
  780. MIB.addReg(DestReg, RegState::Undef);
  781. }
  782. void llvm::addPredicatedMveVpredNOp(MachineInstrBuilder &MIB, unsigned Cond) {
  783. MIB.addImm(Cond);
  784. MIB.addReg(ARM::VPR, RegState::Implicit);
  785. MIB.addReg(0); // tp_reg
  786. }
  787. void llvm::addPredicatedMveVpredROp(MachineInstrBuilder &MIB,
  788. unsigned Cond, unsigned Inactive) {
  789. addPredicatedMveVpredNOp(MIB, Cond);
  790. MIB.addReg(Inactive);
  791. }
  792. void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
  793. MachineBasicBlock::iterator I,
  794. const DebugLoc &DL, MCRegister DestReg,
  795. MCRegister SrcReg, bool KillSrc) const {
  796. bool GPRDest = ARM::GPRRegClass.contains(DestReg);
  797. bool GPRSrc = ARM::GPRRegClass.contains(SrcReg);
  798. if (GPRDest && GPRSrc) {
  799. BuildMI(MBB, I, DL, get(ARM::MOVr), DestReg)
  800. .addReg(SrcReg, getKillRegState(KillSrc))
  801. .add(predOps(ARMCC::AL))
  802. .add(condCodeOp());
  803. return;
  804. }
  805. bool SPRDest = ARM::SPRRegClass.contains(DestReg);
  806. bool SPRSrc = ARM::SPRRegClass.contains(SrcReg);
  807. unsigned Opc = 0;
  808. if (SPRDest && SPRSrc)
  809. Opc = ARM::VMOVS;
  810. else if (GPRDest && SPRSrc)
  811. Opc = ARM::VMOVRS;
  812. else if (SPRDest && GPRSrc)
  813. Opc = ARM::VMOVSR;
  814. else if (ARM::DPRRegClass.contains(DestReg, SrcReg) && Subtarget.hasFP64())
  815. Opc = ARM::VMOVD;
  816. else if (ARM::QPRRegClass.contains(DestReg, SrcReg))
  817. Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MQPRCopy;
  818. if (Opc) {
  819. MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg);
  820. MIB.addReg(SrcReg, getKillRegState(KillSrc));
  821. if (Opc == ARM::VORRq || Opc == ARM::MVE_VORR)
  822. MIB.addReg(SrcReg, getKillRegState(KillSrc));
  823. if (Opc == ARM::MVE_VORR)
  824. addUnpredicatedMveVpredROp(MIB, DestReg);
  825. else if (Opc != ARM::MQPRCopy)
  826. MIB.add(predOps(ARMCC::AL));
  827. return;
  828. }
  829. // Handle register classes that require multiple instructions.
  830. unsigned BeginIdx = 0;
  831. unsigned SubRegs = 0;
  832. int Spacing = 1;
  833. // Use VORRq when possible.
  834. if (ARM::QQPRRegClass.contains(DestReg, SrcReg)) {
  835. Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR;
  836. BeginIdx = ARM::qsub_0;
  837. SubRegs = 2;
  838. } else if (ARM::QQQQPRRegClass.contains(DestReg, SrcReg)) {
  839. Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR;
  840. BeginIdx = ARM::qsub_0;
  841. SubRegs = 4;
  842. // Fall back to VMOVD.
  843. } else if (ARM::DPairRegClass.contains(DestReg, SrcReg)) {
  844. Opc = ARM::VMOVD;
  845. BeginIdx = ARM::dsub_0;
  846. SubRegs = 2;
  847. } else if (ARM::DTripleRegClass.contains(DestReg, SrcReg)) {
  848. Opc = ARM::VMOVD;
  849. BeginIdx = ARM::dsub_0;
  850. SubRegs = 3;
  851. } else if (ARM::DQuadRegClass.contains(DestReg, SrcReg)) {
  852. Opc = ARM::VMOVD;
  853. BeginIdx = ARM::dsub_0;
  854. SubRegs = 4;
  855. } else if (ARM::GPRPairRegClass.contains(DestReg, SrcReg)) {
  856. Opc = Subtarget.isThumb2() ? ARM::tMOVr : ARM::MOVr;
  857. BeginIdx = ARM::gsub_0;
  858. SubRegs = 2;
  859. } else if (ARM::DPairSpcRegClass.contains(DestReg, SrcReg)) {
  860. Opc = ARM::VMOVD;
  861. BeginIdx = ARM::dsub_0;
  862. SubRegs = 2;
  863. Spacing = 2;
  864. } else if (ARM::DTripleSpcRegClass.contains(DestReg, SrcReg)) {
  865. Opc = ARM::VMOVD;
  866. BeginIdx = ARM::dsub_0;
  867. SubRegs = 3;
  868. Spacing = 2;
  869. } else if (ARM::DQuadSpcRegClass.contains(DestReg, SrcReg)) {
  870. Opc = ARM::VMOVD;
  871. BeginIdx = ARM::dsub_0;
  872. SubRegs = 4;
  873. Spacing = 2;
  874. } else if (ARM::DPRRegClass.contains(DestReg, SrcReg) &&
  875. !Subtarget.hasFP64()) {
  876. Opc = ARM::VMOVS;
  877. BeginIdx = ARM::ssub_0;
  878. SubRegs = 2;
  879. } else if (SrcReg == ARM::CPSR) {
  880. copyFromCPSR(MBB, I, DestReg, KillSrc, Subtarget);
  881. return;
  882. } else if (DestReg == ARM::CPSR) {
  883. copyToCPSR(MBB, I, SrcReg, KillSrc, Subtarget);
  884. return;
  885. } else if (DestReg == ARM::VPR) {
  886. assert(ARM::GPRRegClass.contains(SrcReg));
  887. BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMSR_P0), DestReg)
  888. .addReg(SrcReg, getKillRegState(KillSrc))
  889. .add(predOps(ARMCC::AL));
  890. return;
  891. } else if (SrcReg == ARM::VPR) {
  892. assert(ARM::GPRRegClass.contains(DestReg));
  893. BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMRS_P0), DestReg)
  894. .addReg(SrcReg, getKillRegState(KillSrc))
  895. .add(predOps(ARMCC::AL));
  896. return;
  897. } else if (DestReg == ARM::FPSCR_NZCV) {
  898. assert(ARM::GPRRegClass.contains(SrcReg));
  899. BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMSR_FPSCR_NZCVQC), DestReg)
  900. .addReg(SrcReg, getKillRegState(KillSrc))
  901. .add(predOps(ARMCC::AL));
  902. return;
  903. } else if (SrcReg == ARM::FPSCR_NZCV) {
  904. assert(ARM::GPRRegClass.contains(DestReg));
  905. BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMRS_FPSCR_NZCVQC), DestReg)
  906. .addReg(SrcReg, getKillRegState(KillSrc))
  907. .add(predOps(ARMCC::AL));
  908. return;
  909. }
  910. assert(Opc && "Impossible reg-to-reg copy");
  911. const TargetRegisterInfo *TRI = &getRegisterInfo();
  912. MachineInstrBuilder Mov;
  913. // Copy register tuples backward when the first Dest reg overlaps with SrcReg.
  914. if (TRI->regsOverlap(SrcReg, TRI->getSubReg(DestReg, BeginIdx))) {
  915. BeginIdx = BeginIdx + ((SubRegs - 1) * Spacing);
  916. Spacing = -Spacing;
  917. }
  918. #ifndef NDEBUG
  919. SmallSet<unsigned, 4> DstRegs;
  920. #endif
  921. for (unsigned i = 0; i != SubRegs; ++i) {
  922. Register Dst = TRI->getSubReg(DestReg, BeginIdx + i * Spacing);
  923. Register Src = TRI->getSubReg(SrcReg, BeginIdx + i * Spacing);
  924. assert(Dst && Src && "Bad sub-register");
  925. #ifndef NDEBUG
  926. assert(!DstRegs.count(Src) && "destructive vector copy");
  927. DstRegs.insert(Dst);
  928. #endif
  929. Mov = BuildMI(MBB, I, I->getDebugLoc(), get(Opc), Dst).addReg(Src);
  930. // VORR (NEON or MVE) takes two source operands.
  931. if (Opc == ARM::VORRq || Opc == ARM::MVE_VORR) {
  932. Mov.addReg(Src);
  933. }
  934. // MVE VORR takes predicate operands in place of an ordinary condition.
  935. if (Opc == ARM::MVE_VORR)
  936. addUnpredicatedMveVpredROp(Mov, Dst);
  937. else
  938. Mov = Mov.add(predOps(ARMCC::AL));
  939. // MOVr can set CC.
  940. if (Opc == ARM::MOVr)
  941. Mov = Mov.add(condCodeOp());
  942. }
  943. // Add implicit super-register defs and kills to the last instruction.
  944. Mov->addRegisterDefined(DestReg, TRI);
  945. if (KillSrc)
  946. Mov->addRegisterKilled(SrcReg, TRI);
  947. }
  948. std::optional<DestSourcePair>
  949. ARMBaseInstrInfo::isCopyInstrImpl(const MachineInstr &MI) const {
  950. // VMOVRRD is also a copy instruction but it requires
  951. // special way of handling. It is more complex copy version
  952. // and since that we are not considering it. For recognition
  953. // of such instruction isExtractSubregLike MI interface fuction
  954. // could be used.
  955. // VORRq is considered as a move only if two inputs are
  956. // the same register.
  957. if (!MI.isMoveReg() ||
  958. (MI.getOpcode() == ARM::VORRq &&
  959. MI.getOperand(1).getReg() != MI.getOperand(2).getReg()))
  960. return std::nullopt;
  961. return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
  962. }
  963. std::optional<ParamLoadedValue>
  964. ARMBaseInstrInfo::describeLoadedValue(const MachineInstr &MI,
  965. Register Reg) const {
  966. if (auto DstSrcPair = isCopyInstrImpl(MI)) {
  967. Register DstReg = DstSrcPair->Destination->getReg();
  968. // TODO: We don't handle cases where the forwarding reg is narrower/wider
  969. // than the copy registers. Consider for example:
  970. //
  971. // s16 = VMOVS s0
  972. // s17 = VMOVS s1
  973. // call @callee(d0)
  974. //
  975. // We'd like to describe the call site value of d0 as d8, but this requires
  976. // gathering and merging the descriptions for the two VMOVS instructions.
  977. //
  978. // We also don't handle the reverse situation, where the forwarding reg is
  979. // narrower than the copy destination:
  980. //
  981. // d8 = VMOVD d0
  982. // call @callee(s1)
  983. //
  984. // We need to produce a fragment description (the call site value of s1 is
  985. // /not/ just d8).
  986. if (DstReg != Reg)
  987. return std::nullopt;
  988. }
  989. return TargetInstrInfo::describeLoadedValue(MI, Reg);
  990. }
  991. const MachineInstrBuilder &
  992. ARMBaseInstrInfo::AddDReg(MachineInstrBuilder &MIB, unsigned Reg,
  993. unsigned SubIdx, unsigned State,
  994. const TargetRegisterInfo *TRI) const {
  995. if (!SubIdx)
  996. return MIB.addReg(Reg, State);
  997. if (Register::isPhysicalRegister(Reg))
  998. return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
  999. return MIB.addReg(Reg, State, SubIdx);
  1000. }
  1001. void ARMBaseInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
  1002. MachineBasicBlock::iterator I,
  1003. Register SrcReg, bool isKill, int FI,
  1004. const TargetRegisterClass *RC,
  1005. const TargetRegisterInfo *TRI,
  1006. Register VReg) const {
  1007. MachineFunction &MF = *MBB.getParent();
  1008. MachineFrameInfo &MFI = MF.getFrameInfo();
  1009. Align Alignment = MFI.getObjectAlign(FI);
  1010. MachineMemOperand *MMO = MF.getMachineMemOperand(
  1011. MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOStore,
  1012. MFI.getObjectSize(FI), Alignment);
  1013. switch (TRI->getSpillSize(*RC)) {
  1014. case 2:
  1015. if (ARM::HPRRegClass.hasSubClassEq(RC)) {
  1016. BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRH))
  1017. .addReg(SrcReg, getKillRegState(isKill))
  1018. .addFrameIndex(FI)
  1019. .addImm(0)
  1020. .addMemOperand(MMO)
  1021. .add(predOps(ARMCC::AL));
  1022. } else
  1023. llvm_unreachable("Unknown reg class!");
  1024. break;
  1025. case 4:
  1026. if (ARM::GPRRegClass.hasSubClassEq(RC)) {
  1027. BuildMI(MBB, I, DebugLoc(), get(ARM::STRi12))
  1028. .addReg(SrcReg, getKillRegState(isKill))
  1029. .addFrameIndex(FI)
  1030. .addImm(0)
  1031. .addMemOperand(MMO)
  1032. .add(predOps(ARMCC::AL));
  1033. } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
  1034. BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRS))
  1035. .addReg(SrcReg, getKillRegState(isKill))
  1036. .addFrameIndex(FI)
  1037. .addImm(0)
  1038. .addMemOperand(MMO)
  1039. .add(predOps(ARMCC::AL));
  1040. } else if (ARM::VCCRRegClass.hasSubClassEq(RC)) {
  1041. BuildMI(MBB, I, DebugLoc(), get(ARM::VSTR_P0_off))
  1042. .addReg(SrcReg, getKillRegState(isKill))
  1043. .addFrameIndex(FI)
  1044. .addImm(0)
  1045. .addMemOperand(MMO)
  1046. .add(predOps(ARMCC::AL));
  1047. } else
  1048. llvm_unreachable("Unknown reg class!");
  1049. break;
  1050. case 8:
  1051. if (ARM::DPRRegClass.hasSubClassEq(RC)) {
  1052. BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRD))
  1053. .addReg(SrcReg, getKillRegState(isKill))
  1054. .addFrameIndex(FI)
  1055. .addImm(0)
  1056. .addMemOperand(MMO)
  1057. .add(predOps(ARMCC::AL));
  1058. } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) {
  1059. if (Subtarget.hasV5TEOps()) {
  1060. MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::STRD));
  1061. AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI);
  1062. AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI);
  1063. MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO)
  1064. .add(predOps(ARMCC::AL));
  1065. } else {
  1066. // Fallback to STM instruction, which has existed since the dawn of
  1067. // time.
  1068. MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::STMIA))
  1069. .addFrameIndex(FI)
  1070. .addMemOperand(MMO)
  1071. .add(predOps(ARMCC::AL));
  1072. AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI);
  1073. AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI);
  1074. }
  1075. } else
  1076. llvm_unreachable("Unknown reg class!");
  1077. break;
  1078. case 16:
  1079. if (ARM::DPairRegClass.hasSubClassEq(RC) && Subtarget.hasNEON()) {
  1080. // Use aligned spills if the stack can be realigned.
  1081. if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF)) {
  1082. BuildMI(MBB, I, DebugLoc(), get(ARM::VST1q64))
  1083. .addFrameIndex(FI)
  1084. .addImm(16)
  1085. .addReg(SrcReg, getKillRegState(isKill))
  1086. .addMemOperand(MMO)
  1087. .add(predOps(ARMCC::AL));
  1088. } else {
  1089. BuildMI(MBB, I, DebugLoc(), get(ARM::VSTMQIA))
  1090. .addReg(SrcReg, getKillRegState(isKill))
  1091. .addFrameIndex(FI)
  1092. .addMemOperand(MMO)
  1093. .add(predOps(ARMCC::AL));
  1094. }
  1095. } else if (ARM::QPRRegClass.hasSubClassEq(RC) &&
  1096. Subtarget.hasMVEIntegerOps()) {
  1097. auto MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::MVE_VSTRWU32));
  1098. MIB.addReg(SrcReg, getKillRegState(isKill))
  1099. .addFrameIndex(FI)
  1100. .addImm(0)
  1101. .addMemOperand(MMO);
  1102. addUnpredicatedMveVpredNOp(MIB);
  1103. } else
  1104. llvm_unreachable("Unknown reg class!");
  1105. break;
  1106. case 24:
  1107. if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
  1108. // Use aligned spills if the stack can be realigned.
  1109. if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) &&
  1110. Subtarget.hasNEON()) {
  1111. BuildMI(MBB, I, DebugLoc(), get(ARM::VST1d64TPseudo))
  1112. .addFrameIndex(FI)
  1113. .addImm(16)
  1114. .addReg(SrcReg, getKillRegState(isKill))
  1115. .addMemOperand(MMO)
  1116. .add(predOps(ARMCC::AL));
  1117. } else {
  1118. MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(),
  1119. get(ARM::VSTMDIA))
  1120. .addFrameIndex(FI)
  1121. .add(predOps(ARMCC::AL))
  1122. .addMemOperand(MMO);
  1123. MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
  1124. MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
  1125. AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
  1126. }
  1127. } else
  1128. llvm_unreachable("Unknown reg class!");
  1129. break;
  1130. case 32:
  1131. if (ARM::QQPRRegClass.hasSubClassEq(RC) ||
  1132. ARM::MQQPRRegClass.hasSubClassEq(RC) ||
  1133. ARM::DQuadRegClass.hasSubClassEq(RC)) {
  1134. if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) &&
  1135. Subtarget.hasNEON()) {
  1136. // FIXME: It's possible to only store part of the QQ register if the
  1137. // spilled def has a sub-register index.
  1138. BuildMI(MBB, I, DebugLoc(), get(ARM::VST1d64QPseudo))
  1139. .addFrameIndex(FI)
  1140. .addImm(16)
  1141. .addReg(SrcReg, getKillRegState(isKill))
  1142. .addMemOperand(MMO)
  1143. .add(predOps(ARMCC::AL));
  1144. } else if (Subtarget.hasMVEIntegerOps()) {
  1145. BuildMI(MBB, I, DebugLoc(), get(ARM::MQQPRStore))
  1146. .addReg(SrcReg, getKillRegState(isKill))
  1147. .addFrameIndex(FI)
  1148. .addMemOperand(MMO);
  1149. } else {
  1150. MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(),
  1151. get(ARM::VSTMDIA))
  1152. .addFrameIndex(FI)
  1153. .add(predOps(ARMCC::AL))
  1154. .addMemOperand(MMO);
  1155. MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
  1156. MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
  1157. MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
  1158. AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
  1159. }
  1160. } else
  1161. llvm_unreachable("Unknown reg class!");
  1162. break;
  1163. case 64:
  1164. if (ARM::MQQQQPRRegClass.hasSubClassEq(RC) &&
  1165. Subtarget.hasMVEIntegerOps()) {
  1166. BuildMI(MBB, I, DebugLoc(), get(ARM::MQQQQPRStore))
  1167. .addReg(SrcReg, getKillRegState(isKill))
  1168. .addFrameIndex(FI)
  1169. .addMemOperand(MMO);
  1170. } else if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
  1171. MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::VSTMDIA))
  1172. .addFrameIndex(FI)
  1173. .add(predOps(ARMCC::AL))
  1174. .addMemOperand(MMO);
  1175. MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
  1176. MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
  1177. MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
  1178. MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
  1179. MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI);
  1180. MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI);
  1181. MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI);
  1182. AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI);
  1183. } else
  1184. llvm_unreachable("Unknown reg class!");
  1185. break;
  1186. default:
  1187. llvm_unreachable("Unknown reg class!");
  1188. }
  1189. }
  1190. unsigned ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
  1191. int &FrameIndex) const {
  1192. switch (MI.getOpcode()) {
  1193. default: break;
  1194. case ARM::STRrs:
  1195. case ARM::t2STRs: // FIXME: don't use t2STRs to access frame.
  1196. if (MI.getOperand(1).isFI() && MI.getOperand(2).isReg() &&
  1197. MI.getOperand(3).isImm() && MI.getOperand(2).getReg() == 0 &&
  1198. MI.getOperand(3).getImm() == 0) {
  1199. FrameIndex = MI.getOperand(1).getIndex();
  1200. return MI.getOperand(0).getReg();
  1201. }
  1202. break;
  1203. case ARM::STRi12:
  1204. case ARM::t2STRi12:
  1205. case ARM::tSTRspi:
  1206. case ARM::VSTRD:
  1207. case ARM::VSTRS:
  1208. case ARM::VSTR_P0_off:
  1209. case ARM::MVE_VSTRWU32:
  1210. if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() &&
  1211. MI.getOperand(2).getImm() == 0) {
  1212. FrameIndex = MI.getOperand(1).getIndex();
  1213. return MI.getOperand(0).getReg();
  1214. }
  1215. break;
  1216. case ARM::VST1q64:
  1217. case ARM::VST1d64TPseudo:
  1218. case ARM::VST1d64QPseudo:
  1219. if (MI.getOperand(0).isFI() && MI.getOperand(2).getSubReg() == 0) {
  1220. FrameIndex = MI.getOperand(0).getIndex();
  1221. return MI.getOperand(2).getReg();
  1222. }
  1223. break;
  1224. case ARM::VSTMQIA:
  1225. if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) {
  1226. FrameIndex = MI.getOperand(1).getIndex();
  1227. return MI.getOperand(0).getReg();
  1228. }
  1229. break;
  1230. case ARM::MQQPRStore:
  1231. case ARM::MQQQQPRStore:
  1232. if (MI.getOperand(1).isFI()) {
  1233. FrameIndex = MI.getOperand(1).getIndex();
  1234. return MI.getOperand(0).getReg();
  1235. }
  1236. break;
  1237. }
  1238. return 0;
  1239. }
  1240. unsigned ARMBaseInstrInfo::isStoreToStackSlotPostFE(const MachineInstr &MI,
  1241. int &FrameIndex) const {
  1242. SmallVector<const MachineMemOperand *, 1> Accesses;
  1243. if (MI.mayStore() && hasStoreToStackSlot(MI, Accesses) &&
  1244. Accesses.size() == 1) {
  1245. FrameIndex =
  1246. cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
  1247. ->getFrameIndex();
  1248. return true;
  1249. }
  1250. return false;
  1251. }
  1252. void ARMBaseInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
  1253. MachineBasicBlock::iterator I,
  1254. Register DestReg, int FI,
  1255. const TargetRegisterClass *RC,
  1256. const TargetRegisterInfo *TRI,
  1257. Register VReg) const {
  1258. DebugLoc DL;
  1259. if (I != MBB.end()) DL = I->getDebugLoc();
  1260. MachineFunction &MF = *MBB.getParent();
  1261. MachineFrameInfo &MFI = MF.getFrameInfo();
  1262. const Align Alignment = MFI.getObjectAlign(FI);
  1263. MachineMemOperand *MMO = MF.getMachineMemOperand(
  1264. MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOLoad,
  1265. MFI.getObjectSize(FI), Alignment);
  1266. switch (TRI->getSpillSize(*RC)) {
  1267. case 2:
  1268. if (ARM::HPRRegClass.hasSubClassEq(RC)) {
  1269. BuildMI(MBB, I, DL, get(ARM::VLDRH), DestReg)
  1270. .addFrameIndex(FI)
  1271. .addImm(0)
  1272. .addMemOperand(MMO)
  1273. .add(predOps(ARMCC::AL));
  1274. } else
  1275. llvm_unreachable("Unknown reg class!");
  1276. break;
  1277. case 4:
  1278. if (ARM::GPRRegClass.hasSubClassEq(RC)) {
  1279. BuildMI(MBB, I, DL, get(ARM::LDRi12), DestReg)
  1280. .addFrameIndex(FI)
  1281. .addImm(0)
  1282. .addMemOperand(MMO)
  1283. .add(predOps(ARMCC::AL));
  1284. } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
  1285. BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg)
  1286. .addFrameIndex(FI)
  1287. .addImm(0)
  1288. .addMemOperand(MMO)
  1289. .add(predOps(ARMCC::AL));
  1290. } else if (ARM::VCCRRegClass.hasSubClassEq(RC)) {
  1291. BuildMI(MBB, I, DL, get(ARM::VLDR_P0_off), DestReg)
  1292. .addFrameIndex(FI)
  1293. .addImm(0)
  1294. .addMemOperand(MMO)
  1295. .add(predOps(ARMCC::AL));
  1296. } else
  1297. llvm_unreachable("Unknown reg class!");
  1298. break;
  1299. case 8:
  1300. if (ARM::DPRRegClass.hasSubClassEq(RC)) {
  1301. BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg)
  1302. .addFrameIndex(FI)
  1303. .addImm(0)
  1304. .addMemOperand(MMO)
  1305. .add(predOps(ARMCC::AL));
  1306. } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) {
  1307. MachineInstrBuilder MIB;
  1308. if (Subtarget.hasV5TEOps()) {
  1309. MIB = BuildMI(MBB, I, DL, get(ARM::LDRD));
  1310. AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI);
  1311. AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI);
  1312. MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO)
  1313. .add(predOps(ARMCC::AL));
  1314. } else {
  1315. // Fallback to LDM instruction, which has existed since the dawn of
  1316. // time.
  1317. MIB = BuildMI(MBB, I, DL, get(ARM::LDMIA))
  1318. .addFrameIndex(FI)
  1319. .addMemOperand(MMO)
  1320. .add(predOps(ARMCC::AL));
  1321. MIB = AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI);
  1322. MIB = AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI);
  1323. }
  1324. if (DestReg.isPhysical())
  1325. MIB.addReg(DestReg, RegState::ImplicitDefine);
  1326. } else
  1327. llvm_unreachable("Unknown reg class!");
  1328. break;
  1329. case 16:
  1330. if (ARM::DPairRegClass.hasSubClassEq(RC) && Subtarget.hasNEON()) {
  1331. if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF)) {
  1332. BuildMI(MBB, I, DL, get(ARM::VLD1q64), DestReg)
  1333. .addFrameIndex(FI)
  1334. .addImm(16)
  1335. .addMemOperand(MMO)
  1336. .add(predOps(ARMCC::AL));
  1337. } else {
  1338. BuildMI(MBB, I, DL, get(ARM::VLDMQIA), DestReg)
  1339. .addFrameIndex(FI)
  1340. .addMemOperand(MMO)
  1341. .add(predOps(ARMCC::AL));
  1342. }
  1343. } else if (ARM::QPRRegClass.hasSubClassEq(RC) &&
  1344. Subtarget.hasMVEIntegerOps()) {
  1345. auto MIB = BuildMI(MBB, I, DL, get(ARM::MVE_VLDRWU32), DestReg);
  1346. MIB.addFrameIndex(FI)
  1347. .addImm(0)
  1348. .addMemOperand(MMO);
  1349. addUnpredicatedMveVpredNOp(MIB);
  1350. } else
  1351. llvm_unreachable("Unknown reg class!");
  1352. break;
  1353. case 24:
  1354. if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
  1355. if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) &&
  1356. Subtarget.hasNEON()) {
  1357. BuildMI(MBB, I, DL, get(ARM::VLD1d64TPseudo), DestReg)
  1358. .addFrameIndex(FI)
  1359. .addImm(16)
  1360. .addMemOperand(MMO)
  1361. .add(predOps(ARMCC::AL));
  1362. } else {
  1363. MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
  1364. .addFrameIndex(FI)
  1365. .addMemOperand(MMO)
  1366. .add(predOps(ARMCC::AL));
  1367. MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
  1368. MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
  1369. MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
  1370. if (DestReg.isPhysical())
  1371. MIB.addReg(DestReg, RegState::ImplicitDefine);
  1372. }
  1373. } else
  1374. llvm_unreachable("Unknown reg class!");
  1375. break;
  1376. case 32:
  1377. if (ARM::QQPRRegClass.hasSubClassEq(RC) ||
  1378. ARM::MQQPRRegClass.hasSubClassEq(RC) ||
  1379. ARM::DQuadRegClass.hasSubClassEq(RC)) {
  1380. if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) &&
  1381. Subtarget.hasNEON()) {
  1382. BuildMI(MBB, I, DL, get(ARM::VLD1d64QPseudo), DestReg)
  1383. .addFrameIndex(FI)
  1384. .addImm(16)
  1385. .addMemOperand(MMO)
  1386. .add(predOps(ARMCC::AL));
  1387. } else if (Subtarget.hasMVEIntegerOps()) {
  1388. BuildMI(MBB, I, DL, get(ARM::MQQPRLoad), DestReg)
  1389. .addFrameIndex(FI)
  1390. .addMemOperand(MMO);
  1391. } else {
  1392. MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
  1393. .addFrameIndex(FI)
  1394. .add(predOps(ARMCC::AL))
  1395. .addMemOperand(MMO);
  1396. MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
  1397. MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
  1398. MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
  1399. MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
  1400. if (DestReg.isPhysical())
  1401. MIB.addReg(DestReg, RegState::ImplicitDefine);
  1402. }
  1403. } else
  1404. llvm_unreachable("Unknown reg class!");
  1405. break;
  1406. case 64:
  1407. if (ARM::MQQQQPRRegClass.hasSubClassEq(RC) &&
  1408. Subtarget.hasMVEIntegerOps()) {
  1409. BuildMI(MBB, I, DL, get(ARM::MQQQQPRLoad), DestReg)
  1410. .addFrameIndex(FI)
  1411. .addMemOperand(MMO);
  1412. } else if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
  1413. MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
  1414. .addFrameIndex(FI)
  1415. .add(predOps(ARMCC::AL))
  1416. .addMemOperand(MMO);
  1417. MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
  1418. MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
  1419. MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
  1420. MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
  1421. MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::DefineNoRead, TRI);
  1422. MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::DefineNoRead, TRI);
  1423. MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::DefineNoRead, TRI);
  1424. MIB = AddDReg(MIB, DestReg, ARM::dsub_7, RegState::DefineNoRead, TRI);
  1425. if (DestReg.isPhysical())
  1426. MIB.addReg(DestReg, RegState::ImplicitDefine);
  1427. } else
  1428. llvm_unreachable("Unknown reg class!");
  1429. break;
  1430. default:
  1431. llvm_unreachable("Unknown regclass!");
  1432. }
  1433. }
  1434. unsigned ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
  1435. int &FrameIndex) const {
  1436. switch (MI.getOpcode()) {
  1437. default: break;
  1438. case ARM::LDRrs:
  1439. case ARM::t2LDRs: // FIXME: don't use t2LDRs to access frame.
  1440. if (MI.getOperand(1).isFI() && MI.getOperand(2).isReg() &&
  1441. MI.getOperand(3).isImm() && MI.getOperand(2).getReg() == 0 &&
  1442. MI.getOperand(3).getImm() == 0) {
  1443. FrameIndex = MI.getOperand(1).getIndex();
  1444. return MI.getOperand(0).getReg();
  1445. }
  1446. break;
  1447. case ARM::LDRi12:
  1448. case ARM::t2LDRi12:
  1449. case ARM::tLDRspi:
  1450. case ARM::VLDRD:
  1451. case ARM::VLDRS:
  1452. case ARM::VLDR_P0_off:
  1453. case ARM::MVE_VLDRWU32:
  1454. if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() &&
  1455. MI.getOperand(2).getImm() == 0) {
  1456. FrameIndex = MI.getOperand(1).getIndex();
  1457. return MI.getOperand(0).getReg();
  1458. }
  1459. break;
  1460. case ARM::VLD1q64:
  1461. case ARM::VLD1d8TPseudo:
  1462. case ARM::VLD1d16TPseudo:
  1463. case ARM::VLD1d32TPseudo:
  1464. case ARM::VLD1d64TPseudo:
  1465. case ARM::VLD1d8QPseudo:
  1466. case ARM::VLD1d16QPseudo:
  1467. case ARM::VLD1d32QPseudo:
  1468. case ARM::VLD1d64QPseudo:
  1469. if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) {
  1470. FrameIndex = MI.getOperand(1).getIndex();
  1471. return MI.getOperand(0).getReg();
  1472. }
  1473. break;
  1474. case ARM::VLDMQIA:
  1475. if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) {
  1476. FrameIndex = MI.getOperand(1).getIndex();
  1477. return MI.getOperand(0).getReg();
  1478. }
  1479. break;
  1480. case ARM::MQQPRLoad:
  1481. case ARM::MQQQQPRLoad:
  1482. if (MI.getOperand(1).isFI()) {
  1483. FrameIndex = MI.getOperand(1).getIndex();
  1484. return MI.getOperand(0).getReg();
  1485. }
  1486. break;
  1487. }
  1488. return 0;
  1489. }
  1490. unsigned ARMBaseInstrInfo::isLoadFromStackSlotPostFE(const MachineInstr &MI,
  1491. int &FrameIndex) const {
  1492. SmallVector<const MachineMemOperand *, 1> Accesses;
  1493. if (MI.mayLoad() && hasLoadFromStackSlot(MI, Accesses) &&
  1494. Accesses.size() == 1) {
  1495. FrameIndex =
  1496. cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
  1497. ->getFrameIndex();
  1498. return true;
  1499. }
  1500. return false;
  1501. }
  1502. /// Expands MEMCPY to either LDMIA/STMIA or LDMIA_UPD/STMID_UPD
  1503. /// depending on whether the result is used.
  1504. void ARMBaseInstrInfo::expandMEMCPY(MachineBasicBlock::iterator MI) const {
  1505. bool isThumb1 = Subtarget.isThumb1Only();
  1506. bool isThumb2 = Subtarget.isThumb2();
  1507. const ARMBaseInstrInfo *TII = Subtarget.getInstrInfo();
  1508. DebugLoc dl = MI->getDebugLoc();
  1509. MachineBasicBlock *BB = MI->getParent();
  1510. MachineInstrBuilder LDM, STM;
  1511. if (isThumb1 || !MI->getOperand(1).isDead()) {
  1512. MachineOperand LDWb(MI->getOperand(1));
  1513. LDM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA_UPD
  1514. : isThumb1 ? ARM::tLDMIA_UPD
  1515. : ARM::LDMIA_UPD))
  1516. .add(LDWb);
  1517. } else {
  1518. LDM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA : ARM::LDMIA));
  1519. }
  1520. if (isThumb1 || !MI->getOperand(0).isDead()) {
  1521. MachineOperand STWb(MI->getOperand(0));
  1522. STM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA_UPD
  1523. : isThumb1 ? ARM::tSTMIA_UPD
  1524. : ARM::STMIA_UPD))
  1525. .add(STWb);
  1526. } else {
  1527. STM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA : ARM::STMIA));
  1528. }
  1529. MachineOperand LDBase(MI->getOperand(3));
  1530. LDM.add(LDBase).add(predOps(ARMCC::AL));
  1531. MachineOperand STBase(MI->getOperand(2));
  1532. STM.add(STBase).add(predOps(ARMCC::AL));
  1533. // Sort the scratch registers into ascending order.
  1534. const TargetRegisterInfo &TRI = getRegisterInfo();
  1535. SmallVector<unsigned, 6> ScratchRegs;
  1536. for(unsigned I = 5; I < MI->getNumOperands(); ++I)
  1537. ScratchRegs.push_back(MI->getOperand(I).getReg());
  1538. llvm::sort(ScratchRegs,
  1539. [&TRI](const unsigned &Reg1, const unsigned &Reg2) -> bool {
  1540. return TRI.getEncodingValue(Reg1) <
  1541. TRI.getEncodingValue(Reg2);
  1542. });
  1543. for (const auto &Reg : ScratchRegs) {
  1544. LDM.addReg(Reg, RegState::Define);
  1545. STM.addReg(Reg, RegState::Kill);
  1546. }
  1547. BB->erase(MI);
  1548. }
  1549. bool ARMBaseInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
  1550. if (MI.getOpcode() == TargetOpcode::LOAD_STACK_GUARD) {
  1551. expandLoadStackGuard(MI);
  1552. MI.getParent()->erase(MI);
  1553. return true;
  1554. }
  1555. if (MI.getOpcode() == ARM::MEMCPY) {
  1556. expandMEMCPY(MI);
  1557. return true;
  1558. }
  1559. // This hook gets to expand COPY instructions before they become
  1560. // copyPhysReg() calls. Look for VMOVS instructions that can legally be
  1561. // widened to VMOVD. We prefer the VMOVD when possible because it may be
  1562. // changed into a VORR that can go down the NEON pipeline.
  1563. if (!MI.isCopy() || Subtarget.dontWidenVMOVS() || !Subtarget.hasFP64())
  1564. return false;
  1565. // Look for a copy between even S-registers. That is where we keep floats
  1566. // when using NEON v2f32 instructions for f32 arithmetic.
  1567. Register DstRegS = MI.getOperand(0).getReg();
  1568. Register SrcRegS = MI.getOperand(1).getReg();
  1569. if (!ARM::SPRRegClass.contains(DstRegS, SrcRegS))
  1570. return false;
  1571. const TargetRegisterInfo *TRI = &getRegisterInfo();
  1572. unsigned DstRegD = TRI->getMatchingSuperReg(DstRegS, ARM::ssub_0,
  1573. &ARM::DPRRegClass);
  1574. unsigned SrcRegD = TRI->getMatchingSuperReg(SrcRegS, ARM::ssub_0,
  1575. &ARM::DPRRegClass);
  1576. if (!DstRegD || !SrcRegD)
  1577. return false;
  1578. // We want to widen this into a DstRegD = VMOVD SrcRegD copy. This is only
  1579. // legal if the COPY already defines the full DstRegD, and it isn't a
  1580. // sub-register insertion.
  1581. if (!MI.definesRegister(DstRegD, TRI) || MI.readsRegister(DstRegD, TRI))
  1582. return false;
  1583. // A dead copy shouldn't show up here, but reject it just in case.
  1584. if (MI.getOperand(0).isDead())
  1585. return false;
  1586. // All clear, widen the COPY.
  1587. LLVM_DEBUG(dbgs() << "widening: " << MI);
  1588. MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI);
  1589. // Get rid of the old implicit-def of DstRegD. Leave it if it defines a Q-reg
  1590. // or some other super-register.
  1591. int ImpDefIdx = MI.findRegisterDefOperandIdx(DstRegD);
  1592. if (ImpDefIdx != -1)
  1593. MI.removeOperand(ImpDefIdx);
  1594. // Change the opcode and operands.
  1595. MI.setDesc(get(ARM::VMOVD));
  1596. MI.getOperand(0).setReg(DstRegD);
  1597. MI.getOperand(1).setReg(SrcRegD);
  1598. MIB.add(predOps(ARMCC::AL));
  1599. // We are now reading SrcRegD instead of SrcRegS. This may upset the
  1600. // register scavenger and machine verifier, so we need to indicate that we
  1601. // are reading an undefined value from SrcRegD, but a proper value from
  1602. // SrcRegS.
  1603. MI.getOperand(1).setIsUndef();
  1604. MIB.addReg(SrcRegS, RegState::Implicit);
  1605. // SrcRegD may actually contain an unrelated value in the ssub_1
  1606. // sub-register. Don't kill it. Only kill the ssub_0 sub-register.
  1607. if (MI.getOperand(1).isKill()) {
  1608. MI.getOperand(1).setIsKill(false);
  1609. MI.addRegisterKilled(SrcRegS, TRI, true);
  1610. }
  1611. LLVM_DEBUG(dbgs() << "replaced by: " << MI);
  1612. return true;
  1613. }
  1614. /// Create a copy of a const pool value. Update CPI to the new index and return
  1615. /// the label UID.
  1616. static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) {
  1617. MachineConstantPool *MCP = MF.getConstantPool();
  1618. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1619. const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
  1620. assert(MCPE.isMachineConstantPoolEntry() &&
  1621. "Expecting a machine constantpool entry!");
  1622. ARMConstantPoolValue *ACPV =
  1623. static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
  1624. unsigned PCLabelId = AFI->createPICLabelUId();
  1625. ARMConstantPoolValue *NewCPV = nullptr;
  1626. // FIXME: The below assumes PIC relocation model and that the function
  1627. // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and
  1628. // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR
  1629. // instructions, so that's probably OK, but is PIC always correct when
  1630. // we get here?
  1631. if (ACPV->isGlobalValue())
  1632. NewCPV = ARMConstantPoolConstant::Create(
  1633. cast<ARMConstantPoolConstant>(ACPV)->getGV(), PCLabelId, ARMCP::CPValue,
  1634. 4, ACPV->getModifier(), ACPV->mustAddCurrentAddress());
  1635. else if (ACPV->isExtSymbol())
  1636. NewCPV = ARMConstantPoolSymbol::
  1637. Create(MF.getFunction().getContext(),
  1638. cast<ARMConstantPoolSymbol>(ACPV)->getSymbol(), PCLabelId, 4);
  1639. else if (ACPV->isBlockAddress())
  1640. NewCPV = ARMConstantPoolConstant::
  1641. Create(cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress(), PCLabelId,
  1642. ARMCP::CPBlockAddress, 4);
  1643. else if (ACPV->isLSDA())
  1644. NewCPV = ARMConstantPoolConstant::Create(&MF.getFunction(), PCLabelId,
  1645. ARMCP::CPLSDA, 4);
  1646. else if (ACPV->isMachineBasicBlock())
  1647. NewCPV = ARMConstantPoolMBB::
  1648. Create(MF.getFunction().getContext(),
  1649. cast<ARMConstantPoolMBB>(ACPV)->getMBB(), PCLabelId, 4);
  1650. else
  1651. llvm_unreachable("Unexpected ARM constantpool value type!!");
  1652. CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlign());
  1653. return PCLabelId;
  1654. }
  1655. void ARMBaseInstrInfo::reMaterialize(MachineBasicBlock &MBB,
  1656. MachineBasicBlock::iterator I,
  1657. Register DestReg, unsigned SubIdx,
  1658. const MachineInstr &Orig,
  1659. const TargetRegisterInfo &TRI) const {
  1660. unsigned Opcode = Orig.getOpcode();
  1661. switch (Opcode) {
  1662. default: {
  1663. MachineInstr *MI = MBB.getParent()->CloneMachineInstr(&Orig);
  1664. MI->substituteRegister(Orig.getOperand(0).getReg(), DestReg, SubIdx, TRI);
  1665. MBB.insert(I, MI);
  1666. break;
  1667. }
  1668. case ARM::tLDRpci_pic:
  1669. case ARM::t2LDRpci_pic: {
  1670. MachineFunction &MF = *MBB.getParent();
  1671. unsigned CPI = Orig.getOperand(1).getIndex();
  1672. unsigned PCLabelId = duplicateCPV(MF, CPI);
  1673. BuildMI(MBB, I, Orig.getDebugLoc(), get(Opcode), DestReg)
  1674. .addConstantPoolIndex(CPI)
  1675. .addImm(PCLabelId)
  1676. .cloneMemRefs(Orig);
  1677. break;
  1678. }
  1679. }
  1680. }
  1681. MachineInstr &
  1682. ARMBaseInstrInfo::duplicate(MachineBasicBlock &MBB,
  1683. MachineBasicBlock::iterator InsertBefore,
  1684. const MachineInstr &Orig) const {
  1685. MachineInstr &Cloned = TargetInstrInfo::duplicate(MBB, InsertBefore, Orig);
  1686. MachineBasicBlock::instr_iterator I = Cloned.getIterator();
  1687. for (;;) {
  1688. switch (I->getOpcode()) {
  1689. case ARM::tLDRpci_pic:
  1690. case ARM::t2LDRpci_pic: {
  1691. MachineFunction &MF = *MBB.getParent();
  1692. unsigned CPI = I->getOperand(1).getIndex();
  1693. unsigned PCLabelId = duplicateCPV(MF, CPI);
  1694. I->getOperand(1).setIndex(CPI);
  1695. I->getOperand(2).setImm(PCLabelId);
  1696. break;
  1697. }
  1698. }
  1699. if (!I->isBundledWithSucc())
  1700. break;
  1701. ++I;
  1702. }
  1703. return Cloned;
  1704. }
  1705. bool ARMBaseInstrInfo::produceSameValue(const MachineInstr &MI0,
  1706. const MachineInstr &MI1,
  1707. const MachineRegisterInfo *MRI) const {
  1708. unsigned Opcode = MI0.getOpcode();
  1709. if (Opcode == ARM::t2LDRpci || Opcode == ARM::t2LDRpci_pic ||
  1710. Opcode == ARM::tLDRpci || Opcode == ARM::tLDRpci_pic ||
  1711. Opcode == ARM::LDRLIT_ga_pcrel || Opcode == ARM::LDRLIT_ga_pcrel_ldr ||
  1712. Opcode == ARM::tLDRLIT_ga_pcrel || Opcode == ARM::t2LDRLIT_ga_pcrel ||
  1713. Opcode == ARM::MOV_ga_pcrel || Opcode == ARM::MOV_ga_pcrel_ldr ||
  1714. Opcode == ARM::t2MOV_ga_pcrel) {
  1715. if (MI1.getOpcode() != Opcode)
  1716. return false;
  1717. if (MI0.getNumOperands() != MI1.getNumOperands())
  1718. return false;
  1719. const MachineOperand &MO0 = MI0.getOperand(1);
  1720. const MachineOperand &MO1 = MI1.getOperand(1);
  1721. if (MO0.getOffset() != MO1.getOffset())
  1722. return false;
  1723. if (Opcode == ARM::LDRLIT_ga_pcrel || Opcode == ARM::LDRLIT_ga_pcrel_ldr ||
  1724. Opcode == ARM::tLDRLIT_ga_pcrel || Opcode == ARM::t2LDRLIT_ga_pcrel ||
  1725. Opcode == ARM::MOV_ga_pcrel || Opcode == ARM::MOV_ga_pcrel_ldr ||
  1726. Opcode == ARM::t2MOV_ga_pcrel)
  1727. // Ignore the PC labels.
  1728. return MO0.getGlobal() == MO1.getGlobal();
  1729. const MachineFunction *MF = MI0.getParent()->getParent();
  1730. const MachineConstantPool *MCP = MF->getConstantPool();
  1731. int CPI0 = MO0.getIndex();
  1732. int CPI1 = MO1.getIndex();
  1733. const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0];
  1734. const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1];
  1735. bool isARMCP0 = MCPE0.isMachineConstantPoolEntry();
  1736. bool isARMCP1 = MCPE1.isMachineConstantPoolEntry();
  1737. if (isARMCP0 && isARMCP1) {
  1738. ARMConstantPoolValue *ACPV0 =
  1739. static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal);
  1740. ARMConstantPoolValue *ACPV1 =
  1741. static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal);
  1742. return ACPV0->hasSameValue(ACPV1);
  1743. } else if (!isARMCP0 && !isARMCP1) {
  1744. return MCPE0.Val.ConstVal == MCPE1.Val.ConstVal;
  1745. }
  1746. return false;
  1747. } else if (Opcode == ARM::PICLDR) {
  1748. if (MI1.getOpcode() != Opcode)
  1749. return false;
  1750. if (MI0.getNumOperands() != MI1.getNumOperands())
  1751. return false;
  1752. Register Addr0 = MI0.getOperand(1).getReg();
  1753. Register Addr1 = MI1.getOperand(1).getReg();
  1754. if (Addr0 != Addr1) {
  1755. if (!MRI || !Addr0.isVirtual() || !Addr1.isVirtual())
  1756. return false;
  1757. // This assumes SSA form.
  1758. MachineInstr *Def0 = MRI->getVRegDef(Addr0);
  1759. MachineInstr *Def1 = MRI->getVRegDef(Addr1);
  1760. // Check if the loaded value, e.g. a constantpool of a global address, are
  1761. // the same.
  1762. if (!produceSameValue(*Def0, *Def1, MRI))
  1763. return false;
  1764. }
  1765. for (unsigned i = 3, e = MI0.getNumOperands(); i != e; ++i) {
  1766. // %12 = PICLDR %11, 0, 14, %noreg
  1767. const MachineOperand &MO0 = MI0.getOperand(i);
  1768. const MachineOperand &MO1 = MI1.getOperand(i);
  1769. if (!MO0.isIdenticalTo(MO1))
  1770. return false;
  1771. }
  1772. return true;
  1773. }
  1774. return MI0.isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
  1775. }
  1776. /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
  1777. /// determine if two loads are loading from the same base address. It should
  1778. /// only return true if the base pointers are the same and the only differences
  1779. /// between the two addresses is the offset. It also returns the offsets by
  1780. /// reference.
  1781. ///
  1782. /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched
  1783. /// is permanently disabled.
  1784. bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
  1785. int64_t &Offset1,
  1786. int64_t &Offset2) const {
  1787. // Don't worry about Thumb: just ARM and Thumb2.
  1788. if (Subtarget.isThumb1Only()) return false;
  1789. if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
  1790. return false;
  1791. switch (Load1->getMachineOpcode()) {
  1792. default:
  1793. return false;
  1794. case ARM::LDRi12:
  1795. case ARM::LDRBi12:
  1796. case ARM::LDRD:
  1797. case ARM::LDRH:
  1798. case ARM::LDRSB:
  1799. case ARM::LDRSH:
  1800. case ARM::VLDRD:
  1801. case ARM::VLDRS:
  1802. case ARM::t2LDRi8:
  1803. case ARM::t2LDRBi8:
  1804. case ARM::t2LDRDi8:
  1805. case ARM::t2LDRSHi8:
  1806. case ARM::t2LDRi12:
  1807. case ARM::t2LDRBi12:
  1808. case ARM::t2LDRSHi12:
  1809. break;
  1810. }
  1811. switch (Load2->getMachineOpcode()) {
  1812. default:
  1813. return false;
  1814. case ARM::LDRi12:
  1815. case ARM::LDRBi12:
  1816. case ARM::LDRD:
  1817. case ARM::LDRH:
  1818. case ARM::LDRSB:
  1819. case ARM::LDRSH:
  1820. case ARM::VLDRD:
  1821. case ARM::VLDRS:
  1822. case ARM::t2LDRi8:
  1823. case ARM::t2LDRBi8:
  1824. case ARM::t2LDRSHi8:
  1825. case ARM::t2LDRi12:
  1826. case ARM::t2LDRBi12:
  1827. case ARM::t2LDRSHi12:
  1828. break;
  1829. }
  1830. // Check if base addresses and chain operands match.
  1831. if (Load1->getOperand(0) != Load2->getOperand(0) ||
  1832. Load1->getOperand(4) != Load2->getOperand(4))
  1833. return false;
  1834. // Index should be Reg0.
  1835. if (Load1->getOperand(3) != Load2->getOperand(3))
  1836. return false;
  1837. // Determine the offsets.
  1838. if (isa<ConstantSDNode>(Load1->getOperand(1)) &&
  1839. isa<ConstantSDNode>(Load2->getOperand(1))) {
  1840. Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getSExtValue();
  1841. Offset2 = cast<ConstantSDNode>(Load2->getOperand(1))->getSExtValue();
  1842. return true;
  1843. }
  1844. return false;
  1845. }
  1846. /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
  1847. /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should
  1848. /// be scheduled togther. On some targets if two loads are loading from
  1849. /// addresses in the same cache line, it's better if they are scheduled
  1850. /// together. This function takes two integers that represent the load offsets
  1851. /// from the common base address. It returns true if it decides it's desirable
  1852. /// to schedule the two loads together. "NumLoads" is the number of loads that
  1853. /// have already been scheduled after Load1.
  1854. ///
  1855. /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched
  1856. /// is permanently disabled.
  1857. bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
  1858. int64_t Offset1, int64_t Offset2,
  1859. unsigned NumLoads) const {
  1860. // Don't worry about Thumb: just ARM and Thumb2.
  1861. if (Subtarget.isThumb1Only()) return false;
  1862. assert(Offset2 > Offset1);
  1863. if ((Offset2 - Offset1) / 8 > 64)
  1864. return false;
  1865. // Check if the machine opcodes are different. If they are different
  1866. // then we consider them to not be of the same base address,
  1867. // EXCEPT in the case of Thumb2 byte loads where one is LDRBi8 and the other LDRBi12.
  1868. // In this case, they are considered to be the same because they are different
  1869. // encoding forms of the same basic instruction.
  1870. if ((Load1->getMachineOpcode() != Load2->getMachineOpcode()) &&
  1871. !((Load1->getMachineOpcode() == ARM::t2LDRBi8 &&
  1872. Load2->getMachineOpcode() == ARM::t2LDRBi12) ||
  1873. (Load1->getMachineOpcode() == ARM::t2LDRBi12 &&
  1874. Load2->getMachineOpcode() == ARM::t2LDRBi8)))
  1875. return false; // FIXME: overly conservative?
  1876. // Four loads in a row should be sufficient.
  1877. if (NumLoads >= 3)
  1878. return false;
  1879. return true;
  1880. }
  1881. bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
  1882. const MachineBasicBlock *MBB,
  1883. const MachineFunction &MF) const {
  1884. // Debug info is never a scheduling boundary. It's necessary to be explicit
  1885. // due to the special treatment of IT instructions below, otherwise a
  1886. // dbg_value followed by an IT will result in the IT instruction being
  1887. // considered a scheduling hazard, which is wrong. It should be the actual
  1888. // instruction preceding the dbg_value instruction(s), just like it is
  1889. // when debug info is not present.
  1890. if (MI.isDebugInstr())
  1891. return false;
  1892. // Terminators and labels can't be scheduled around.
  1893. if (MI.isTerminator() || MI.isPosition())
  1894. return true;
  1895. // INLINEASM_BR can jump to another block
  1896. if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
  1897. return true;
  1898. if (isSEHInstruction(MI))
  1899. return true;
  1900. // Treat the start of the IT block as a scheduling boundary, but schedule
  1901. // t2IT along with all instructions following it.
  1902. // FIXME: This is a big hammer. But the alternative is to add all potential
  1903. // true and anti dependencies to IT block instructions as implicit operands
  1904. // to the t2IT instruction. The added compile time and complexity does not
  1905. // seem worth it.
  1906. MachineBasicBlock::const_iterator I = MI;
  1907. // Make sure to skip any debug instructions
  1908. while (++I != MBB->end() && I->isDebugInstr())
  1909. ;
  1910. if (I != MBB->end() && I->getOpcode() == ARM::t2IT)
  1911. return true;
  1912. // Don't attempt to schedule around any instruction that defines
  1913. // a stack-oriented pointer, as it's unlikely to be profitable. This
  1914. // saves compile time, because it doesn't require every single
  1915. // stack slot reference to depend on the instruction that does the
  1916. // modification.
  1917. // Calls don't actually change the stack pointer, even if they have imp-defs.
  1918. // No ARM calling conventions change the stack pointer. (X86 calling
  1919. // conventions sometimes do).
  1920. if (!MI.isCall() && MI.definesRegister(ARM::SP))
  1921. return true;
  1922. return false;
  1923. }
  1924. bool ARMBaseInstrInfo::
  1925. isProfitableToIfCvt(MachineBasicBlock &MBB,
  1926. unsigned NumCycles, unsigned ExtraPredCycles,
  1927. BranchProbability Probability) const {
  1928. if (!NumCycles)
  1929. return false;
  1930. // If we are optimizing for size, see if the branch in the predecessor can be
  1931. // lowered to cbn?z by the constant island lowering pass, and return false if
  1932. // so. This results in a shorter instruction sequence.
  1933. if (MBB.getParent()->getFunction().hasOptSize()) {
  1934. MachineBasicBlock *Pred = *MBB.pred_begin();
  1935. if (!Pred->empty()) {
  1936. MachineInstr *LastMI = &*Pred->rbegin();
  1937. if (LastMI->getOpcode() == ARM::t2Bcc) {
  1938. const TargetRegisterInfo *TRI = &getRegisterInfo();
  1939. MachineInstr *CmpMI = findCMPToFoldIntoCBZ(LastMI, TRI);
  1940. if (CmpMI)
  1941. return false;
  1942. }
  1943. }
  1944. }
  1945. return isProfitableToIfCvt(MBB, NumCycles, ExtraPredCycles,
  1946. MBB, 0, 0, Probability);
  1947. }
  1948. bool ARMBaseInstrInfo::
  1949. isProfitableToIfCvt(MachineBasicBlock &TBB,
  1950. unsigned TCycles, unsigned TExtra,
  1951. MachineBasicBlock &FBB,
  1952. unsigned FCycles, unsigned FExtra,
  1953. BranchProbability Probability) const {
  1954. if (!TCycles)
  1955. return false;
  1956. // In thumb code we often end up trading one branch for a IT block, and
  1957. // if we are cloning the instruction can increase code size. Prevent
  1958. // blocks with multiple predecesors from being ifcvted to prevent this
  1959. // cloning.
  1960. if (Subtarget.isThumb2() && TBB.getParent()->getFunction().hasMinSize()) {
  1961. if (TBB.pred_size() != 1 || FBB.pred_size() != 1)
  1962. return false;
  1963. }
  1964. // Attempt to estimate the relative costs of predication versus branching.
  1965. // Here we scale up each component of UnpredCost to avoid precision issue when
  1966. // scaling TCycles/FCycles by Probability.
  1967. const unsigned ScalingUpFactor = 1024;
  1968. unsigned PredCost = (TCycles + FCycles + TExtra + FExtra) * ScalingUpFactor;
  1969. unsigned UnpredCost;
  1970. if (!Subtarget.hasBranchPredictor()) {
  1971. // When we don't have a branch predictor it's always cheaper to not take a
  1972. // branch than take it, so we have to take that into account.
  1973. unsigned NotTakenBranchCost = 1;
  1974. unsigned TakenBranchCost = Subtarget.getMispredictionPenalty();
  1975. unsigned TUnpredCycles, FUnpredCycles;
  1976. if (!FCycles) {
  1977. // Triangle: TBB is the fallthrough
  1978. TUnpredCycles = TCycles + NotTakenBranchCost;
  1979. FUnpredCycles = TakenBranchCost;
  1980. } else {
  1981. // Diamond: TBB is the block that is branched to, FBB is the fallthrough
  1982. TUnpredCycles = TCycles + TakenBranchCost;
  1983. FUnpredCycles = FCycles + NotTakenBranchCost;
  1984. // The branch at the end of FBB will disappear when it's predicated, so
  1985. // discount it from PredCost.
  1986. PredCost -= 1 * ScalingUpFactor;
  1987. }
  1988. // The total cost is the cost of each path scaled by their probabilites
  1989. unsigned TUnpredCost = Probability.scale(TUnpredCycles * ScalingUpFactor);
  1990. unsigned FUnpredCost = Probability.getCompl().scale(FUnpredCycles * ScalingUpFactor);
  1991. UnpredCost = TUnpredCost + FUnpredCost;
  1992. // When predicating assume that the first IT can be folded away but later
  1993. // ones cost one cycle each
  1994. if (Subtarget.isThumb2() && TCycles + FCycles > 4) {
  1995. PredCost += ((TCycles + FCycles - 4) / 4) * ScalingUpFactor;
  1996. }
  1997. } else {
  1998. unsigned TUnpredCost = Probability.scale(TCycles * ScalingUpFactor);
  1999. unsigned FUnpredCost =
  2000. Probability.getCompl().scale(FCycles * ScalingUpFactor);
  2001. UnpredCost = TUnpredCost + FUnpredCost;
  2002. UnpredCost += 1 * ScalingUpFactor; // The branch itself
  2003. UnpredCost += Subtarget.getMispredictionPenalty() * ScalingUpFactor / 10;
  2004. }
  2005. return PredCost <= UnpredCost;
  2006. }
  2007. unsigned
  2008. ARMBaseInstrInfo::extraSizeToPredicateInstructions(const MachineFunction &MF,
  2009. unsigned NumInsts) const {
  2010. // Thumb2 needs a 2-byte IT instruction to predicate up to 4 instructions.
  2011. // ARM has a condition code field in every predicable instruction, using it
  2012. // doesn't change code size.
  2013. if (!Subtarget.isThumb2())
  2014. return 0;
  2015. // It's possible that the size of the IT is restricted to a single block.
  2016. unsigned MaxInsts = Subtarget.restrictIT() ? 1 : 4;
  2017. return divideCeil(NumInsts, MaxInsts) * 2;
  2018. }
  2019. unsigned
  2020. ARMBaseInstrInfo::predictBranchSizeForIfCvt(MachineInstr &MI) const {
  2021. // If this branch is likely to be folded into the comparison to form a
  2022. // CB(N)Z, then removing it won't reduce code size at all, because that will
  2023. // just replace the CB(N)Z with a CMP.
  2024. if (MI.getOpcode() == ARM::t2Bcc &&
  2025. findCMPToFoldIntoCBZ(&MI, &getRegisterInfo()))
  2026. return 0;
  2027. unsigned Size = getInstSizeInBytes(MI);
  2028. // For Thumb2, all branches are 32-bit instructions during the if conversion
  2029. // pass, but may be replaced with 16-bit instructions during size reduction.
  2030. // Since the branches considered by if conversion tend to be forward branches
  2031. // over small basic blocks, they are very likely to be in range for the
  2032. // narrow instructions, so we assume the final code size will be half what it
  2033. // currently is.
  2034. if (Subtarget.isThumb2())
  2035. Size /= 2;
  2036. return Size;
  2037. }
  2038. bool
  2039. ARMBaseInstrInfo::isProfitableToUnpredicate(MachineBasicBlock &TMBB,
  2040. MachineBasicBlock &FMBB) const {
  2041. // Reduce false anti-dependencies to let the target's out-of-order execution
  2042. // engine do its thing.
  2043. return Subtarget.isProfitableToUnpredicate();
  2044. }
  2045. /// getInstrPredicate - If instruction is predicated, returns its predicate
  2046. /// condition, otherwise returns AL. It also returns the condition code
  2047. /// register by reference.
  2048. ARMCC::CondCodes llvm::getInstrPredicate(const MachineInstr &MI,
  2049. Register &PredReg) {
  2050. int PIdx = MI.findFirstPredOperandIdx();
  2051. if (PIdx == -1) {
  2052. PredReg = 0;
  2053. return ARMCC::AL;
  2054. }
  2055. PredReg = MI.getOperand(PIdx+1).getReg();
  2056. return (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
  2057. }
  2058. unsigned llvm::getMatchingCondBranchOpcode(unsigned Opc) {
  2059. if (Opc == ARM::B)
  2060. return ARM::Bcc;
  2061. if (Opc == ARM::tB)
  2062. return ARM::tBcc;
  2063. if (Opc == ARM::t2B)
  2064. return ARM::t2Bcc;
  2065. llvm_unreachable("Unknown unconditional branch opcode!");
  2066. }
  2067. MachineInstr *ARMBaseInstrInfo::commuteInstructionImpl(MachineInstr &MI,
  2068. bool NewMI,
  2069. unsigned OpIdx1,
  2070. unsigned OpIdx2) const {
  2071. switch (MI.getOpcode()) {
  2072. case ARM::MOVCCr:
  2073. case ARM::t2MOVCCr: {
  2074. // MOVCC can be commuted by inverting the condition.
  2075. Register PredReg;
  2076. ARMCC::CondCodes CC = getInstrPredicate(MI, PredReg);
  2077. // MOVCC AL can't be inverted. Shouldn't happen.
  2078. if (CC == ARMCC::AL || PredReg != ARM::CPSR)
  2079. return nullptr;
  2080. MachineInstr *CommutedMI =
  2081. TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
  2082. if (!CommutedMI)
  2083. return nullptr;
  2084. // After swapping the MOVCC operands, also invert the condition.
  2085. CommutedMI->getOperand(CommutedMI->findFirstPredOperandIdx())
  2086. .setImm(ARMCC::getOppositeCondition(CC));
  2087. return CommutedMI;
  2088. }
  2089. }
  2090. return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
  2091. }
  2092. /// Identify instructions that can be folded into a MOVCC instruction, and
  2093. /// return the defining instruction.
  2094. MachineInstr *
  2095. ARMBaseInstrInfo::canFoldIntoMOVCC(Register Reg, const MachineRegisterInfo &MRI,
  2096. const TargetInstrInfo *TII) const {
  2097. if (!Reg.isVirtual())
  2098. return nullptr;
  2099. if (!MRI.hasOneNonDBGUse(Reg))
  2100. return nullptr;
  2101. MachineInstr *MI = MRI.getVRegDef(Reg);
  2102. if (!MI)
  2103. return nullptr;
  2104. // Check if MI can be predicated and folded into the MOVCC.
  2105. if (!isPredicable(*MI))
  2106. return nullptr;
  2107. // Check if MI has any non-dead defs or physreg uses. This also detects
  2108. // predicated instructions which will be reading CPSR.
  2109. for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 1)) {
  2110. // Reject frame index operands, PEI can't handle the predicated pseudos.
  2111. if (MO.isFI() || MO.isCPI() || MO.isJTI())
  2112. return nullptr;
  2113. if (!MO.isReg())
  2114. continue;
  2115. // MI can't have any tied operands, that would conflict with predication.
  2116. if (MO.isTied())
  2117. return nullptr;
  2118. if (MO.getReg().isPhysical())
  2119. return nullptr;
  2120. if (MO.isDef() && !MO.isDead())
  2121. return nullptr;
  2122. }
  2123. bool DontMoveAcrossStores = true;
  2124. if (!MI->isSafeToMove(/* AliasAnalysis = */ nullptr, DontMoveAcrossStores))
  2125. return nullptr;
  2126. return MI;
  2127. }
  2128. bool ARMBaseInstrInfo::analyzeSelect(const MachineInstr &MI,
  2129. SmallVectorImpl<MachineOperand> &Cond,
  2130. unsigned &TrueOp, unsigned &FalseOp,
  2131. bool &Optimizable) const {
  2132. assert((MI.getOpcode() == ARM::MOVCCr || MI.getOpcode() == ARM::t2MOVCCr) &&
  2133. "Unknown select instruction");
  2134. // MOVCC operands:
  2135. // 0: Def.
  2136. // 1: True use.
  2137. // 2: False use.
  2138. // 3: Condition code.
  2139. // 4: CPSR use.
  2140. TrueOp = 1;
  2141. FalseOp = 2;
  2142. Cond.push_back(MI.getOperand(3));
  2143. Cond.push_back(MI.getOperand(4));
  2144. // We can always fold a def.
  2145. Optimizable = true;
  2146. return false;
  2147. }
  2148. MachineInstr *
  2149. ARMBaseInstrInfo::optimizeSelect(MachineInstr &MI,
  2150. SmallPtrSetImpl<MachineInstr *> &SeenMIs,
  2151. bool PreferFalse) const {
  2152. assert((MI.getOpcode() == ARM::MOVCCr || MI.getOpcode() == ARM::t2MOVCCr) &&
  2153. "Unknown select instruction");
  2154. MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
  2155. MachineInstr *DefMI = canFoldIntoMOVCC(MI.getOperand(2).getReg(), MRI, this);
  2156. bool Invert = !DefMI;
  2157. if (!DefMI)
  2158. DefMI = canFoldIntoMOVCC(MI.getOperand(1).getReg(), MRI, this);
  2159. if (!DefMI)
  2160. return nullptr;
  2161. // Find new register class to use.
  2162. MachineOperand FalseReg = MI.getOperand(Invert ? 2 : 1);
  2163. MachineOperand TrueReg = MI.getOperand(Invert ? 1 : 2);
  2164. Register DestReg = MI.getOperand(0).getReg();
  2165. const TargetRegisterClass *FalseClass = MRI.getRegClass(FalseReg.getReg());
  2166. const TargetRegisterClass *TrueClass = MRI.getRegClass(TrueReg.getReg());
  2167. if (!MRI.constrainRegClass(DestReg, FalseClass))
  2168. return nullptr;
  2169. if (!MRI.constrainRegClass(DestReg, TrueClass))
  2170. return nullptr;
  2171. // Create a new predicated version of DefMI.
  2172. // Rfalse is the first use.
  2173. MachineInstrBuilder NewMI =
  2174. BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), DefMI->getDesc(), DestReg);
  2175. // Copy all the DefMI operands, excluding its (null) predicate.
  2176. const MCInstrDesc &DefDesc = DefMI->getDesc();
  2177. for (unsigned i = 1, e = DefDesc.getNumOperands();
  2178. i != e && !DefDesc.operands()[i].isPredicate(); ++i)
  2179. NewMI.add(DefMI->getOperand(i));
  2180. unsigned CondCode = MI.getOperand(3).getImm();
  2181. if (Invert)
  2182. NewMI.addImm(ARMCC::getOppositeCondition(ARMCC::CondCodes(CondCode)));
  2183. else
  2184. NewMI.addImm(CondCode);
  2185. NewMI.add(MI.getOperand(4));
  2186. // DefMI is not the -S version that sets CPSR, so add an optional %noreg.
  2187. if (NewMI->hasOptionalDef())
  2188. NewMI.add(condCodeOp());
  2189. // The output register value when the predicate is false is an implicit
  2190. // register operand tied to the first def.
  2191. // The tie makes the register allocator ensure the FalseReg is allocated the
  2192. // same register as operand 0.
  2193. FalseReg.setImplicit();
  2194. NewMI.add(FalseReg);
  2195. NewMI->tieOperands(0, NewMI->getNumOperands() - 1);
  2196. // Update SeenMIs set: register newly created MI and erase removed DefMI.
  2197. SeenMIs.insert(NewMI);
  2198. SeenMIs.erase(DefMI);
  2199. // If MI is inside a loop, and DefMI is outside the loop, then kill flags on
  2200. // DefMI would be invalid when tranferred inside the loop. Checking for a
  2201. // loop is expensive, but at least remove kill flags if they are in different
  2202. // BBs.
  2203. if (DefMI->getParent() != MI.getParent())
  2204. NewMI->clearKillInfo();
  2205. // The caller will erase MI, but not DefMI.
  2206. DefMI->eraseFromParent();
  2207. return NewMI;
  2208. }
  2209. /// Map pseudo instructions that imply an 'S' bit onto real opcodes. Whether the
  2210. /// instruction is encoded with an 'S' bit is determined by the optional CPSR
  2211. /// def operand.
  2212. ///
  2213. /// This will go away once we can teach tblgen how to set the optional CPSR def
  2214. /// operand itself.
  2215. struct AddSubFlagsOpcodePair {
  2216. uint16_t PseudoOpc;
  2217. uint16_t MachineOpc;
  2218. };
  2219. static const AddSubFlagsOpcodePair AddSubFlagsOpcodeMap[] = {
  2220. {ARM::ADDSri, ARM::ADDri},
  2221. {ARM::ADDSrr, ARM::ADDrr},
  2222. {ARM::ADDSrsi, ARM::ADDrsi},
  2223. {ARM::ADDSrsr, ARM::ADDrsr},
  2224. {ARM::SUBSri, ARM::SUBri},
  2225. {ARM::SUBSrr, ARM::SUBrr},
  2226. {ARM::SUBSrsi, ARM::SUBrsi},
  2227. {ARM::SUBSrsr, ARM::SUBrsr},
  2228. {ARM::RSBSri, ARM::RSBri},
  2229. {ARM::RSBSrsi, ARM::RSBrsi},
  2230. {ARM::RSBSrsr, ARM::RSBrsr},
  2231. {ARM::tADDSi3, ARM::tADDi3},
  2232. {ARM::tADDSi8, ARM::tADDi8},
  2233. {ARM::tADDSrr, ARM::tADDrr},
  2234. {ARM::tADCS, ARM::tADC},
  2235. {ARM::tSUBSi3, ARM::tSUBi3},
  2236. {ARM::tSUBSi8, ARM::tSUBi8},
  2237. {ARM::tSUBSrr, ARM::tSUBrr},
  2238. {ARM::tSBCS, ARM::tSBC},
  2239. {ARM::tRSBS, ARM::tRSB},
  2240. {ARM::tLSLSri, ARM::tLSLri},
  2241. {ARM::t2ADDSri, ARM::t2ADDri},
  2242. {ARM::t2ADDSrr, ARM::t2ADDrr},
  2243. {ARM::t2ADDSrs, ARM::t2ADDrs},
  2244. {ARM::t2SUBSri, ARM::t2SUBri},
  2245. {ARM::t2SUBSrr, ARM::t2SUBrr},
  2246. {ARM::t2SUBSrs, ARM::t2SUBrs},
  2247. {ARM::t2RSBSri, ARM::t2RSBri},
  2248. {ARM::t2RSBSrs, ARM::t2RSBrs},
  2249. };
  2250. unsigned llvm::convertAddSubFlagsOpcode(unsigned OldOpc) {
  2251. for (const auto &Entry : AddSubFlagsOpcodeMap)
  2252. if (OldOpc == Entry.PseudoOpc)
  2253. return Entry.MachineOpc;
  2254. return 0;
  2255. }
  2256. void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB,
  2257. MachineBasicBlock::iterator &MBBI,
  2258. const DebugLoc &dl, Register DestReg,
  2259. Register BaseReg, int NumBytes,
  2260. ARMCC::CondCodes Pred, Register PredReg,
  2261. const ARMBaseInstrInfo &TII,
  2262. unsigned MIFlags) {
  2263. if (NumBytes == 0 && DestReg != BaseReg) {
  2264. BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), DestReg)
  2265. .addReg(BaseReg, RegState::Kill)
  2266. .add(predOps(Pred, PredReg))
  2267. .add(condCodeOp())
  2268. .setMIFlags(MIFlags);
  2269. return;
  2270. }
  2271. bool isSub = NumBytes < 0;
  2272. if (isSub) NumBytes = -NumBytes;
  2273. while (NumBytes) {
  2274. unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
  2275. unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
  2276. assert(ThisVal && "Didn't extract field correctly");
  2277. // We will handle these bits from offset, clear them.
  2278. NumBytes &= ~ThisVal;
  2279. assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?");
  2280. // Build the new ADD / SUB.
  2281. unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri;
  2282. BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg)
  2283. .addReg(BaseReg, RegState::Kill)
  2284. .addImm(ThisVal)
  2285. .add(predOps(Pred, PredReg))
  2286. .add(condCodeOp())
  2287. .setMIFlags(MIFlags);
  2288. BaseReg = DestReg;
  2289. }
  2290. }
  2291. bool llvm::tryFoldSPUpdateIntoPushPop(const ARMSubtarget &Subtarget,
  2292. MachineFunction &MF, MachineInstr *MI,
  2293. unsigned NumBytes) {
  2294. // This optimisation potentially adds lots of load and store
  2295. // micro-operations, it's only really a great benefit to code-size.
  2296. if (!Subtarget.hasMinSize())
  2297. return false;
  2298. // If only one register is pushed/popped, LLVM can use an LDR/STR
  2299. // instead. We can't modify those so make sure we're dealing with an
  2300. // instruction we understand.
  2301. bool IsPop = isPopOpcode(MI->getOpcode());
  2302. bool IsPush = isPushOpcode(MI->getOpcode());
  2303. if (!IsPush && !IsPop)
  2304. return false;
  2305. bool IsVFPPushPop = MI->getOpcode() == ARM::VSTMDDB_UPD ||
  2306. MI->getOpcode() == ARM::VLDMDIA_UPD;
  2307. bool IsT1PushPop = MI->getOpcode() == ARM::tPUSH ||
  2308. MI->getOpcode() == ARM::tPOP ||
  2309. MI->getOpcode() == ARM::tPOP_RET;
  2310. assert((IsT1PushPop || (MI->getOperand(0).getReg() == ARM::SP &&
  2311. MI->getOperand(1).getReg() == ARM::SP)) &&
  2312. "trying to fold sp update into non-sp-updating push/pop");
  2313. // The VFP push & pop act on D-registers, so we can only fold an adjustment
  2314. // by a multiple of 8 bytes in correctly. Similarly rN is 4-bytes. Don't try
  2315. // if this is violated.
  2316. if (NumBytes % (IsVFPPushPop ? 8 : 4) != 0)
  2317. return false;
  2318. // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
  2319. // pred) so the list starts at 4. Thumb1 starts after the predicate.
  2320. int RegListIdx = IsT1PushPop ? 2 : 4;
  2321. // Calculate the space we'll need in terms of registers.
  2322. unsigned RegsNeeded;
  2323. const TargetRegisterClass *RegClass;
  2324. if (IsVFPPushPop) {
  2325. RegsNeeded = NumBytes / 8;
  2326. RegClass = &ARM::DPRRegClass;
  2327. } else {
  2328. RegsNeeded = NumBytes / 4;
  2329. RegClass = &ARM::GPRRegClass;
  2330. }
  2331. // We're going to have to strip all list operands off before
  2332. // re-adding them since the order matters, so save the existing ones
  2333. // for later.
  2334. SmallVector<MachineOperand, 4> RegList;
  2335. // We're also going to need the first register transferred by this
  2336. // instruction, which won't necessarily be the first register in the list.
  2337. unsigned FirstRegEnc = -1;
  2338. const TargetRegisterInfo *TRI = MF.getRegInfo().getTargetRegisterInfo();
  2339. for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i) {
  2340. MachineOperand &MO = MI->getOperand(i);
  2341. RegList.push_back(MO);
  2342. if (MO.isReg() && !MO.isImplicit() &&
  2343. TRI->getEncodingValue(MO.getReg()) < FirstRegEnc)
  2344. FirstRegEnc = TRI->getEncodingValue(MO.getReg());
  2345. }
  2346. const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
  2347. // Now try to find enough space in the reglist to allocate NumBytes.
  2348. for (int CurRegEnc = FirstRegEnc - 1; CurRegEnc >= 0 && RegsNeeded;
  2349. --CurRegEnc) {
  2350. unsigned CurReg = RegClass->getRegister(CurRegEnc);
  2351. if (IsT1PushPop && CurRegEnc > TRI->getEncodingValue(ARM::R7))
  2352. continue;
  2353. if (!IsPop) {
  2354. // Pushing any register is completely harmless, mark the register involved
  2355. // as undef since we don't care about its value and must not restore it
  2356. // during stack unwinding.
  2357. RegList.push_back(MachineOperand::CreateReg(CurReg, false, false,
  2358. false, false, true));
  2359. --RegsNeeded;
  2360. continue;
  2361. }
  2362. // However, we can only pop an extra register if it's not live. For
  2363. // registers live within the function we might clobber a return value
  2364. // register; the other way a register can be live here is if it's
  2365. // callee-saved.
  2366. if (isCalleeSavedRegister(CurReg, CSRegs) ||
  2367. MI->getParent()->computeRegisterLiveness(TRI, CurReg, MI) !=
  2368. MachineBasicBlock::LQR_Dead) {
  2369. // VFP pops don't allow holes in the register list, so any skip is fatal
  2370. // for our transformation. GPR pops do, so we should just keep looking.
  2371. if (IsVFPPushPop)
  2372. return false;
  2373. else
  2374. continue;
  2375. }
  2376. // Mark the unimportant registers as <def,dead> in the POP.
  2377. RegList.push_back(MachineOperand::CreateReg(CurReg, true, false, false,
  2378. true));
  2379. --RegsNeeded;
  2380. }
  2381. if (RegsNeeded > 0)
  2382. return false;
  2383. // Finally we know we can profitably perform the optimisation so go
  2384. // ahead: strip all existing registers off and add them back again
  2385. // in the right order.
  2386. for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i)
  2387. MI->removeOperand(i);
  2388. // Add the complete list back in.
  2389. MachineInstrBuilder MIB(MF, &*MI);
  2390. for (const MachineOperand &MO : llvm::reverse(RegList))
  2391. MIB.add(MO);
  2392. return true;
  2393. }
  2394. bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
  2395. Register FrameReg, int &Offset,
  2396. const ARMBaseInstrInfo &TII) {
  2397. unsigned Opcode = MI.getOpcode();
  2398. const MCInstrDesc &Desc = MI.getDesc();
  2399. unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
  2400. bool isSub = false;
  2401. // Memory operands in inline assembly always use AddrMode2.
  2402. if (Opcode == ARM::INLINEASM || Opcode == ARM::INLINEASM_BR)
  2403. AddrMode = ARMII::AddrMode2;
  2404. if (Opcode == ARM::ADDri) {
  2405. Offset += MI.getOperand(FrameRegIdx+1).getImm();
  2406. if (Offset == 0) {
  2407. // Turn it into a move.
  2408. MI.setDesc(TII.get(ARM::MOVr));
  2409. MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
  2410. MI.removeOperand(FrameRegIdx+1);
  2411. Offset = 0;
  2412. return true;
  2413. } else if (Offset < 0) {
  2414. Offset = -Offset;
  2415. isSub = true;
  2416. MI.setDesc(TII.get(ARM::SUBri));
  2417. }
  2418. // Common case: small offset, fits into instruction.
  2419. if (ARM_AM::getSOImmVal(Offset) != -1) {
  2420. // Replace the FrameIndex with sp / fp
  2421. MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
  2422. MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset);
  2423. Offset = 0;
  2424. return true;
  2425. }
  2426. // Otherwise, pull as much of the immedidate into this ADDri/SUBri
  2427. // as possible.
  2428. unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
  2429. unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
  2430. // We will handle these bits from offset, clear them.
  2431. Offset &= ~ThisImmVal;
  2432. // Get the properly encoded SOImmVal field.
  2433. assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 &&
  2434. "Bit extraction didn't work?");
  2435. MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal);
  2436. } else {
  2437. unsigned ImmIdx = 0;
  2438. int InstrOffs = 0;
  2439. unsigned NumBits = 0;
  2440. unsigned Scale = 1;
  2441. switch (AddrMode) {
  2442. case ARMII::AddrMode_i12:
  2443. ImmIdx = FrameRegIdx + 1;
  2444. InstrOffs = MI.getOperand(ImmIdx).getImm();
  2445. NumBits = 12;
  2446. break;
  2447. case ARMII::AddrMode2:
  2448. ImmIdx = FrameRegIdx+2;
  2449. InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
  2450. if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
  2451. InstrOffs *= -1;
  2452. NumBits = 12;
  2453. break;
  2454. case ARMII::AddrMode3:
  2455. ImmIdx = FrameRegIdx+2;
  2456. InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
  2457. if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
  2458. InstrOffs *= -1;
  2459. NumBits = 8;
  2460. break;
  2461. case ARMII::AddrMode4:
  2462. case ARMII::AddrMode6:
  2463. // Can't fold any offset even if it's zero.
  2464. return false;
  2465. case ARMII::AddrMode5:
  2466. ImmIdx = FrameRegIdx+1;
  2467. InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
  2468. if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
  2469. InstrOffs *= -1;
  2470. NumBits = 8;
  2471. Scale = 4;
  2472. break;
  2473. case ARMII::AddrMode5FP16:
  2474. ImmIdx = FrameRegIdx+1;
  2475. InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
  2476. if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
  2477. InstrOffs *= -1;
  2478. NumBits = 8;
  2479. Scale = 2;
  2480. break;
  2481. case ARMII::AddrModeT2_i7:
  2482. case ARMII::AddrModeT2_i7s2:
  2483. case ARMII::AddrModeT2_i7s4:
  2484. ImmIdx = FrameRegIdx+1;
  2485. InstrOffs = MI.getOperand(ImmIdx).getImm();
  2486. NumBits = 7;
  2487. Scale = (AddrMode == ARMII::AddrModeT2_i7s2 ? 2 :
  2488. AddrMode == ARMII::AddrModeT2_i7s4 ? 4 : 1);
  2489. break;
  2490. default:
  2491. llvm_unreachable("Unsupported addressing mode!");
  2492. }
  2493. Offset += InstrOffs * Scale;
  2494. assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
  2495. if (Offset < 0) {
  2496. Offset = -Offset;
  2497. isSub = true;
  2498. }
  2499. // Attempt to fold address comp. if opcode has offset bits
  2500. if (NumBits > 0) {
  2501. // Common case: small offset, fits into instruction.
  2502. MachineOperand &ImmOp = MI.getOperand(ImmIdx);
  2503. int ImmedOffset = Offset / Scale;
  2504. unsigned Mask = (1 << NumBits) - 1;
  2505. if ((unsigned)Offset <= Mask * Scale) {
  2506. // Replace the FrameIndex with sp
  2507. MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
  2508. // FIXME: When addrmode2 goes away, this will simplify (like the
  2509. // T2 version), as the LDR.i12 versions don't need the encoding
  2510. // tricks for the offset value.
  2511. if (isSub) {
  2512. if (AddrMode == ARMII::AddrMode_i12)
  2513. ImmedOffset = -ImmedOffset;
  2514. else
  2515. ImmedOffset |= 1 << NumBits;
  2516. }
  2517. ImmOp.ChangeToImmediate(ImmedOffset);
  2518. Offset = 0;
  2519. return true;
  2520. }
  2521. // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
  2522. ImmedOffset = ImmedOffset & Mask;
  2523. if (isSub) {
  2524. if (AddrMode == ARMII::AddrMode_i12)
  2525. ImmedOffset = -ImmedOffset;
  2526. else
  2527. ImmedOffset |= 1 << NumBits;
  2528. }
  2529. ImmOp.ChangeToImmediate(ImmedOffset);
  2530. Offset &= ~(Mask*Scale);
  2531. }
  2532. }
  2533. Offset = (isSub) ? -Offset : Offset;
  2534. return Offset == 0;
  2535. }
  2536. /// analyzeCompare - For a comparison instruction, return the source registers
  2537. /// in SrcReg and SrcReg2 if having two register operands, and the value it
  2538. /// compares against in CmpValue. Return true if the comparison instruction
  2539. /// can be analyzed.
  2540. bool ARMBaseInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
  2541. Register &SrcReg2, int64_t &CmpMask,
  2542. int64_t &CmpValue) const {
  2543. switch (MI.getOpcode()) {
  2544. default: break;
  2545. case ARM::CMPri:
  2546. case ARM::t2CMPri:
  2547. case ARM::tCMPi8:
  2548. SrcReg = MI.getOperand(0).getReg();
  2549. SrcReg2 = 0;
  2550. CmpMask = ~0;
  2551. CmpValue = MI.getOperand(1).getImm();
  2552. return true;
  2553. case ARM::CMPrr:
  2554. case ARM::t2CMPrr:
  2555. case ARM::tCMPr:
  2556. SrcReg = MI.getOperand(0).getReg();
  2557. SrcReg2 = MI.getOperand(1).getReg();
  2558. CmpMask = ~0;
  2559. CmpValue = 0;
  2560. return true;
  2561. case ARM::TSTri:
  2562. case ARM::t2TSTri:
  2563. SrcReg = MI.getOperand(0).getReg();
  2564. SrcReg2 = 0;
  2565. CmpMask = MI.getOperand(1).getImm();
  2566. CmpValue = 0;
  2567. return true;
  2568. }
  2569. return false;
  2570. }
  2571. /// isSuitableForMask - Identify a suitable 'and' instruction that
  2572. /// operates on the given source register and applies the same mask
  2573. /// as a 'tst' instruction. Provide a limited look-through for copies.
  2574. /// When successful, MI will hold the found instruction.
  2575. static bool isSuitableForMask(MachineInstr *&MI, Register SrcReg,
  2576. int CmpMask, bool CommonUse) {
  2577. switch (MI->getOpcode()) {
  2578. case ARM::ANDri:
  2579. case ARM::t2ANDri:
  2580. if (CmpMask != MI->getOperand(2).getImm())
  2581. return false;
  2582. if (SrcReg == MI->getOperand(CommonUse ? 1 : 0).getReg())
  2583. return true;
  2584. break;
  2585. }
  2586. return false;
  2587. }
  2588. /// getCmpToAddCondition - assume the flags are set by CMP(a,b), return
  2589. /// the condition code if we modify the instructions such that flags are
  2590. /// set by ADD(a,b,X).
  2591. inline static ARMCC::CondCodes getCmpToAddCondition(ARMCC::CondCodes CC) {
  2592. switch (CC) {
  2593. default: return ARMCC::AL;
  2594. case ARMCC::HS: return ARMCC::LO;
  2595. case ARMCC::LO: return ARMCC::HS;
  2596. case ARMCC::VS: return ARMCC::VS;
  2597. case ARMCC::VC: return ARMCC::VC;
  2598. }
  2599. }
  2600. /// isRedundantFlagInstr - check whether the first instruction, whose only
  2601. /// purpose is to update flags, can be made redundant.
  2602. /// CMPrr can be made redundant by SUBrr if the operands are the same.
  2603. /// CMPri can be made redundant by SUBri if the operands are the same.
  2604. /// CMPrr(r0, r1) can be made redundant by ADDr[ri](r0, r1, X).
  2605. /// This function can be extended later on.
  2606. inline static bool isRedundantFlagInstr(const MachineInstr *CmpI,
  2607. Register SrcReg, Register SrcReg2,
  2608. int64_t ImmValue,
  2609. const MachineInstr *OI,
  2610. bool &IsThumb1) {
  2611. if ((CmpI->getOpcode() == ARM::CMPrr || CmpI->getOpcode() == ARM::t2CMPrr) &&
  2612. (OI->getOpcode() == ARM::SUBrr || OI->getOpcode() == ARM::t2SUBrr) &&
  2613. ((OI->getOperand(1).getReg() == SrcReg &&
  2614. OI->getOperand(2).getReg() == SrcReg2) ||
  2615. (OI->getOperand(1).getReg() == SrcReg2 &&
  2616. OI->getOperand(2).getReg() == SrcReg))) {
  2617. IsThumb1 = false;
  2618. return true;
  2619. }
  2620. if (CmpI->getOpcode() == ARM::tCMPr && OI->getOpcode() == ARM::tSUBrr &&
  2621. ((OI->getOperand(2).getReg() == SrcReg &&
  2622. OI->getOperand(3).getReg() == SrcReg2) ||
  2623. (OI->getOperand(2).getReg() == SrcReg2 &&
  2624. OI->getOperand(3).getReg() == SrcReg))) {
  2625. IsThumb1 = true;
  2626. return true;
  2627. }
  2628. if ((CmpI->getOpcode() == ARM::CMPri || CmpI->getOpcode() == ARM::t2CMPri) &&
  2629. (OI->getOpcode() == ARM::SUBri || OI->getOpcode() == ARM::t2SUBri) &&
  2630. OI->getOperand(1).getReg() == SrcReg &&
  2631. OI->getOperand(2).getImm() == ImmValue) {
  2632. IsThumb1 = false;
  2633. return true;
  2634. }
  2635. if (CmpI->getOpcode() == ARM::tCMPi8 &&
  2636. (OI->getOpcode() == ARM::tSUBi8 || OI->getOpcode() == ARM::tSUBi3) &&
  2637. OI->getOperand(2).getReg() == SrcReg &&
  2638. OI->getOperand(3).getImm() == ImmValue) {
  2639. IsThumb1 = true;
  2640. return true;
  2641. }
  2642. if ((CmpI->getOpcode() == ARM::CMPrr || CmpI->getOpcode() == ARM::t2CMPrr) &&
  2643. (OI->getOpcode() == ARM::ADDrr || OI->getOpcode() == ARM::t2ADDrr ||
  2644. OI->getOpcode() == ARM::ADDri || OI->getOpcode() == ARM::t2ADDri) &&
  2645. OI->getOperand(0).isReg() && OI->getOperand(1).isReg() &&
  2646. OI->getOperand(0).getReg() == SrcReg &&
  2647. OI->getOperand(1).getReg() == SrcReg2) {
  2648. IsThumb1 = false;
  2649. return true;
  2650. }
  2651. if (CmpI->getOpcode() == ARM::tCMPr &&
  2652. (OI->getOpcode() == ARM::tADDi3 || OI->getOpcode() == ARM::tADDi8 ||
  2653. OI->getOpcode() == ARM::tADDrr) &&
  2654. OI->getOperand(0).getReg() == SrcReg &&
  2655. OI->getOperand(2).getReg() == SrcReg2) {
  2656. IsThumb1 = true;
  2657. return true;
  2658. }
  2659. return false;
  2660. }
  2661. static bool isOptimizeCompareCandidate(MachineInstr *MI, bool &IsThumb1) {
  2662. switch (MI->getOpcode()) {
  2663. default: return false;
  2664. case ARM::tLSLri:
  2665. case ARM::tLSRri:
  2666. case ARM::tLSLrr:
  2667. case ARM::tLSRrr:
  2668. case ARM::tSUBrr:
  2669. case ARM::tADDrr:
  2670. case ARM::tADDi3:
  2671. case ARM::tADDi8:
  2672. case ARM::tSUBi3:
  2673. case ARM::tSUBi8:
  2674. case ARM::tMUL:
  2675. case ARM::tADC:
  2676. case ARM::tSBC:
  2677. case ARM::tRSB:
  2678. case ARM::tAND:
  2679. case ARM::tORR:
  2680. case ARM::tEOR:
  2681. case ARM::tBIC:
  2682. case ARM::tMVN:
  2683. case ARM::tASRri:
  2684. case ARM::tASRrr:
  2685. case ARM::tROR:
  2686. IsThumb1 = true;
  2687. [[fallthrough]];
  2688. case ARM::RSBrr:
  2689. case ARM::RSBri:
  2690. case ARM::RSCrr:
  2691. case ARM::RSCri:
  2692. case ARM::ADDrr:
  2693. case ARM::ADDri:
  2694. case ARM::ADCrr:
  2695. case ARM::ADCri:
  2696. case ARM::SUBrr:
  2697. case ARM::SUBri:
  2698. case ARM::SBCrr:
  2699. case ARM::SBCri:
  2700. case ARM::t2RSBri:
  2701. case ARM::t2ADDrr:
  2702. case ARM::t2ADDri:
  2703. case ARM::t2ADCrr:
  2704. case ARM::t2ADCri:
  2705. case ARM::t2SUBrr:
  2706. case ARM::t2SUBri:
  2707. case ARM::t2SBCrr:
  2708. case ARM::t2SBCri:
  2709. case ARM::ANDrr:
  2710. case ARM::ANDri:
  2711. case ARM::ANDrsr:
  2712. case ARM::ANDrsi:
  2713. case ARM::t2ANDrr:
  2714. case ARM::t2ANDri:
  2715. case ARM::t2ANDrs:
  2716. case ARM::ORRrr:
  2717. case ARM::ORRri:
  2718. case ARM::ORRrsr:
  2719. case ARM::ORRrsi:
  2720. case ARM::t2ORRrr:
  2721. case ARM::t2ORRri:
  2722. case ARM::t2ORRrs:
  2723. case ARM::EORrr:
  2724. case ARM::EORri:
  2725. case ARM::EORrsr:
  2726. case ARM::EORrsi:
  2727. case ARM::t2EORrr:
  2728. case ARM::t2EORri:
  2729. case ARM::t2EORrs:
  2730. case ARM::BICri:
  2731. case ARM::BICrr:
  2732. case ARM::BICrsi:
  2733. case ARM::BICrsr:
  2734. case ARM::t2BICri:
  2735. case ARM::t2BICrr:
  2736. case ARM::t2BICrs:
  2737. case ARM::t2LSRri:
  2738. case ARM::t2LSRrr:
  2739. case ARM::t2LSLri:
  2740. case ARM::t2LSLrr:
  2741. case ARM::MOVsr:
  2742. case ARM::MOVsi:
  2743. return true;
  2744. }
  2745. }
  2746. /// optimizeCompareInstr - Convert the instruction supplying the argument to the
  2747. /// comparison into one that sets the zero bit in the flags register;
  2748. /// Remove a redundant Compare instruction if an earlier instruction can set the
  2749. /// flags in the same way as Compare.
  2750. /// E.g. SUBrr(r1,r2) and CMPrr(r1,r2). We also handle the case where two
  2751. /// operands are swapped: SUBrr(r1,r2) and CMPrr(r2,r1), by updating the
  2752. /// condition code of instructions which use the flags.
  2753. bool ARMBaseInstrInfo::optimizeCompareInstr(
  2754. MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int64_t CmpMask,
  2755. int64_t CmpValue, const MachineRegisterInfo *MRI) const {
  2756. // Get the unique definition of SrcReg.
  2757. MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
  2758. if (!MI) return false;
  2759. // Masked compares sometimes use the same register as the corresponding 'and'.
  2760. if (CmpMask != ~0) {
  2761. if (!isSuitableForMask(MI, SrcReg, CmpMask, false) || isPredicated(*MI)) {
  2762. MI = nullptr;
  2763. for (MachineRegisterInfo::use_instr_iterator
  2764. UI = MRI->use_instr_begin(SrcReg), UE = MRI->use_instr_end();
  2765. UI != UE; ++UI) {
  2766. if (UI->getParent() != CmpInstr.getParent())
  2767. continue;
  2768. MachineInstr *PotentialAND = &*UI;
  2769. if (!isSuitableForMask(PotentialAND, SrcReg, CmpMask, true) ||
  2770. isPredicated(*PotentialAND))
  2771. continue;
  2772. MI = PotentialAND;
  2773. break;
  2774. }
  2775. if (!MI) return false;
  2776. }
  2777. }
  2778. // Get ready to iterate backward from CmpInstr.
  2779. MachineBasicBlock::iterator I = CmpInstr, E = MI,
  2780. B = CmpInstr.getParent()->begin();
  2781. // Early exit if CmpInstr is at the beginning of the BB.
  2782. if (I == B) return false;
  2783. // There are two possible candidates which can be changed to set CPSR:
  2784. // One is MI, the other is a SUB or ADD instruction.
  2785. // For CMPrr(r1,r2), we are looking for SUB(r1,r2), SUB(r2,r1), or
  2786. // ADDr[ri](r1, r2, X).
  2787. // For CMPri(r1, CmpValue), we are looking for SUBri(r1, CmpValue).
  2788. MachineInstr *SubAdd = nullptr;
  2789. if (SrcReg2 != 0)
  2790. // MI is not a candidate for CMPrr.
  2791. MI = nullptr;
  2792. else if (MI->getParent() != CmpInstr.getParent() || CmpValue != 0) {
  2793. // Conservatively refuse to convert an instruction which isn't in the same
  2794. // BB as the comparison.
  2795. // For CMPri w/ CmpValue != 0, a SubAdd may still be a candidate.
  2796. // Thus we cannot return here.
  2797. if (CmpInstr.getOpcode() == ARM::CMPri ||
  2798. CmpInstr.getOpcode() == ARM::t2CMPri ||
  2799. CmpInstr.getOpcode() == ARM::tCMPi8)
  2800. MI = nullptr;
  2801. else
  2802. return false;
  2803. }
  2804. bool IsThumb1 = false;
  2805. if (MI && !isOptimizeCompareCandidate(MI, IsThumb1))
  2806. return false;
  2807. // We also want to do this peephole for cases like this: if (a*b == 0),
  2808. // and optimise away the CMP instruction from the generated code sequence:
  2809. // MULS, MOVS, MOVS, CMP. Here the MOVS instructions load the boolean values
  2810. // resulting from the select instruction, but these MOVS instructions for
  2811. // Thumb1 (V6M) are flag setting and are thus preventing this optimisation.
  2812. // However, if we only have MOVS instructions in between the CMP and the
  2813. // other instruction (the MULS in this example), then the CPSR is dead so we
  2814. // can safely reorder the sequence into: MOVS, MOVS, MULS, CMP. We do this
  2815. // reordering and then continue the analysis hoping we can eliminate the
  2816. // CMP. This peephole works on the vregs, so is still in SSA form. As a
  2817. // consequence, the movs won't redefine/kill the MUL operands which would
  2818. // make this reordering illegal.
  2819. const TargetRegisterInfo *TRI = &getRegisterInfo();
  2820. if (MI && IsThumb1) {
  2821. --I;
  2822. if (I != E && !MI->readsRegister(ARM::CPSR, TRI)) {
  2823. bool CanReorder = true;
  2824. for (; I != E; --I) {
  2825. if (I->getOpcode() != ARM::tMOVi8) {
  2826. CanReorder = false;
  2827. break;
  2828. }
  2829. }
  2830. if (CanReorder) {
  2831. MI = MI->removeFromParent();
  2832. E = CmpInstr;
  2833. CmpInstr.getParent()->insert(E, MI);
  2834. }
  2835. }
  2836. I = CmpInstr;
  2837. E = MI;
  2838. }
  2839. // Check that CPSR isn't set between the comparison instruction and the one we
  2840. // want to change. At the same time, search for SubAdd.
  2841. bool SubAddIsThumb1 = false;
  2842. do {
  2843. const MachineInstr &Instr = *--I;
  2844. // Check whether CmpInstr can be made redundant by the current instruction.
  2845. if (isRedundantFlagInstr(&CmpInstr, SrcReg, SrcReg2, CmpValue, &Instr,
  2846. SubAddIsThumb1)) {
  2847. SubAdd = &*I;
  2848. break;
  2849. }
  2850. // Allow E (which was initially MI) to be SubAdd but do not search before E.
  2851. if (I == E)
  2852. break;
  2853. if (Instr.modifiesRegister(ARM::CPSR, TRI) ||
  2854. Instr.readsRegister(ARM::CPSR, TRI))
  2855. // This instruction modifies or uses CPSR after the one we want to
  2856. // change. We can't do this transformation.
  2857. return false;
  2858. if (I == B) {
  2859. // In some cases, we scan the use-list of an instruction for an AND;
  2860. // that AND is in the same BB, but may not be scheduled before the
  2861. // corresponding TST. In that case, bail out.
  2862. //
  2863. // FIXME: We could try to reschedule the AND.
  2864. return false;
  2865. }
  2866. } while (true);
  2867. // Return false if no candidates exist.
  2868. if (!MI && !SubAdd)
  2869. return false;
  2870. // If we found a SubAdd, use it as it will be closer to the CMP
  2871. if (SubAdd) {
  2872. MI = SubAdd;
  2873. IsThumb1 = SubAddIsThumb1;
  2874. }
  2875. // We can't use a predicated instruction - it doesn't always write the flags.
  2876. if (isPredicated(*MI))
  2877. return false;
  2878. // Scan forward for the use of CPSR
  2879. // When checking against MI: if it's a conditional code that requires
  2880. // checking of the V bit or C bit, then this is not safe to do.
  2881. // It is safe to remove CmpInstr if CPSR is redefined or killed.
  2882. // If we are done with the basic block, we need to check whether CPSR is
  2883. // live-out.
  2884. SmallVector<std::pair<MachineOperand*, ARMCC::CondCodes>, 4>
  2885. OperandsToUpdate;
  2886. bool isSafe = false;
  2887. I = CmpInstr;
  2888. E = CmpInstr.getParent()->end();
  2889. while (!isSafe && ++I != E) {
  2890. const MachineInstr &Instr = *I;
  2891. for (unsigned IO = 0, EO = Instr.getNumOperands();
  2892. !isSafe && IO != EO; ++IO) {
  2893. const MachineOperand &MO = Instr.getOperand(IO);
  2894. if (MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) {
  2895. isSafe = true;
  2896. break;
  2897. }
  2898. if (!MO.isReg() || MO.getReg() != ARM::CPSR)
  2899. continue;
  2900. if (MO.isDef()) {
  2901. isSafe = true;
  2902. break;
  2903. }
  2904. // Condition code is after the operand before CPSR except for VSELs.
  2905. ARMCC::CondCodes CC;
  2906. bool IsInstrVSel = true;
  2907. switch (Instr.getOpcode()) {
  2908. default:
  2909. IsInstrVSel = false;
  2910. CC = (ARMCC::CondCodes)Instr.getOperand(IO - 1).getImm();
  2911. break;
  2912. case ARM::VSELEQD:
  2913. case ARM::VSELEQS:
  2914. case ARM::VSELEQH:
  2915. CC = ARMCC::EQ;
  2916. break;
  2917. case ARM::VSELGTD:
  2918. case ARM::VSELGTS:
  2919. case ARM::VSELGTH:
  2920. CC = ARMCC::GT;
  2921. break;
  2922. case ARM::VSELGED:
  2923. case ARM::VSELGES:
  2924. case ARM::VSELGEH:
  2925. CC = ARMCC::GE;
  2926. break;
  2927. case ARM::VSELVSD:
  2928. case ARM::VSELVSS:
  2929. case ARM::VSELVSH:
  2930. CC = ARMCC::VS;
  2931. break;
  2932. }
  2933. if (SubAdd) {
  2934. // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based
  2935. // on CMP needs to be updated to be based on SUB.
  2936. // If we have ADD(r1, r2, X) and CMP(r1, r2), the condition code also
  2937. // needs to be modified.
  2938. // Push the condition code operands to OperandsToUpdate.
  2939. // If it is safe to remove CmpInstr, the condition code of these
  2940. // operands will be modified.
  2941. unsigned Opc = SubAdd->getOpcode();
  2942. bool IsSub = Opc == ARM::SUBrr || Opc == ARM::t2SUBrr ||
  2943. Opc == ARM::SUBri || Opc == ARM::t2SUBri ||
  2944. Opc == ARM::tSUBrr || Opc == ARM::tSUBi3 ||
  2945. Opc == ARM::tSUBi8;
  2946. unsigned OpI = Opc != ARM::tSUBrr ? 1 : 2;
  2947. if (!IsSub ||
  2948. (SrcReg2 != 0 && SubAdd->getOperand(OpI).getReg() == SrcReg2 &&
  2949. SubAdd->getOperand(OpI + 1).getReg() == SrcReg)) {
  2950. // VSel doesn't support condition code update.
  2951. if (IsInstrVSel)
  2952. return false;
  2953. // Ensure we can swap the condition.
  2954. ARMCC::CondCodes NewCC = (IsSub ? getSwappedCondition(CC) : getCmpToAddCondition(CC));
  2955. if (NewCC == ARMCC::AL)
  2956. return false;
  2957. OperandsToUpdate.push_back(
  2958. std::make_pair(&((*I).getOperand(IO - 1)), NewCC));
  2959. }
  2960. } else {
  2961. // No SubAdd, so this is x = <op> y, z; cmp x, 0.
  2962. switch (CC) {
  2963. case ARMCC::EQ: // Z
  2964. case ARMCC::NE: // Z
  2965. case ARMCC::MI: // N
  2966. case ARMCC::PL: // N
  2967. case ARMCC::AL: // none
  2968. // CPSR can be used multiple times, we should continue.
  2969. break;
  2970. case ARMCC::HS: // C
  2971. case ARMCC::LO: // C
  2972. case ARMCC::VS: // V
  2973. case ARMCC::VC: // V
  2974. case ARMCC::HI: // C Z
  2975. case ARMCC::LS: // C Z
  2976. case ARMCC::GE: // N V
  2977. case ARMCC::LT: // N V
  2978. case ARMCC::GT: // Z N V
  2979. case ARMCC::LE: // Z N V
  2980. // The instruction uses the V bit or C bit which is not safe.
  2981. return false;
  2982. }
  2983. }
  2984. }
  2985. }
  2986. // If CPSR is not killed nor re-defined, we should check whether it is
  2987. // live-out. If it is live-out, do not optimize.
  2988. if (!isSafe) {
  2989. MachineBasicBlock *MBB = CmpInstr.getParent();
  2990. for (MachineBasicBlock *Succ : MBB->successors())
  2991. if (Succ->isLiveIn(ARM::CPSR))
  2992. return false;
  2993. }
  2994. // Toggle the optional operand to CPSR (if it exists - in Thumb1 we always
  2995. // set CPSR so this is represented as an explicit output)
  2996. if (!IsThumb1) {
  2997. unsigned CPSRRegNum = MI->getNumExplicitOperands() - 1;
  2998. MI->getOperand(CPSRRegNum).setReg(ARM::CPSR);
  2999. MI->getOperand(CPSRRegNum).setIsDef(true);
  3000. }
  3001. assert(!isPredicated(*MI) && "Can't use flags from predicated instruction");
  3002. CmpInstr.eraseFromParent();
  3003. // Modify the condition code of operands in OperandsToUpdate.
  3004. // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
  3005. // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
  3006. for (unsigned i = 0, e = OperandsToUpdate.size(); i < e; i++)
  3007. OperandsToUpdate[i].first->setImm(OperandsToUpdate[i].second);
  3008. MI->clearRegisterDeads(ARM::CPSR);
  3009. return true;
  3010. }
  3011. bool ARMBaseInstrInfo::shouldSink(const MachineInstr &MI) const {
  3012. // Do not sink MI if it might be used to optimize a redundant compare.
  3013. // We heuristically only look at the instruction immediately following MI to
  3014. // avoid potentially searching the entire basic block.
  3015. if (isPredicated(MI))
  3016. return true;
  3017. MachineBasicBlock::const_iterator Next = &MI;
  3018. ++Next;
  3019. Register SrcReg, SrcReg2;
  3020. int64_t CmpMask, CmpValue;
  3021. bool IsThumb1;
  3022. if (Next != MI.getParent()->end() &&
  3023. analyzeCompare(*Next, SrcReg, SrcReg2, CmpMask, CmpValue) &&
  3024. isRedundantFlagInstr(&*Next, SrcReg, SrcReg2, CmpValue, &MI, IsThumb1))
  3025. return false;
  3026. return true;
  3027. }
  3028. bool ARMBaseInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
  3029. Register Reg,
  3030. MachineRegisterInfo *MRI) const {
  3031. // Fold large immediates into add, sub, or, xor.
  3032. unsigned DefOpc = DefMI.getOpcode();
  3033. if (DefOpc != ARM::t2MOVi32imm && DefOpc != ARM::MOVi32imm)
  3034. return false;
  3035. if (!DefMI.getOperand(1).isImm())
  3036. // Could be t2MOVi32imm @xx
  3037. return false;
  3038. if (!MRI->hasOneNonDBGUse(Reg))
  3039. return false;
  3040. const MCInstrDesc &DefMCID = DefMI.getDesc();
  3041. if (DefMCID.hasOptionalDef()) {
  3042. unsigned NumOps = DefMCID.getNumOperands();
  3043. const MachineOperand &MO = DefMI.getOperand(NumOps - 1);
  3044. if (MO.getReg() == ARM::CPSR && !MO.isDead())
  3045. // If DefMI defines CPSR and it is not dead, it's obviously not safe
  3046. // to delete DefMI.
  3047. return false;
  3048. }
  3049. const MCInstrDesc &UseMCID = UseMI.getDesc();
  3050. if (UseMCID.hasOptionalDef()) {
  3051. unsigned NumOps = UseMCID.getNumOperands();
  3052. if (UseMI.getOperand(NumOps - 1).getReg() == ARM::CPSR)
  3053. // If the instruction sets the flag, do not attempt this optimization
  3054. // since it may change the semantics of the code.
  3055. return false;
  3056. }
  3057. unsigned UseOpc = UseMI.getOpcode();
  3058. unsigned NewUseOpc = 0;
  3059. uint32_t ImmVal = (uint32_t)DefMI.getOperand(1).getImm();
  3060. uint32_t SOImmValV1 = 0, SOImmValV2 = 0;
  3061. bool Commute = false;
  3062. switch (UseOpc) {
  3063. default: return false;
  3064. case ARM::SUBrr:
  3065. case ARM::ADDrr:
  3066. case ARM::ORRrr:
  3067. case ARM::EORrr:
  3068. case ARM::t2SUBrr:
  3069. case ARM::t2ADDrr:
  3070. case ARM::t2ORRrr:
  3071. case ARM::t2EORrr: {
  3072. Commute = UseMI.getOperand(2).getReg() != Reg;
  3073. switch (UseOpc) {
  3074. default: break;
  3075. case ARM::ADDrr:
  3076. case ARM::SUBrr:
  3077. if (UseOpc == ARM::SUBrr && Commute)
  3078. return false;
  3079. // ADD/SUB are special because they're essentially the same operation, so
  3080. // we can handle a larger range of immediates.
  3081. if (ARM_AM::isSOImmTwoPartVal(ImmVal))
  3082. NewUseOpc = UseOpc == ARM::ADDrr ? ARM::ADDri : ARM::SUBri;
  3083. else if (ARM_AM::isSOImmTwoPartVal(-ImmVal)) {
  3084. ImmVal = -ImmVal;
  3085. NewUseOpc = UseOpc == ARM::ADDrr ? ARM::SUBri : ARM::ADDri;
  3086. } else
  3087. return false;
  3088. SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
  3089. SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
  3090. break;
  3091. case ARM::ORRrr:
  3092. case ARM::EORrr:
  3093. if (!ARM_AM::isSOImmTwoPartVal(ImmVal))
  3094. return false;
  3095. SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
  3096. SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
  3097. switch (UseOpc) {
  3098. default: break;
  3099. case ARM::ORRrr: NewUseOpc = ARM::ORRri; break;
  3100. case ARM::EORrr: NewUseOpc = ARM::EORri; break;
  3101. }
  3102. break;
  3103. case ARM::t2ADDrr:
  3104. case ARM::t2SUBrr: {
  3105. if (UseOpc == ARM::t2SUBrr && Commute)
  3106. return false;
  3107. // ADD/SUB are special because they're essentially the same operation, so
  3108. // we can handle a larger range of immediates.
  3109. const bool ToSP = DefMI.getOperand(0).getReg() == ARM::SP;
  3110. const unsigned t2ADD = ToSP ? ARM::t2ADDspImm : ARM::t2ADDri;
  3111. const unsigned t2SUB = ToSP ? ARM::t2SUBspImm : ARM::t2SUBri;
  3112. if (ARM_AM::isT2SOImmTwoPartVal(ImmVal))
  3113. NewUseOpc = UseOpc == ARM::t2ADDrr ? t2ADD : t2SUB;
  3114. else if (ARM_AM::isT2SOImmTwoPartVal(-ImmVal)) {
  3115. ImmVal = -ImmVal;
  3116. NewUseOpc = UseOpc == ARM::t2ADDrr ? t2SUB : t2ADD;
  3117. } else
  3118. return false;
  3119. SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
  3120. SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
  3121. break;
  3122. }
  3123. case ARM::t2ORRrr:
  3124. case ARM::t2EORrr:
  3125. if (!ARM_AM::isT2SOImmTwoPartVal(ImmVal))
  3126. return false;
  3127. SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
  3128. SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
  3129. switch (UseOpc) {
  3130. default: break;
  3131. case ARM::t2ORRrr: NewUseOpc = ARM::t2ORRri; break;
  3132. case ARM::t2EORrr: NewUseOpc = ARM::t2EORri; break;
  3133. }
  3134. break;
  3135. }
  3136. }
  3137. }
  3138. unsigned OpIdx = Commute ? 2 : 1;
  3139. Register Reg1 = UseMI.getOperand(OpIdx).getReg();
  3140. bool isKill = UseMI.getOperand(OpIdx).isKill();
  3141. const TargetRegisterClass *TRC = MRI->getRegClass(Reg);
  3142. Register NewReg = MRI->createVirtualRegister(TRC);
  3143. BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(), get(NewUseOpc),
  3144. NewReg)
  3145. .addReg(Reg1, getKillRegState(isKill))
  3146. .addImm(SOImmValV1)
  3147. .add(predOps(ARMCC::AL))
  3148. .add(condCodeOp());
  3149. UseMI.setDesc(get(NewUseOpc));
  3150. UseMI.getOperand(1).setReg(NewReg);
  3151. UseMI.getOperand(1).setIsKill();
  3152. UseMI.getOperand(2).ChangeToImmediate(SOImmValV2);
  3153. DefMI.eraseFromParent();
  3154. // FIXME: t2ADDrr should be split, as different rulles apply when writing to SP.
  3155. // Just as t2ADDri, that was split to [t2ADDri, t2ADDspImm].
  3156. // Then the below code will not be needed, as the input/output register
  3157. // classes will be rgpr or gprSP.
  3158. // For now, we fix the UseMI operand explicitly here:
  3159. switch(NewUseOpc){
  3160. case ARM::t2ADDspImm:
  3161. case ARM::t2SUBspImm:
  3162. case ARM::t2ADDri:
  3163. case ARM::t2SUBri:
  3164. MRI->constrainRegClass(UseMI.getOperand(0).getReg(), TRC);
  3165. }
  3166. return true;
  3167. }
  3168. static unsigned getNumMicroOpsSwiftLdSt(const InstrItineraryData *ItinData,
  3169. const MachineInstr &MI) {
  3170. switch (MI.getOpcode()) {
  3171. default: {
  3172. const MCInstrDesc &Desc = MI.getDesc();
  3173. int UOps = ItinData->getNumMicroOps(Desc.getSchedClass());
  3174. assert(UOps >= 0 && "bad # UOps");
  3175. return UOps;
  3176. }
  3177. case ARM::LDRrs:
  3178. case ARM::LDRBrs:
  3179. case ARM::STRrs:
  3180. case ARM::STRBrs: {
  3181. unsigned ShOpVal = MI.getOperand(3).getImm();
  3182. bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
  3183. unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
  3184. if (!isSub &&
  3185. (ShImm == 0 ||
  3186. ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
  3187. ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
  3188. return 1;
  3189. return 2;
  3190. }
  3191. case ARM::LDRH:
  3192. case ARM::STRH: {
  3193. if (!MI.getOperand(2).getReg())
  3194. return 1;
  3195. unsigned ShOpVal = MI.getOperand(3).getImm();
  3196. bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
  3197. unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
  3198. if (!isSub &&
  3199. (ShImm == 0 ||
  3200. ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
  3201. ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
  3202. return 1;
  3203. return 2;
  3204. }
  3205. case ARM::LDRSB:
  3206. case ARM::LDRSH:
  3207. return (ARM_AM::getAM3Op(MI.getOperand(3).getImm()) == ARM_AM::sub) ? 3 : 2;
  3208. case ARM::LDRSB_POST:
  3209. case ARM::LDRSH_POST: {
  3210. Register Rt = MI.getOperand(0).getReg();
  3211. Register Rm = MI.getOperand(3).getReg();
  3212. return (Rt == Rm) ? 4 : 3;
  3213. }
  3214. case ARM::LDR_PRE_REG:
  3215. case ARM::LDRB_PRE_REG: {
  3216. Register Rt = MI.getOperand(0).getReg();
  3217. Register Rm = MI.getOperand(3).getReg();
  3218. if (Rt == Rm)
  3219. return 3;
  3220. unsigned ShOpVal = MI.getOperand(4).getImm();
  3221. bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
  3222. unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
  3223. if (!isSub &&
  3224. (ShImm == 0 ||
  3225. ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
  3226. ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
  3227. return 2;
  3228. return 3;
  3229. }
  3230. case ARM::STR_PRE_REG:
  3231. case ARM::STRB_PRE_REG: {
  3232. unsigned ShOpVal = MI.getOperand(4).getImm();
  3233. bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
  3234. unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
  3235. if (!isSub &&
  3236. (ShImm == 0 ||
  3237. ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
  3238. ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
  3239. return 2;
  3240. return 3;
  3241. }
  3242. case ARM::LDRH_PRE:
  3243. case ARM::STRH_PRE: {
  3244. Register Rt = MI.getOperand(0).getReg();
  3245. Register Rm = MI.getOperand(3).getReg();
  3246. if (!Rm)
  3247. return 2;
  3248. if (Rt == Rm)
  3249. return 3;
  3250. return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 3 : 2;
  3251. }
  3252. case ARM::LDR_POST_REG:
  3253. case ARM::LDRB_POST_REG:
  3254. case ARM::LDRH_POST: {
  3255. Register Rt = MI.getOperand(0).getReg();
  3256. Register Rm = MI.getOperand(3).getReg();
  3257. return (Rt == Rm) ? 3 : 2;
  3258. }
  3259. case ARM::LDR_PRE_IMM:
  3260. case ARM::LDRB_PRE_IMM:
  3261. case ARM::LDR_POST_IMM:
  3262. case ARM::LDRB_POST_IMM:
  3263. case ARM::STRB_POST_IMM:
  3264. case ARM::STRB_POST_REG:
  3265. case ARM::STRB_PRE_IMM:
  3266. case ARM::STRH_POST:
  3267. case ARM::STR_POST_IMM:
  3268. case ARM::STR_POST_REG:
  3269. case ARM::STR_PRE_IMM:
  3270. return 2;
  3271. case ARM::LDRSB_PRE:
  3272. case ARM::LDRSH_PRE: {
  3273. Register Rm = MI.getOperand(3).getReg();
  3274. if (Rm == 0)
  3275. return 3;
  3276. Register Rt = MI.getOperand(0).getReg();
  3277. if (Rt == Rm)
  3278. return 4;
  3279. unsigned ShOpVal = MI.getOperand(4).getImm();
  3280. bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
  3281. unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
  3282. if (!isSub &&
  3283. (ShImm == 0 ||
  3284. ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
  3285. ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
  3286. return 3;
  3287. return 4;
  3288. }
  3289. case ARM::LDRD: {
  3290. Register Rt = MI.getOperand(0).getReg();
  3291. Register Rn = MI.getOperand(2).getReg();
  3292. Register Rm = MI.getOperand(3).getReg();
  3293. if (Rm)
  3294. return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 4
  3295. : 3;
  3296. return (Rt == Rn) ? 3 : 2;
  3297. }
  3298. case ARM::STRD: {
  3299. Register Rm = MI.getOperand(3).getReg();
  3300. if (Rm)
  3301. return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 4
  3302. : 3;
  3303. return 2;
  3304. }
  3305. case ARM::LDRD_POST:
  3306. case ARM::t2LDRD_POST:
  3307. return 3;
  3308. case ARM::STRD_POST:
  3309. case ARM::t2STRD_POST:
  3310. return 4;
  3311. case ARM::LDRD_PRE: {
  3312. Register Rt = MI.getOperand(0).getReg();
  3313. Register Rn = MI.getOperand(3).getReg();
  3314. Register Rm = MI.getOperand(4).getReg();
  3315. if (Rm)
  3316. return (ARM_AM::getAM3Op(MI.getOperand(5).getImm()) == ARM_AM::sub) ? 5
  3317. : 4;
  3318. return (Rt == Rn) ? 4 : 3;
  3319. }
  3320. case ARM::t2LDRD_PRE: {
  3321. Register Rt = MI.getOperand(0).getReg();
  3322. Register Rn = MI.getOperand(3).getReg();
  3323. return (Rt == Rn) ? 4 : 3;
  3324. }
  3325. case ARM::STRD_PRE: {
  3326. Register Rm = MI.getOperand(4).getReg();
  3327. if (Rm)
  3328. return (ARM_AM::getAM3Op(MI.getOperand(5).getImm()) == ARM_AM::sub) ? 5
  3329. : 4;
  3330. return 3;
  3331. }
  3332. case ARM::t2STRD_PRE:
  3333. return 3;
  3334. case ARM::t2LDR_POST:
  3335. case ARM::t2LDRB_POST:
  3336. case ARM::t2LDRB_PRE:
  3337. case ARM::t2LDRSBi12:
  3338. case ARM::t2LDRSBi8:
  3339. case ARM::t2LDRSBpci:
  3340. case ARM::t2LDRSBs:
  3341. case ARM::t2LDRH_POST:
  3342. case ARM::t2LDRH_PRE:
  3343. case ARM::t2LDRSBT:
  3344. case ARM::t2LDRSB_POST:
  3345. case ARM::t2LDRSB_PRE:
  3346. case ARM::t2LDRSH_POST:
  3347. case ARM::t2LDRSH_PRE:
  3348. case ARM::t2LDRSHi12:
  3349. case ARM::t2LDRSHi8:
  3350. case ARM::t2LDRSHpci:
  3351. case ARM::t2LDRSHs:
  3352. return 2;
  3353. case ARM::t2LDRDi8: {
  3354. Register Rt = MI.getOperand(0).getReg();
  3355. Register Rn = MI.getOperand(2).getReg();
  3356. return (Rt == Rn) ? 3 : 2;
  3357. }
  3358. case ARM::t2STRB_POST:
  3359. case ARM::t2STRB_PRE:
  3360. case ARM::t2STRBs:
  3361. case ARM::t2STRDi8:
  3362. case ARM::t2STRH_POST:
  3363. case ARM::t2STRH_PRE:
  3364. case ARM::t2STRHs:
  3365. case ARM::t2STR_POST:
  3366. case ARM::t2STR_PRE:
  3367. case ARM::t2STRs:
  3368. return 2;
  3369. }
  3370. }
  3371. // Return the number of 32-bit words loaded by LDM or stored by STM. If this
  3372. // can't be easily determined return 0 (missing MachineMemOperand).
  3373. //
  3374. // FIXME: The current MachineInstr design does not support relying on machine
  3375. // mem operands to determine the width of a memory access. Instead, we expect
  3376. // the target to provide this information based on the instruction opcode and
  3377. // operands. However, using MachineMemOperand is the best solution now for
  3378. // two reasons:
  3379. //
  3380. // 1) getNumMicroOps tries to infer LDM memory width from the total number of MI
  3381. // operands. This is much more dangerous than using the MachineMemOperand
  3382. // sizes because CodeGen passes can insert/remove optional machine operands. In
  3383. // fact, it's totally incorrect for preRA passes and appears to be wrong for
  3384. // postRA passes as well.
  3385. //
  3386. // 2) getNumLDMAddresses is only used by the scheduling machine model and any
  3387. // machine model that calls this should handle the unknown (zero size) case.
  3388. //
  3389. // Long term, we should require a target hook that verifies MachineMemOperand
  3390. // sizes during MC lowering. That target hook should be local to MC lowering
  3391. // because we can't ensure that it is aware of other MI forms. Doing this will
  3392. // ensure that MachineMemOperands are correctly propagated through all passes.
  3393. unsigned ARMBaseInstrInfo::getNumLDMAddresses(const MachineInstr &MI) const {
  3394. unsigned Size = 0;
  3395. for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
  3396. E = MI.memoperands_end();
  3397. I != E; ++I) {
  3398. Size += (*I)->getSize();
  3399. }
  3400. // FIXME: The scheduler currently can't handle values larger than 16. But
  3401. // the values can actually go up to 32 for floating-point load/store
  3402. // multiple (VLDMIA etc.). Also, the way this code is reasoning about memory
  3403. // operations isn't right; we could end up with "extra" memory operands for
  3404. // various reasons, like tail merge merging two memory operations.
  3405. return std::min(Size / 4, 16U);
  3406. }
  3407. static unsigned getNumMicroOpsSingleIssuePlusExtras(unsigned Opc,
  3408. unsigned NumRegs) {
  3409. unsigned UOps = 1 + NumRegs; // 1 for address computation.
  3410. switch (Opc) {
  3411. default:
  3412. break;
  3413. case ARM::VLDMDIA_UPD:
  3414. case ARM::VLDMDDB_UPD:
  3415. case ARM::VLDMSIA_UPD:
  3416. case ARM::VLDMSDB_UPD:
  3417. case ARM::VSTMDIA_UPD:
  3418. case ARM::VSTMDDB_UPD:
  3419. case ARM::VSTMSIA_UPD:
  3420. case ARM::VSTMSDB_UPD:
  3421. case ARM::LDMIA_UPD:
  3422. case ARM::LDMDA_UPD:
  3423. case ARM::LDMDB_UPD:
  3424. case ARM::LDMIB_UPD:
  3425. case ARM::STMIA_UPD:
  3426. case ARM::STMDA_UPD:
  3427. case ARM::STMDB_UPD:
  3428. case ARM::STMIB_UPD:
  3429. case ARM::tLDMIA_UPD:
  3430. case ARM::tSTMIA_UPD:
  3431. case ARM::t2LDMIA_UPD:
  3432. case ARM::t2LDMDB_UPD:
  3433. case ARM::t2STMIA_UPD:
  3434. case ARM::t2STMDB_UPD:
  3435. ++UOps; // One for base register writeback.
  3436. break;
  3437. case ARM::LDMIA_RET:
  3438. case ARM::tPOP_RET:
  3439. case ARM::t2LDMIA_RET:
  3440. UOps += 2; // One for base reg wb, one for write to pc.
  3441. break;
  3442. }
  3443. return UOps;
  3444. }
  3445. unsigned ARMBaseInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
  3446. const MachineInstr &MI) const {
  3447. if (!ItinData || ItinData->isEmpty())
  3448. return 1;
  3449. const MCInstrDesc &Desc = MI.getDesc();
  3450. unsigned Class = Desc.getSchedClass();
  3451. int ItinUOps = ItinData->getNumMicroOps(Class);
  3452. if (ItinUOps >= 0) {
  3453. if (Subtarget.isSwift() && (Desc.mayLoad() || Desc.mayStore()))
  3454. return getNumMicroOpsSwiftLdSt(ItinData, MI);
  3455. return ItinUOps;
  3456. }
  3457. unsigned Opc = MI.getOpcode();
  3458. switch (Opc) {
  3459. default:
  3460. llvm_unreachable("Unexpected multi-uops instruction!");
  3461. case ARM::VLDMQIA:
  3462. case ARM::VSTMQIA:
  3463. return 2;
  3464. // The number of uOps for load / store multiple are determined by the number
  3465. // registers.
  3466. //
  3467. // On Cortex-A8, each pair of register loads / stores can be scheduled on the
  3468. // same cycle. The scheduling for the first load / store must be done
  3469. // separately by assuming the address is not 64-bit aligned.
  3470. //
  3471. // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address
  3472. // is not 64-bit aligned, then AGU would take an extra cycle. For VFP / NEON
  3473. // load / store multiple, the formula is (#reg / 2) + (#reg % 2) + 1.
  3474. case ARM::VLDMDIA:
  3475. case ARM::VLDMDIA_UPD:
  3476. case ARM::VLDMDDB_UPD:
  3477. case ARM::VLDMSIA:
  3478. case ARM::VLDMSIA_UPD:
  3479. case ARM::VLDMSDB_UPD:
  3480. case ARM::VSTMDIA:
  3481. case ARM::VSTMDIA_UPD:
  3482. case ARM::VSTMDDB_UPD:
  3483. case ARM::VSTMSIA:
  3484. case ARM::VSTMSIA_UPD:
  3485. case ARM::VSTMSDB_UPD: {
  3486. unsigned NumRegs = MI.getNumOperands() - Desc.getNumOperands();
  3487. return (NumRegs / 2) + (NumRegs % 2) + 1;
  3488. }
  3489. case ARM::LDMIA_RET:
  3490. case ARM::LDMIA:
  3491. case ARM::LDMDA:
  3492. case ARM::LDMDB:
  3493. case ARM::LDMIB:
  3494. case ARM::LDMIA_UPD:
  3495. case ARM::LDMDA_UPD:
  3496. case ARM::LDMDB_UPD:
  3497. case ARM::LDMIB_UPD:
  3498. case ARM::STMIA:
  3499. case ARM::STMDA:
  3500. case ARM::STMDB:
  3501. case ARM::STMIB:
  3502. case ARM::STMIA_UPD:
  3503. case ARM::STMDA_UPD:
  3504. case ARM::STMDB_UPD:
  3505. case ARM::STMIB_UPD:
  3506. case ARM::tLDMIA:
  3507. case ARM::tLDMIA_UPD:
  3508. case ARM::tSTMIA_UPD:
  3509. case ARM::tPOP_RET:
  3510. case ARM::tPOP:
  3511. case ARM::tPUSH:
  3512. case ARM::t2LDMIA_RET:
  3513. case ARM::t2LDMIA:
  3514. case ARM::t2LDMDB:
  3515. case ARM::t2LDMIA_UPD:
  3516. case ARM::t2LDMDB_UPD:
  3517. case ARM::t2STMIA:
  3518. case ARM::t2STMDB:
  3519. case ARM::t2STMIA_UPD:
  3520. case ARM::t2STMDB_UPD: {
  3521. unsigned NumRegs = MI.getNumOperands() - Desc.getNumOperands() + 1;
  3522. switch (Subtarget.getLdStMultipleTiming()) {
  3523. case ARMSubtarget::SingleIssuePlusExtras:
  3524. return getNumMicroOpsSingleIssuePlusExtras(Opc, NumRegs);
  3525. case ARMSubtarget::SingleIssue:
  3526. // Assume the worst.
  3527. return NumRegs;
  3528. case ARMSubtarget::DoubleIssue: {
  3529. if (NumRegs < 4)
  3530. return 2;
  3531. // 4 registers would be issued: 2, 2.
  3532. // 5 registers would be issued: 2, 2, 1.
  3533. unsigned UOps = (NumRegs / 2);
  3534. if (NumRegs % 2)
  3535. ++UOps;
  3536. return UOps;
  3537. }
  3538. case ARMSubtarget::DoubleIssueCheckUnalignedAccess: {
  3539. unsigned UOps = (NumRegs / 2);
  3540. // If there are odd number of registers or if it's not 64-bit aligned,
  3541. // then it takes an extra AGU (Address Generation Unit) cycle.
  3542. if ((NumRegs % 2) || !MI.hasOneMemOperand() ||
  3543. (*MI.memoperands_begin())->getAlign() < Align(8))
  3544. ++UOps;
  3545. return UOps;
  3546. }
  3547. }
  3548. }
  3549. }
  3550. llvm_unreachable("Didn't find the number of microops");
  3551. }
  3552. int
  3553. ARMBaseInstrInfo::getVLDMDefCycle(const InstrItineraryData *ItinData,
  3554. const MCInstrDesc &DefMCID,
  3555. unsigned DefClass,
  3556. unsigned DefIdx, unsigned DefAlign) const {
  3557. int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
  3558. if (RegNo <= 0)
  3559. // Def is the address writeback.
  3560. return ItinData->getOperandCycle(DefClass, DefIdx);
  3561. int DefCycle;
  3562. if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
  3563. // (regno / 2) + (regno % 2) + 1
  3564. DefCycle = RegNo / 2 + 1;
  3565. if (RegNo % 2)
  3566. ++DefCycle;
  3567. } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
  3568. DefCycle = RegNo;
  3569. bool isSLoad = false;
  3570. switch (DefMCID.getOpcode()) {
  3571. default: break;
  3572. case ARM::VLDMSIA:
  3573. case ARM::VLDMSIA_UPD:
  3574. case ARM::VLDMSDB_UPD:
  3575. isSLoad = true;
  3576. break;
  3577. }
  3578. // If there are odd number of 'S' registers or if it's not 64-bit aligned,
  3579. // then it takes an extra cycle.
  3580. if ((isSLoad && (RegNo % 2)) || DefAlign < 8)
  3581. ++DefCycle;
  3582. } else {
  3583. // Assume the worst.
  3584. DefCycle = RegNo + 2;
  3585. }
  3586. return DefCycle;
  3587. }
  3588. int
  3589. ARMBaseInstrInfo::getLDMDefCycle(const InstrItineraryData *ItinData,
  3590. const MCInstrDesc &DefMCID,
  3591. unsigned DefClass,
  3592. unsigned DefIdx, unsigned DefAlign) const {
  3593. int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
  3594. if (RegNo <= 0)
  3595. // Def is the address writeback.
  3596. return ItinData->getOperandCycle(DefClass, DefIdx);
  3597. int DefCycle;
  3598. if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
  3599. // 4 registers would be issued: 1, 2, 1.
  3600. // 5 registers would be issued: 1, 2, 2.
  3601. DefCycle = RegNo / 2;
  3602. if (DefCycle < 1)
  3603. DefCycle = 1;
  3604. // Result latency is issue cycle + 2: E2.
  3605. DefCycle += 2;
  3606. } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
  3607. DefCycle = (RegNo / 2);
  3608. // If there are odd number of registers or if it's not 64-bit aligned,
  3609. // then it takes an extra AGU (Address Generation Unit) cycle.
  3610. if ((RegNo % 2) || DefAlign < 8)
  3611. ++DefCycle;
  3612. // Result latency is AGU cycles + 2.
  3613. DefCycle += 2;
  3614. } else {
  3615. // Assume the worst.
  3616. DefCycle = RegNo + 2;
  3617. }
  3618. return DefCycle;
  3619. }
  3620. int
  3621. ARMBaseInstrInfo::getVSTMUseCycle(const InstrItineraryData *ItinData,
  3622. const MCInstrDesc &UseMCID,
  3623. unsigned UseClass,
  3624. unsigned UseIdx, unsigned UseAlign) const {
  3625. int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
  3626. if (RegNo <= 0)
  3627. return ItinData->getOperandCycle(UseClass, UseIdx);
  3628. int UseCycle;
  3629. if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
  3630. // (regno / 2) + (regno % 2) + 1
  3631. UseCycle = RegNo / 2 + 1;
  3632. if (RegNo % 2)
  3633. ++UseCycle;
  3634. } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
  3635. UseCycle = RegNo;
  3636. bool isSStore = false;
  3637. switch (UseMCID.getOpcode()) {
  3638. default: break;
  3639. case ARM::VSTMSIA:
  3640. case ARM::VSTMSIA_UPD:
  3641. case ARM::VSTMSDB_UPD:
  3642. isSStore = true;
  3643. break;
  3644. }
  3645. // If there are odd number of 'S' registers or if it's not 64-bit aligned,
  3646. // then it takes an extra cycle.
  3647. if ((isSStore && (RegNo % 2)) || UseAlign < 8)
  3648. ++UseCycle;
  3649. } else {
  3650. // Assume the worst.
  3651. UseCycle = RegNo + 2;
  3652. }
  3653. return UseCycle;
  3654. }
  3655. int
  3656. ARMBaseInstrInfo::getSTMUseCycle(const InstrItineraryData *ItinData,
  3657. const MCInstrDesc &UseMCID,
  3658. unsigned UseClass,
  3659. unsigned UseIdx, unsigned UseAlign) const {
  3660. int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
  3661. if (RegNo <= 0)
  3662. return ItinData->getOperandCycle(UseClass, UseIdx);
  3663. int UseCycle;
  3664. if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
  3665. UseCycle = RegNo / 2;
  3666. if (UseCycle < 2)
  3667. UseCycle = 2;
  3668. // Read in E3.
  3669. UseCycle += 2;
  3670. } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
  3671. UseCycle = (RegNo / 2);
  3672. // If there are odd number of registers or if it's not 64-bit aligned,
  3673. // then it takes an extra AGU (Address Generation Unit) cycle.
  3674. if ((RegNo % 2) || UseAlign < 8)
  3675. ++UseCycle;
  3676. } else {
  3677. // Assume the worst.
  3678. UseCycle = 1;
  3679. }
  3680. return UseCycle;
  3681. }
  3682. int
  3683. ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
  3684. const MCInstrDesc &DefMCID,
  3685. unsigned DefIdx, unsigned DefAlign,
  3686. const MCInstrDesc &UseMCID,
  3687. unsigned UseIdx, unsigned UseAlign) const {
  3688. unsigned DefClass = DefMCID.getSchedClass();
  3689. unsigned UseClass = UseMCID.getSchedClass();
  3690. if (DefIdx < DefMCID.getNumDefs() && UseIdx < UseMCID.getNumOperands())
  3691. return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
  3692. // This may be a def / use of a variable_ops instruction, the operand
  3693. // latency might be determinable dynamically. Let the target try to
  3694. // figure it out.
  3695. int DefCycle = -1;
  3696. bool LdmBypass = false;
  3697. switch (DefMCID.getOpcode()) {
  3698. default:
  3699. DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
  3700. break;
  3701. case ARM::VLDMDIA:
  3702. case ARM::VLDMDIA_UPD:
  3703. case ARM::VLDMDDB_UPD:
  3704. case ARM::VLDMSIA:
  3705. case ARM::VLDMSIA_UPD:
  3706. case ARM::VLDMSDB_UPD:
  3707. DefCycle = getVLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
  3708. break;
  3709. case ARM::LDMIA_RET:
  3710. case ARM::LDMIA:
  3711. case ARM::LDMDA:
  3712. case ARM::LDMDB:
  3713. case ARM::LDMIB:
  3714. case ARM::LDMIA_UPD:
  3715. case ARM::LDMDA_UPD:
  3716. case ARM::LDMDB_UPD:
  3717. case ARM::LDMIB_UPD:
  3718. case ARM::tLDMIA:
  3719. case ARM::tLDMIA_UPD:
  3720. case ARM::tPUSH:
  3721. case ARM::t2LDMIA_RET:
  3722. case ARM::t2LDMIA:
  3723. case ARM::t2LDMDB:
  3724. case ARM::t2LDMIA_UPD:
  3725. case ARM::t2LDMDB_UPD:
  3726. LdmBypass = true;
  3727. DefCycle = getLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
  3728. break;
  3729. }
  3730. if (DefCycle == -1)
  3731. // We can't seem to determine the result latency of the def, assume it's 2.
  3732. DefCycle = 2;
  3733. int UseCycle = -1;
  3734. switch (UseMCID.getOpcode()) {
  3735. default:
  3736. UseCycle = ItinData->getOperandCycle(UseClass, UseIdx);
  3737. break;
  3738. case ARM::VSTMDIA:
  3739. case ARM::VSTMDIA_UPD:
  3740. case ARM::VSTMDDB_UPD:
  3741. case ARM::VSTMSIA:
  3742. case ARM::VSTMSIA_UPD:
  3743. case ARM::VSTMSDB_UPD:
  3744. UseCycle = getVSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
  3745. break;
  3746. case ARM::STMIA:
  3747. case ARM::STMDA:
  3748. case ARM::STMDB:
  3749. case ARM::STMIB:
  3750. case ARM::STMIA_UPD:
  3751. case ARM::STMDA_UPD:
  3752. case ARM::STMDB_UPD:
  3753. case ARM::STMIB_UPD:
  3754. case ARM::tSTMIA_UPD:
  3755. case ARM::tPOP_RET:
  3756. case ARM::tPOP:
  3757. case ARM::t2STMIA:
  3758. case ARM::t2STMDB:
  3759. case ARM::t2STMIA_UPD:
  3760. case ARM::t2STMDB_UPD:
  3761. UseCycle = getSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
  3762. break;
  3763. }
  3764. if (UseCycle == -1)
  3765. // Assume it's read in the first stage.
  3766. UseCycle = 1;
  3767. UseCycle = DefCycle - UseCycle + 1;
  3768. if (UseCycle > 0) {
  3769. if (LdmBypass) {
  3770. // It's a variable_ops instruction so we can't use DefIdx here. Just use
  3771. // first def operand.
  3772. if (ItinData->hasPipelineForwarding(DefClass, DefMCID.getNumOperands()-1,
  3773. UseClass, UseIdx))
  3774. --UseCycle;
  3775. } else if (ItinData->hasPipelineForwarding(DefClass, DefIdx,
  3776. UseClass, UseIdx)) {
  3777. --UseCycle;
  3778. }
  3779. }
  3780. return UseCycle;
  3781. }
  3782. static const MachineInstr *getBundledDefMI(const TargetRegisterInfo *TRI,
  3783. const MachineInstr *MI, unsigned Reg,
  3784. unsigned &DefIdx, unsigned &Dist) {
  3785. Dist = 0;
  3786. MachineBasicBlock::const_iterator I = MI; ++I;
  3787. MachineBasicBlock::const_instr_iterator II = std::prev(I.getInstrIterator());
  3788. assert(II->isInsideBundle() && "Empty bundle?");
  3789. int Idx = -1;
  3790. while (II->isInsideBundle()) {
  3791. Idx = II->findRegisterDefOperandIdx(Reg, false, true, TRI);
  3792. if (Idx != -1)
  3793. break;
  3794. --II;
  3795. ++Dist;
  3796. }
  3797. assert(Idx != -1 && "Cannot find bundled definition!");
  3798. DefIdx = Idx;
  3799. return &*II;
  3800. }
  3801. static const MachineInstr *getBundledUseMI(const TargetRegisterInfo *TRI,
  3802. const MachineInstr &MI, unsigned Reg,
  3803. unsigned &UseIdx, unsigned &Dist) {
  3804. Dist = 0;
  3805. MachineBasicBlock::const_instr_iterator II = ++MI.getIterator();
  3806. assert(II->isInsideBundle() && "Empty bundle?");
  3807. MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
  3808. // FIXME: This doesn't properly handle multiple uses.
  3809. int Idx = -1;
  3810. while (II != E && II->isInsideBundle()) {
  3811. Idx = II->findRegisterUseOperandIdx(Reg, false, TRI);
  3812. if (Idx != -1)
  3813. break;
  3814. if (II->getOpcode() != ARM::t2IT)
  3815. ++Dist;
  3816. ++II;
  3817. }
  3818. if (Idx == -1) {
  3819. Dist = 0;
  3820. return nullptr;
  3821. }
  3822. UseIdx = Idx;
  3823. return &*II;
  3824. }
  3825. /// Return the number of cycles to add to (or subtract from) the static
  3826. /// itinerary based on the def opcode and alignment. The caller will ensure that
  3827. /// adjusted latency is at least one cycle.
  3828. static int adjustDefLatency(const ARMSubtarget &Subtarget,
  3829. const MachineInstr &DefMI,
  3830. const MCInstrDesc &DefMCID, unsigned DefAlign) {
  3831. int Adjust = 0;
  3832. if (Subtarget.isCortexA8() || Subtarget.isLikeA9() || Subtarget.isCortexA7()) {
  3833. // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
  3834. // variants are one cycle cheaper.
  3835. switch (DefMCID.getOpcode()) {
  3836. default: break;
  3837. case ARM::LDRrs:
  3838. case ARM::LDRBrs: {
  3839. unsigned ShOpVal = DefMI.getOperand(3).getImm();
  3840. unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
  3841. if (ShImm == 0 ||
  3842. (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
  3843. --Adjust;
  3844. break;
  3845. }
  3846. case ARM::t2LDRs:
  3847. case ARM::t2LDRBs:
  3848. case ARM::t2LDRHs:
  3849. case ARM::t2LDRSHs: {
  3850. // Thumb2 mode: lsl only.
  3851. unsigned ShAmt = DefMI.getOperand(3).getImm();
  3852. if (ShAmt == 0 || ShAmt == 2)
  3853. --Adjust;
  3854. break;
  3855. }
  3856. }
  3857. } else if (Subtarget.isSwift()) {
  3858. // FIXME: Properly handle all of the latency adjustments for address
  3859. // writeback.
  3860. switch (DefMCID.getOpcode()) {
  3861. default: break;
  3862. case ARM::LDRrs:
  3863. case ARM::LDRBrs: {
  3864. unsigned ShOpVal = DefMI.getOperand(3).getImm();
  3865. bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
  3866. unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
  3867. if (!isSub &&
  3868. (ShImm == 0 ||
  3869. ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
  3870. ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
  3871. Adjust -= 2;
  3872. else if (!isSub &&
  3873. ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
  3874. --Adjust;
  3875. break;
  3876. }
  3877. case ARM::t2LDRs:
  3878. case ARM::t2LDRBs:
  3879. case ARM::t2LDRHs:
  3880. case ARM::t2LDRSHs: {
  3881. // Thumb2 mode: lsl only.
  3882. unsigned ShAmt = DefMI.getOperand(3).getImm();
  3883. if (ShAmt == 0 || ShAmt == 1 || ShAmt == 2 || ShAmt == 3)
  3884. Adjust -= 2;
  3885. break;
  3886. }
  3887. }
  3888. }
  3889. if (DefAlign < 8 && Subtarget.checkVLDnAccessAlignment()) {
  3890. switch (DefMCID.getOpcode()) {
  3891. default: break;
  3892. case ARM::VLD1q8:
  3893. case ARM::VLD1q16:
  3894. case ARM::VLD1q32:
  3895. case ARM::VLD1q64:
  3896. case ARM::VLD1q8wb_fixed:
  3897. case ARM::VLD1q16wb_fixed:
  3898. case ARM::VLD1q32wb_fixed:
  3899. case ARM::VLD1q64wb_fixed:
  3900. case ARM::VLD1q8wb_register:
  3901. case ARM::VLD1q16wb_register:
  3902. case ARM::VLD1q32wb_register:
  3903. case ARM::VLD1q64wb_register:
  3904. case ARM::VLD2d8:
  3905. case ARM::VLD2d16:
  3906. case ARM::VLD2d32:
  3907. case ARM::VLD2q8:
  3908. case ARM::VLD2q16:
  3909. case ARM::VLD2q32:
  3910. case ARM::VLD2d8wb_fixed:
  3911. case ARM::VLD2d16wb_fixed:
  3912. case ARM::VLD2d32wb_fixed:
  3913. case ARM::VLD2q8wb_fixed:
  3914. case ARM::VLD2q16wb_fixed:
  3915. case ARM::VLD2q32wb_fixed:
  3916. case ARM::VLD2d8wb_register:
  3917. case ARM::VLD2d16wb_register:
  3918. case ARM::VLD2d32wb_register:
  3919. case ARM::VLD2q8wb_register:
  3920. case ARM::VLD2q16wb_register:
  3921. case ARM::VLD2q32wb_register:
  3922. case ARM::VLD3d8:
  3923. case ARM::VLD3d16:
  3924. case ARM::VLD3d32:
  3925. case ARM::VLD1d64T:
  3926. case ARM::VLD3d8_UPD:
  3927. case ARM::VLD3d16_UPD:
  3928. case ARM::VLD3d32_UPD:
  3929. case ARM::VLD1d64Twb_fixed:
  3930. case ARM::VLD1d64Twb_register:
  3931. case ARM::VLD3q8_UPD:
  3932. case ARM::VLD3q16_UPD:
  3933. case ARM::VLD3q32_UPD:
  3934. case ARM::VLD4d8:
  3935. case ARM::VLD4d16:
  3936. case ARM::VLD4d32:
  3937. case ARM::VLD1d64Q:
  3938. case ARM::VLD4d8_UPD:
  3939. case ARM::VLD4d16_UPD:
  3940. case ARM::VLD4d32_UPD:
  3941. case ARM::VLD1d64Qwb_fixed:
  3942. case ARM::VLD1d64Qwb_register:
  3943. case ARM::VLD4q8_UPD:
  3944. case ARM::VLD4q16_UPD:
  3945. case ARM::VLD4q32_UPD:
  3946. case ARM::VLD1DUPq8:
  3947. case ARM::VLD1DUPq16:
  3948. case ARM::VLD1DUPq32:
  3949. case ARM::VLD1DUPq8wb_fixed:
  3950. case ARM::VLD1DUPq16wb_fixed:
  3951. case ARM::VLD1DUPq32wb_fixed:
  3952. case ARM::VLD1DUPq8wb_register:
  3953. case ARM::VLD1DUPq16wb_register:
  3954. case ARM::VLD1DUPq32wb_register:
  3955. case ARM::VLD2DUPd8:
  3956. case ARM::VLD2DUPd16:
  3957. case ARM::VLD2DUPd32:
  3958. case ARM::VLD2DUPd8wb_fixed:
  3959. case ARM::VLD2DUPd16wb_fixed:
  3960. case ARM::VLD2DUPd32wb_fixed:
  3961. case ARM::VLD2DUPd8wb_register:
  3962. case ARM::VLD2DUPd16wb_register:
  3963. case ARM::VLD2DUPd32wb_register:
  3964. case ARM::VLD4DUPd8:
  3965. case ARM::VLD4DUPd16:
  3966. case ARM::VLD4DUPd32:
  3967. case ARM::VLD4DUPd8_UPD:
  3968. case ARM::VLD4DUPd16_UPD:
  3969. case ARM::VLD4DUPd32_UPD:
  3970. case ARM::VLD1LNd8:
  3971. case ARM::VLD1LNd16:
  3972. case ARM::VLD1LNd32:
  3973. case ARM::VLD1LNd8_UPD:
  3974. case ARM::VLD1LNd16_UPD:
  3975. case ARM::VLD1LNd32_UPD:
  3976. case ARM::VLD2LNd8:
  3977. case ARM::VLD2LNd16:
  3978. case ARM::VLD2LNd32:
  3979. case ARM::VLD2LNq16:
  3980. case ARM::VLD2LNq32:
  3981. case ARM::VLD2LNd8_UPD:
  3982. case ARM::VLD2LNd16_UPD:
  3983. case ARM::VLD2LNd32_UPD:
  3984. case ARM::VLD2LNq16_UPD:
  3985. case ARM::VLD2LNq32_UPD:
  3986. case ARM::VLD4LNd8:
  3987. case ARM::VLD4LNd16:
  3988. case ARM::VLD4LNd32:
  3989. case ARM::VLD4LNq16:
  3990. case ARM::VLD4LNq32:
  3991. case ARM::VLD4LNd8_UPD:
  3992. case ARM::VLD4LNd16_UPD:
  3993. case ARM::VLD4LNd32_UPD:
  3994. case ARM::VLD4LNq16_UPD:
  3995. case ARM::VLD4LNq32_UPD:
  3996. // If the address is not 64-bit aligned, the latencies of these
  3997. // instructions increases by one.
  3998. ++Adjust;
  3999. break;
  4000. }
  4001. }
  4002. return Adjust;
  4003. }
  4004. int ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
  4005. const MachineInstr &DefMI,
  4006. unsigned DefIdx,
  4007. const MachineInstr &UseMI,
  4008. unsigned UseIdx) const {
  4009. // No operand latency. The caller may fall back to getInstrLatency.
  4010. if (!ItinData || ItinData->isEmpty())
  4011. return -1;
  4012. const MachineOperand &DefMO = DefMI.getOperand(DefIdx);
  4013. Register Reg = DefMO.getReg();
  4014. const MachineInstr *ResolvedDefMI = &DefMI;
  4015. unsigned DefAdj = 0;
  4016. if (DefMI.isBundle())
  4017. ResolvedDefMI =
  4018. getBundledDefMI(&getRegisterInfo(), &DefMI, Reg, DefIdx, DefAdj);
  4019. if (ResolvedDefMI->isCopyLike() || ResolvedDefMI->isInsertSubreg() ||
  4020. ResolvedDefMI->isRegSequence() || ResolvedDefMI->isImplicitDef()) {
  4021. return 1;
  4022. }
  4023. const MachineInstr *ResolvedUseMI = &UseMI;
  4024. unsigned UseAdj = 0;
  4025. if (UseMI.isBundle()) {
  4026. ResolvedUseMI =
  4027. getBundledUseMI(&getRegisterInfo(), UseMI, Reg, UseIdx, UseAdj);
  4028. if (!ResolvedUseMI)
  4029. return -1;
  4030. }
  4031. return getOperandLatencyImpl(
  4032. ItinData, *ResolvedDefMI, DefIdx, ResolvedDefMI->getDesc(), DefAdj, DefMO,
  4033. Reg, *ResolvedUseMI, UseIdx, ResolvedUseMI->getDesc(), UseAdj);
  4034. }
  4035. int ARMBaseInstrInfo::getOperandLatencyImpl(
  4036. const InstrItineraryData *ItinData, const MachineInstr &DefMI,
  4037. unsigned DefIdx, const MCInstrDesc &DefMCID, unsigned DefAdj,
  4038. const MachineOperand &DefMO, unsigned Reg, const MachineInstr &UseMI,
  4039. unsigned UseIdx, const MCInstrDesc &UseMCID, unsigned UseAdj) const {
  4040. if (Reg == ARM::CPSR) {
  4041. if (DefMI.getOpcode() == ARM::FMSTAT) {
  4042. // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?)
  4043. return Subtarget.isLikeA9() ? 1 : 20;
  4044. }
  4045. // CPSR set and branch can be paired in the same cycle.
  4046. if (UseMI.isBranch())
  4047. return 0;
  4048. // Otherwise it takes the instruction latency (generally one).
  4049. unsigned Latency = getInstrLatency(ItinData, DefMI);
  4050. // For Thumb2 and -Os, prefer scheduling CPSR setting instruction close to
  4051. // its uses. Instructions which are otherwise scheduled between them may
  4052. // incur a code size penalty (not able to use the CPSR setting 16-bit
  4053. // instructions).
  4054. if (Latency > 0 && Subtarget.isThumb2()) {
  4055. const MachineFunction *MF = DefMI.getParent()->getParent();
  4056. // FIXME: Use Function::hasOptSize().
  4057. if (MF->getFunction().hasFnAttribute(Attribute::OptimizeForSize))
  4058. --Latency;
  4059. }
  4060. return Latency;
  4061. }
  4062. if (DefMO.isImplicit() || UseMI.getOperand(UseIdx).isImplicit())
  4063. return -1;
  4064. unsigned DefAlign = DefMI.hasOneMemOperand()
  4065. ? (*DefMI.memoperands_begin())->getAlign().value()
  4066. : 0;
  4067. unsigned UseAlign = UseMI.hasOneMemOperand()
  4068. ? (*UseMI.memoperands_begin())->getAlign().value()
  4069. : 0;
  4070. // Get the itinerary's latency if possible, and handle variable_ops.
  4071. int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign, UseMCID,
  4072. UseIdx, UseAlign);
  4073. // Unable to find operand latency. The caller may resort to getInstrLatency.
  4074. if (Latency < 0)
  4075. return Latency;
  4076. // Adjust for IT block position.
  4077. int Adj = DefAdj + UseAdj;
  4078. // Adjust for dynamic def-side opcode variants not captured by the itinerary.
  4079. Adj += adjustDefLatency(Subtarget, DefMI, DefMCID, DefAlign);
  4080. if (Adj >= 0 || (int)Latency > -Adj) {
  4081. return Latency + Adj;
  4082. }
  4083. // Return the itinerary latency, which may be zero but not less than zero.
  4084. return Latency;
  4085. }
  4086. int
  4087. ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
  4088. SDNode *DefNode, unsigned DefIdx,
  4089. SDNode *UseNode, unsigned UseIdx) const {
  4090. if (!DefNode->isMachineOpcode())
  4091. return 1;
  4092. const MCInstrDesc &DefMCID = get(DefNode->getMachineOpcode());
  4093. if (isZeroCost(DefMCID.Opcode))
  4094. return 0;
  4095. if (!ItinData || ItinData->isEmpty())
  4096. return DefMCID.mayLoad() ? 3 : 1;
  4097. if (!UseNode->isMachineOpcode()) {
  4098. int Latency = ItinData->getOperandCycle(DefMCID.getSchedClass(), DefIdx);
  4099. int Adj = Subtarget.getPreISelOperandLatencyAdjustment();
  4100. int Threshold = 1 + Adj;
  4101. return Latency <= Threshold ? 1 : Latency - Adj;
  4102. }
  4103. const MCInstrDesc &UseMCID = get(UseNode->getMachineOpcode());
  4104. auto *DefMN = cast<MachineSDNode>(DefNode);
  4105. unsigned DefAlign = !DefMN->memoperands_empty()
  4106. ? (*DefMN->memoperands_begin())->getAlign().value()
  4107. : 0;
  4108. auto *UseMN = cast<MachineSDNode>(UseNode);
  4109. unsigned UseAlign = !UseMN->memoperands_empty()
  4110. ? (*UseMN->memoperands_begin())->getAlign().value()
  4111. : 0;
  4112. int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign,
  4113. UseMCID, UseIdx, UseAlign);
  4114. if (Latency > 1 &&
  4115. (Subtarget.isCortexA8() || Subtarget.isLikeA9() ||
  4116. Subtarget.isCortexA7())) {
  4117. // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
  4118. // variants are one cycle cheaper.
  4119. switch (DefMCID.getOpcode()) {
  4120. default: break;
  4121. case ARM::LDRrs:
  4122. case ARM::LDRBrs: {
  4123. unsigned ShOpVal =
  4124. cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
  4125. unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
  4126. if (ShImm == 0 ||
  4127. (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
  4128. --Latency;
  4129. break;
  4130. }
  4131. case ARM::t2LDRs:
  4132. case ARM::t2LDRBs:
  4133. case ARM::t2LDRHs:
  4134. case ARM::t2LDRSHs: {
  4135. // Thumb2 mode: lsl only.
  4136. unsigned ShAmt =
  4137. cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
  4138. if (ShAmt == 0 || ShAmt == 2)
  4139. --Latency;
  4140. break;
  4141. }
  4142. }
  4143. } else if (DefIdx == 0 && Latency > 2 && Subtarget.isSwift()) {
  4144. // FIXME: Properly handle all of the latency adjustments for address
  4145. // writeback.
  4146. switch (DefMCID.getOpcode()) {
  4147. default: break;
  4148. case ARM::LDRrs:
  4149. case ARM::LDRBrs: {
  4150. unsigned ShOpVal =
  4151. cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
  4152. unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
  4153. if (ShImm == 0 ||
  4154. ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
  4155. ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
  4156. Latency -= 2;
  4157. else if (ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
  4158. --Latency;
  4159. break;
  4160. }
  4161. case ARM::t2LDRs:
  4162. case ARM::t2LDRBs:
  4163. case ARM::t2LDRHs:
  4164. case ARM::t2LDRSHs:
  4165. // Thumb2 mode: lsl 0-3 only.
  4166. Latency -= 2;
  4167. break;
  4168. }
  4169. }
  4170. if (DefAlign < 8 && Subtarget.checkVLDnAccessAlignment())
  4171. switch (DefMCID.getOpcode()) {
  4172. default: break;
  4173. case ARM::VLD1q8:
  4174. case ARM::VLD1q16:
  4175. case ARM::VLD1q32:
  4176. case ARM::VLD1q64:
  4177. case ARM::VLD1q8wb_register:
  4178. case ARM::VLD1q16wb_register:
  4179. case ARM::VLD1q32wb_register:
  4180. case ARM::VLD1q64wb_register:
  4181. case ARM::VLD1q8wb_fixed:
  4182. case ARM::VLD1q16wb_fixed:
  4183. case ARM::VLD1q32wb_fixed:
  4184. case ARM::VLD1q64wb_fixed:
  4185. case ARM::VLD2d8:
  4186. case ARM::VLD2d16:
  4187. case ARM::VLD2d32:
  4188. case ARM::VLD2q8Pseudo:
  4189. case ARM::VLD2q16Pseudo:
  4190. case ARM::VLD2q32Pseudo:
  4191. case ARM::VLD2d8wb_fixed:
  4192. case ARM::VLD2d16wb_fixed:
  4193. case ARM::VLD2d32wb_fixed:
  4194. case ARM::VLD2q8PseudoWB_fixed:
  4195. case ARM::VLD2q16PseudoWB_fixed:
  4196. case ARM::VLD2q32PseudoWB_fixed:
  4197. case ARM::VLD2d8wb_register:
  4198. case ARM::VLD2d16wb_register:
  4199. case ARM::VLD2d32wb_register:
  4200. case ARM::VLD2q8PseudoWB_register:
  4201. case ARM::VLD2q16PseudoWB_register:
  4202. case ARM::VLD2q32PseudoWB_register:
  4203. case ARM::VLD3d8Pseudo:
  4204. case ARM::VLD3d16Pseudo:
  4205. case ARM::VLD3d32Pseudo:
  4206. case ARM::VLD1d8TPseudo:
  4207. case ARM::VLD1d16TPseudo:
  4208. case ARM::VLD1d32TPseudo:
  4209. case ARM::VLD1d64TPseudo:
  4210. case ARM::VLD1d64TPseudoWB_fixed:
  4211. case ARM::VLD1d64TPseudoWB_register:
  4212. case ARM::VLD3d8Pseudo_UPD:
  4213. case ARM::VLD3d16Pseudo_UPD:
  4214. case ARM::VLD3d32Pseudo_UPD:
  4215. case ARM::VLD3q8Pseudo_UPD:
  4216. case ARM::VLD3q16Pseudo_UPD:
  4217. case ARM::VLD3q32Pseudo_UPD:
  4218. case ARM::VLD3q8oddPseudo:
  4219. case ARM::VLD3q16oddPseudo:
  4220. case ARM::VLD3q32oddPseudo:
  4221. case ARM::VLD3q8oddPseudo_UPD:
  4222. case ARM::VLD3q16oddPseudo_UPD:
  4223. case ARM::VLD3q32oddPseudo_UPD:
  4224. case ARM::VLD4d8Pseudo:
  4225. case ARM::VLD4d16Pseudo:
  4226. case ARM::VLD4d32Pseudo:
  4227. case ARM::VLD1d8QPseudo:
  4228. case ARM::VLD1d16QPseudo:
  4229. case ARM::VLD1d32QPseudo:
  4230. case ARM::VLD1d64QPseudo:
  4231. case ARM::VLD1d64QPseudoWB_fixed:
  4232. case ARM::VLD1d64QPseudoWB_register:
  4233. case ARM::VLD1q8HighQPseudo:
  4234. case ARM::VLD1q8LowQPseudo_UPD:
  4235. case ARM::VLD1q8HighTPseudo:
  4236. case ARM::VLD1q8LowTPseudo_UPD:
  4237. case ARM::VLD1q16HighQPseudo:
  4238. case ARM::VLD1q16LowQPseudo_UPD:
  4239. case ARM::VLD1q16HighTPseudo:
  4240. case ARM::VLD1q16LowTPseudo_UPD:
  4241. case ARM::VLD1q32HighQPseudo:
  4242. case ARM::VLD1q32LowQPseudo_UPD:
  4243. case ARM::VLD1q32HighTPseudo:
  4244. case ARM::VLD1q32LowTPseudo_UPD:
  4245. case ARM::VLD1q64HighQPseudo:
  4246. case ARM::VLD1q64LowQPseudo_UPD:
  4247. case ARM::VLD1q64HighTPseudo:
  4248. case ARM::VLD1q64LowTPseudo_UPD:
  4249. case ARM::VLD4d8Pseudo_UPD:
  4250. case ARM::VLD4d16Pseudo_UPD:
  4251. case ARM::VLD4d32Pseudo_UPD:
  4252. case ARM::VLD4q8Pseudo_UPD:
  4253. case ARM::VLD4q16Pseudo_UPD:
  4254. case ARM::VLD4q32Pseudo_UPD:
  4255. case ARM::VLD4q8oddPseudo:
  4256. case ARM::VLD4q16oddPseudo:
  4257. case ARM::VLD4q32oddPseudo:
  4258. case ARM::VLD4q8oddPseudo_UPD:
  4259. case ARM::VLD4q16oddPseudo_UPD:
  4260. case ARM::VLD4q32oddPseudo_UPD:
  4261. case ARM::VLD1DUPq8:
  4262. case ARM::VLD1DUPq16:
  4263. case ARM::VLD1DUPq32:
  4264. case ARM::VLD1DUPq8wb_fixed:
  4265. case ARM::VLD1DUPq16wb_fixed:
  4266. case ARM::VLD1DUPq32wb_fixed:
  4267. case ARM::VLD1DUPq8wb_register:
  4268. case ARM::VLD1DUPq16wb_register:
  4269. case ARM::VLD1DUPq32wb_register:
  4270. case ARM::VLD2DUPd8:
  4271. case ARM::VLD2DUPd16:
  4272. case ARM::VLD2DUPd32:
  4273. case ARM::VLD2DUPd8wb_fixed:
  4274. case ARM::VLD2DUPd16wb_fixed:
  4275. case ARM::VLD2DUPd32wb_fixed:
  4276. case ARM::VLD2DUPd8wb_register:
  4277. case ARM::VLD2DUPd16wb_register:
  4278. case ARM::VLD2DUPd32wb_register:
  4279. case ARM::VLD2DUPq8EvenPseudo:
  4280. case ARM::VLD2DUPq8OddPseudo:
  4281. case ARM::VLD2DUPq16EvenPseudo:
  4282. case ARM::VLD2DUPq16OddPseudo:
  4283. case ARM::VLD2DUPq32EvenPseudo:
  4284. case ARM::VLD2DUPq32OddPseudo:
  4285. case ARM::VLD3DUPq8EvenPseudo:
  4286. case ARM::VLD3DUPq8OddPseudo:
  4287. case ARM::VLD3DUPq16EvenPseudo:
  4288. case ARM::VLD3DUPq16OddPseudo:
  4289. case ARM::VLD3DUPq32EvenPseudo:
  4290. case ARM::VLD3DUPq32OddPseudo:
  4291. case ARM::VLD4DUPd8Pseudo:
  4292. case ARM::VLD4DUPd16Pseudo:
  4293. case ARM::VLD4DUPd32Pseudo:
  4294. case ARM::VLD4DUPd8Pseudo_UPD:
  4295. case ARM::VLD4DUPd16Pseudo_UPD:
  4296. case ARM::VLD4DUPd32Pseudo_UPD:
  4297. case ARM::VLD4DUPq8EvenPseudo:
  4298. case ARM::VLD4DUPq8OddPseudo:
  4299. case ARM::VLD4DUPq16EvenPseudo:
  4300. case ARM::VLD4DUPq16OddPseudo:
  4301. case ARM::VLD4DUPq32EvenPseudo:
  4302. case ARM::VLD4DUPq32OddPseudo:
  4303. case ARM::VLD1LNq8Pseudo:
  4304. case ARM::VLD1LNq16Pseudo:
  4305. case ARM::VLD1LNq32Pseudo:
  4306. case ARM::VLD1LNq8Pseudo_UPD:
  4307. case ARM::VLD1LNq16Pseudo_UPD:
  4308. case ARM::VLD1LNq32Pseudo_UPD:
  4309. case ARM::VLD2LNd8Pseudo:
  4310. case ARM::VLD2LNd16Pseudo:
  4311. case ARM::VLD2LNd32Pseudo:
  4312. case ARM::VLD2LNq16Pseudo:
  4313. case ARM::VLD2LNq32Pseudo:
  4314. case ARM::VLD2LNd8Pseudo_UPD:
  4315. case ARM::VLD2LNd16Pseudo_UPD:
  4316. case ARM::VLD2LNd32Pseudo_UPD:
  4317. case ARM::VLD2LNq16Pseudo_UPD:
  4318. case ARM::VLD2LNq32Pseudo_UPD:
  4319. case ARM::VLD4LNd8Pseudo:
  4320. case ARM::VLD4LNd16Pseudo:
  4321. case ARM::VLD4LNd32Pseudo:
  4322. case ARM::VLD4LNq16Pseudo:
  4323. case ARM::VLD4LNq32Pseudo:
  4324. case ARM::VLD4LNd8Pseudo_UPD:
  4325. case ARM::VLD4LNd16Pseudo_UPD:
  4326. case ARM::VLD4LNd32Pseudo_UPD:
  4327. case ARM::VLD4LNq16Pseudo_UPD:
  4328. case ARM::VLD4LNq32Pseudo_UPD:
  4329. // If the address is not 64-bit aligned, the latencies of these
  4330. // instructions increases by one.
  4331. ++Latency;
  4332. break;
  4333. }
  4334. return Latency;
  4335. }
  4336. unsigned ARMBaseInstrInfo::getPredicationCost(const MachineInstr &MI) const {
  4337. if (MI.isCopyLike() || MI.isInsertSubreg() || MI.isRegSequence() ||
  4338. MI.isImplicitDef())
  4339. return 0;
  4340. if (MI.isBundle())
  4341. return 0;
  4342. const MCInstrDesc &MCID = MI.getDesc();
  4343. if (MCID.isCall() || (MCID.hasImplicitDefOfPhysReg(ARM::CPSR) &&
  4344. !Subtarget.cheapPredicableCPSRDef())) {
  4345. // When predicated, CPSR is an additional source operand for CPSR updating
  4346. // instructions, this apparently increases their latencies.
  4347. return 1;
  4348. }
  4349. return 0;
  4350. }
  4351. unsigned ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
  4352. const MachineInstr &MI,
  4353. unsigned *PredCost) const {
  4354. if (MI.isCopyLike() || MI.isInsertSubreg() || MI.isRegSequence() ||
  4355. MI.isImplicitDef())
  4356. return 1;
  4357. // An instruction scheduler typically runs on unbundled instructions, however
  4358. // other passes may query the latency of a bundled instruction.
  4359. if (MI.isBundle()) {
  4360. unsigned Latency = 0;
  4361. MachineBasicBlock::const_instr_iterator I = MI.getIterator();
  4362. MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
  4363. while (++I != E && I->isInsideBundle()) {
  4364. if (I->getOpcode() != ARM::t2IT)
  4365. Latency += getInstrLatency(ItinData, *I, PredCost);
  4366. }
  4367. return Latency;
  4368. }
  4369. const MCInstrDesc &MCID = MI.getDesc();
  4370. if (PredCost && (MCID.isCall() || (MCID.hasImplicitDefOfPhysReg(ARM::CPSR) &&
  4371. !Subtarget.cheapPredicableCPSRDef()))) {
  4372. // When predicated, CPSR is an additional source operand for CPSR updating
  4373. // instructions, this apparently increases their latencies.
  4374. *PredCost = 1;
  4375. }
  4376. // Be sure to call getStageLatency for an empty itinerary in case it has a
  4377. // valid MinLatency property.
  4378. if (!ItinData)
  4379. return MI.mayLoad() ? 3 : 1;
  4380. unsigned Class = MCID.getSchedClass();
  4381. // For instructions with variable uops, use uops as latency.
  4382. if (!ItinData->isEmpty() && ItinData->getNumMicroOps(Class) < 0)
  4383. return getNumMicroOps(ItinData, MI);
  4384. // For the common case, fall back on the itinerary's latency.
  4385. unsigned Latency = ItinData->getStageLatency(Class);
  4386. // Adjust for dynamic def-side opcode variants not captured by the itinerary.
  4387. unsigned DefAlign =
  4388. MI.hasOneMemOperand() ? (*MI.memoperands_begin())->getAlign().value() : 0;
  4389. int Adj = adjustDefLatency(Subtarget, MI, MCID, DefAlign);
  4390. if (Adj >= 0 || (int)Latency > -Adj) {
  4391. return Latency + Adj;
  4392. }
  4393. return Latency;
  4394. }
  4395. int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
  4396. SDNode *Node) const {
  4397. if (!Node->isMachineOpcode())
  4398. return 1;
  4399. if (!ItinData || ItinData->isEmpty())
  4400. return 1;
  4401. unsigned Opcode = Node->getMachineOpcode();
  4402. switch (Opcode) {
  4403. default:
  4404. return ItinData->getStageLatency(get(Opcode).getSchedClass());
  4405. case ARM::VLDMQIA:
  4406. case ARM::VSTMQIA:
  4407. return 2;
  4408. }
  4409. }
  4410. bool ARMBaseInstrInfo::hasHighOperandLatency(const TargetSchedModel &SchedModel,
  4411. const MachineRegisterInfo *MRI,
  4412. const MachineInstr &DefMI,
  4413. unsigned DefIdx,
  4414. const MachineInstr &UseMI,
  4415. unsigned UseIdx) const {
  4416. unsigned DDomain = DefMI.getDesc().TSFlags & ARMII::DomainMask;
  4417. unsigned UDomain = UseMI.getDesc().TSFlags & ARMII::DomainMask;
  4418. if (Subtarget.nonpipelinedVFP() &&
  4419. (DDomain == ARMII::DomainVFP || UDomain == ARMII::DomainVFP))
  4420. return true;
  4421. // Hoist VFP / NEON instructions with 4 or higher latency.
  4422. unsigned Latency =
  4423. SchedModel.computeOperandLatency(&DefMI, DefIdx, &UseMI, UseIdx);
  4424. if (Latency <= 3)
  4425. return false;
  4426. return DDomain == ARMII::DomainVFP || DDomain == ARMII::DomainNEON ||
  4427. UDomain == ARMII::DomainVFP || UDomain == ARMII::DomainNEON;
  4428. }
  4429. bool ARMBaseInstrInfo::hasLowDefLatency(const TargetSchedModel &SchedModel,
  4430. const MachineInstr &DefMI,
  4431. unsigned DefIdx) const {
  4432. const InstrItineraryData *ItinData = SchedModel.getInstrItineraries();
  4433. if (!ItinData || ItinData->isEmpty())
  4434. return false;
  4435. unsigned DDomain = DefMI.getDesc().TSFlags & ARMII::DomainMask;
  4436. if (DDomain == ARMII::DomainGeneral) {
  4437. unsigned DefClass = DefMI.getDesc().getSchedClass();
  4438. int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
  4439. return (DefCycle != -1 && DefCycle <= 2);
  4440. }
  4441. return false;
  4442. }
  4443. bool ARMBaseInstrInfo::verifyInstruction(const MachineInstr &MI,
  4444. StringRef &ErrInfo) const {
  4445. if (convertAddSubFlagsOpcode(MI.getOpcode())) {
  4446. ErrInfo = "Pseudo flag setting opcodes only exist in Selection DAG";
  4447. return false;
  4448. }
  4449. if (MI.getOpcode() == ARM::tMOVr && !Subtarget.hasV6Ops()) {
  4450. // Make sure we don't generate a lo-lo mov that isn't supported.
  4451. if (!ARM::hGPRRegClass.contains(MI.getOperand(0).getReg()) &&
  4452. !ARM::hGPRRegClass.contains(MI.getOperand(1).getReg())) {
  4453. ErrInfo = "Non-flag-setting Thumb1 mov is v6-only";
  4454. return false;
  4455. }
  4456. }
  4457. if (MI.getOpcode() == ARM::tPUSH ||
  4458. MI.getOpcode() == ARM::tPOP ||
  4459. MI.getOpcode() == ARM::tPOP_RET) {
  4460. for (const MachineOperand &MO : llvm::drop_begin(MI.operands(), 2)) {
  4461. if (MO.isImplicit() || !MO.isReg())
  4462. continue;
  4463. Register Reg = MO.getReg();
  4464. if (Reg < ARM::R0 || Reg > ARM::R7) {
  4465. if (!(MI.getOpcode() == ARM::tPUSH && Reg == ARM::LR) &&
  4466. !(MI.getOpcode() == ARM::tPOP_RET && Reg == ARM::PC)) {
  4467. ErrInfo = "Unsupported register in Thumb1 push/pop";
  4468. return false;
  4469. }
  4470. }
  4471. }
  4472. }
  4473. if (MI.getOpcode() == ARM::MVE_VMOV_q_rr) {
  4474. assert(MI.getOperand(4).isImm() && MI.getOperand(5).isImm());
  4475. if ((MI.getOperand(4).getImm() != 2 && MI.getOperand(4).getImm() != 3) ||
  4476. MI.getOperand(4).getImm() != MI.getOperand(5).getImm() + 2) {
  4477. ErrInfo = "Incorrect array index for MVE_VMOV_q_rr";
  4478. return false;
  4479. }
  4480. }
  4481. // Check the address model by taking the first Imm operand and checking it is
  4482. // legal for that addressing mode.
  4483. ARMII::AddrMode AddrMode =
  4484. (ARMII::AddrMode)(MI.getDesc().TSFlags & ARMII::AddrModeMask);
  4485. switch (AddrMode) {
  4486. default:
  4487. break;
  4488. case ARMII::AddrModeT2_i7:
  4489. case ARMII::AddrModeT2_i7s2:
  4490. case ARMII::AddrModeT2_i7s4:
  4491. case ARMII::AddrModeT2_i8:
  4492. case ARMII::AddrModeT2_i8pos:
  4493. case ARMII::AddrModeT2_i8neg:
  4494. case ARMII::AddrModeT2_i8s4:
  4495. case ARMII::AddrModeT2_i12: {
  4496. uint32_t Imm = 0;
  4497. for (auto Op : MI.operands()) {
  4498. if (Op.isImm()) {
  4499. Imm = Op.getImm();
  4500. break;
  4501. }
  4502. }
  4503. if (!isLegalAddressImm(MI.getOpcode(), Imm, this)) {
  4504. ErrInfo = "Incorrect AddrMode Imm for instruction";
  4505. return false;
  4506. }
  4507. break;
  4508. }
  4509. }
  4510. return true;
  4511. }
  4512. void ARMBaseInstrInfo::expandLoadStackGuardBase(MachineBasicBlock::iterator MI,
  4513. unsigned LoadImmOpc,
  4514. unsigned LoadOpc) const {
  4515. assert(!Subtarget.isROPI() && !Subtarget.isRWPI() &&
  4516. "ROPI/RWPI not currently supported with stack guard");
  4517. MachineBasicBlock &MBB = *MI->getParent();
  4518. DebugLoc DL = MI->getDebugLoc();
  4519. Register Reg = MI->getOperand(0).getReg();
  4520. MachineInstrBuilder MIB;
  4521. unsigned int Offset = 0;
  4522. if (LoadImmOpc == ARM::MRC || LoadImmOpc == ARM::t2MRC) {
  4523. assert(Subtarget.isReadTPHard() &&
  4524. "TLS stack protector requires hardware TLS register");
  4525. BuildMI(MBB, MI, DL, get(LoadImmOpc), Reg)
  4526. .addImm(15)
  4527. .addImm(0)
  4528. .addImm(13)
  4529. .addImm(0)
  4530. .addImm(3)
  4531. .add(predOps(ARMCC::AL));
  4532. Module &M = *MBB.getParent()->getFunction().getParent();
  4533. Offset = M.getStackProtectorGuardOffset();
  4534. if (Offset & ~0xfffU) {
  4535. // The offset won't fit in the LDR's 12-bit immediate field, so emit an
  4536. // extra ADD to cover the delta. This gives us a guaranteed 8 additional
  4537. // bits, resulting in a range of 0 to +1 MiB for the guard offset.
  4538. unsigned AddOpc = (LoadImmOpc == ARM::MRC) ? ARM::ADDri : ARM::t2ADDri;
  4539. BuildMI(MBB, MI, DL, get(AddOpc), Reg)
  4540. .addReg(Reg, RegState::Kill)
  4541. .addImm(Offset & ~0xfffU)
  4542. .add(predOps(ARMCC::AL))
  4543. .addReg(0);
  4544. Offset &= 0xfffU;
  4545. }
  4546. } else {
  4547. const GlobalValue *GV =
  4548. cast<GlobalValue>((*MI->memoperands_begin())->getValue());
  4549. bool IsIndirect = Subtarget.isGVIndirectSymbol(GV);
  4550. unsigned TargetFlags = ARMII::MO_NO_FLAG;
  4551. if (Subtarget.isTargetMachO()) {
  4552. TargetFlags |= ARMII::MO_NONLAZY;
  4553. } else if (Subtarget.isTargetCOFF()) {
  4554. if (GV->hasDLLImportStorageClass())
  4555. TargetFlags |= ARMII::MO_DLLIMPORT;
  4556. else if (IsIndirect)
  4557. TargetFlags |= ARMII::MO_COFFSTUB;
  4558. } else if (Subtarget.isGVInGOT(GV)) {
  4559. TargetFlags |= ARMII::MO_GOT;
  4560. }
  4561. BuildMI(MBB, MI, DL, get(LoadImmOpc), Reg)
  4562. .addGlobalAddress(GV, 0, TargetFlags);
  4563. if (IsIndirect) {
  4564. MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg);
  4565. MIB.addReg(Reg, RegState::Kill).addImm(0);
  4566. auto Flags = MachineMemOperand::MOLoad |
  4567. MachineMemOperand::MODereferenceable |
  4568. MachineMemOperand::MOInvariant;
  4569. MachineMemOperand *MMO = MBB.getParent()->getMachineMemOperand(
  4570. MachinePointerInfo::getGOT(*MBB.getParent()), Flags, 4, Align(4));
  4571. MIB.addMemOperand(MMO).add(predOps(ARMCC::AL));
  4572. }
  4573. }
  4574. MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg);
  4575. MIB.addReg(Reg, RegState::Kill)
  4576. .addImm(Offset)
  4577. .cloneMemRefs(*MI)
  4578. .add(predOps(ARMCC::AL));
  4579. }
  4580. bool
  4581. ARMBaseInstrInfo::isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc,
  4582. unsigned &AddSubOpc,
  4583. bool &NegAcc, bool &HasLane) const {
  4584. DenseMap<unsigned, unsigned>::const_iterator I = MLxEntryMap.find(Opcode);
  4585. if (I == MLxEntryMap.end())
  4586. return false;
  4587. const ARM_MLxEntry &Entry = ARM_MLxTable[I->second];
  4588. MulOpc = Entry.MulOpc;
  4589. AddSubOpc = Entry.AddSubOpc;
  4590. NegAcc = Entry.NegAcc;
  4591. HasLane = Entry.HasLane;
  4592. return true;
  4593. }
  4594. //===----------------------------------------------------------------------===//
  4595. // Execution domains.
  4596. //===----------------------------------------------------------------------===//
  4597. //
  4598. // Some instructions go down the NEON pipeline, some go down the VFP pipeline,
  4599. // and some can go down both. The vmov instructions go down the VFP pipeline,
  4600. // but they can be changed to vorr equivalents that are executed by the NEON
  4601. // pipeline.
  4602. //
  4603. // We use the following execution domain numbering:
  4604. //
  4605. enum ARMExeDomain {
  4606. ExeGeneric = 0,
  4607. ExeVFP = 1,
  4608. ExeNEON = 2
  4609. };
  4610. //
  4611. // Also see ARMInstrFormats.td and Domain* enums in ARMBaseInfo.h
  4612. //
  4613. std::pair<uint16_t, uint16_t>
  4614. ARMBaseInstrInfo::getExecutionDomain(const MachineInstr &MI) const {
  4615. // If we don't have access to NEON instructions then we won't be able
  4616. // to swizzle anything to the NEON domain. Check to make sure.
  4617. if (Subtarget.hasNEON()) {
  4618. // VMOVD, VMOVRS and VMOVSR are VFP instructions, but can be changed to NEON
  4619. // if they are not predicated.
  4620. if (MI.getOpcode() == ARM::VMOVD && !isPredicated(MI))
  4621. return std::make_pair(ExeVFP, (1 << ExeVFP) | (1 << ExeNEON));
  4622. // CortexA9 is particularly picky about mixing the two and wants these
  4623. // converted.
  4624. if (Subtarget.useNEONForFPMovs() && !isPredicated(MI) &&
  4625. (MI.getOpcode() == ARM::VMOVRS || MI.getOpcode() == ARM::VMOVSR ||
  4626. MI.getOpcode() == ARM::VMOVS))
  4627. return std::make_pair(ExeVFP, (1 << ExeVFP) | (1 << ExeNEON));
  4628. }
  4629. // No other instructions can be swizzled, so just determine their domain.
  4630. unsigned Domain = MI.getDesc().TSFlags & ARMII::DomainMask;
  4631. if (Domain & ARMII::DomainNEON)
  4632. return std::make_pair(ExeNEON, 0);
  4633. // Certain instructions can go either way on Cortex-A8.
  4634. // Treat them as NEON instructions.
  4635. if ((Domain & ARMII::DomainNEONA8) && Subtarget.isCortexA8())
  4636. return std::make_pair(ExeNEON, 0);
  4637. if (Domain & ARMII::DomainVFP)
  4638. return std::make_pair(ExeVFP, 0);
  4639. return std::make_pair(ExeGeneric, 0);
  4640. }
  4641. static unsigned getCorrespondingDRegAndLane(const TargetRegisterInfo *TRI,
  4642. unsigned SReg, unsigned &Lane) {
  4643. unsigned DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_0, &ARM::DPRRegClass);
  4644. Lane = 0;
  4645. if (DReg != ARM::NoRegister)
  4646. return DReg;
  4647. Lane = 1;
  4648. DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_1, &ARM::DPRRegClass);
  4649. assert(DReg && "S-register with no D super-register?");
  4650. return DReg;
  4651. }
  4652. /// getImplicitSPRUseForDPRUse - Given a use of a DPR register and lane,
  4653. /// set ImplicitSReg to a register number that must be marked as implicit-use or
  4654. /// zero if no register needs to be defined as implicit-use.
  4655. ///
  4656. /// If the function cannot determine if an SPR should be marked implicit use or
  4657. /// not, it returns false.
  4658. ///
  4659. /// This function handles cases where an instruction is being modified from taking
  4660. /// an SPR to a DPR[Lane]. A use of the DPR is being added, which may conflict
  4661. /// with an earlier def of an SPR corresponding to DPR[Lane^1] (i.e. the other
  4662. /// lane of the DPR).
  4663. ///
  4664. /// If the other SPR is defined, an implicit-use of it should be added. Else,
  4665. /// (including the case where the DPR itself is defined), it should not.
  4666. ///
  4667. static bool getImplicitSPRUseForDPRUse(const TargetRegisterInfo *TRI,
  4668. MachineInstr &MI, unsigned DReg,
  4669. unsigned Lane, unsigned &ImplicitSReg) {
  4670. // If the DPR is defined or used already, the other SPR lane will be chained
  4671. // correctly, so there is nothing to be done.
  4672. if (MI.definesRegister(DReg, TRI) || MI.readsRegister(DReg, TRI)) {
  4673. ImplicitSReg = 0;
  4674. return true;
  4675. }
  4676. // Otherwise we need to go searching to see if the SPR is set explicitly.
  4677. ImplicitSReg = TRI->getSubReg(DReg,
  4678. (Lane & 1) ? ARM::ssub_0 : ARM::ssub_1);
  4679. MachineBasicBlock::LivenessQueryResult LQR =
  4680. MI.getParent()->computeRegisterLiveness(TRI, ImplicitSReg, MI);
  4681. if (LQR == MachineBasicBlock::LQR_Live)
  4682. return true;
  4683. else if (LQR == MachineBasicBlock::LQR_Unknown)
  4684. return false;
  4685. // If the register is known not to be live, there is no need to add an
  4686. // implicit-use.
  4687. ImplicitSReg = 0;
  4688. return true;
  4689. }
  4690. void ARMBaseInstrInfo::setExecutionDomain(MachineInstr &MI,
  4691. unsigned Domain) const {
  4692. unsigned DstReg, SrcReg, DReg;
  4693. unsigned Lane;
  4694. MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI);
  4695. const TargetRegisterInfo *TRI = &getRegisterInfo();
  4696. switch (MI.getOpcode()) {
  4697. default:
  4698. llvm_unreachable("cannot handle opcode!");
  4699. break;
  4700. case ARM::VMOVD:
  4701. if (Domain != ExeNEON)
  4702. break;
  4703. // Zap the predicate operands.
  4704. assert(!isPredicated(MI) && "Cannot predicate a VORRd");
  4705. // Make sure we've got NEON instructions.
  4706. assert(Subtarget.hasNEON() && "VORRd requires NEON");
  4707. // Source instruction is %DDst = VMOVD %DSrc, 14, %noreg (; implicits)
  4708. DstReg = MI.getOperand(0).getReg();
  4709. SrcReg = MI.getOperand(1).getReg();
  4710. for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
  4711. MI.removeOperand(i - 1);
  4712. // Change to a %DDst = VORRd %DSrc, %DSrc, 14, %noreg (; implicits)
  4713. MI.setDesc(get(ARM::VORRd));
  4714. MIB.addReg(DstReg, RegState::Define)
  4715. .addReg(SrcReg)
  4716. .addReg(SrcReg)
  4717. .add(predOps(ARMCC::AL));
  4718. break;
  4719. case ARM::VMOVRS:
  4720. if (Domain != ExeNEON)
  4721. break;
  4722. assert(!isPredicated(MI) && "Cannot predicate a VGETLN");
  4723. // Source instruction is %RDst = VMOVRS %SSrc, 14, %noreg (; implicits)
  4724. DstReg = MI.getOperand(0).getReg();
  4725. SrcReg = MI.getOperand(1).getReg();
  4726. for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
  4727. MI.removeOperand(i - 1);
  4728. DReg = getCorrespondingDRegAndLane(TRI, SrcReg, Lane);
  4729. // Convert to %RDst = VGETLNi32 %DSrc, Lane, 14, %noreg (; imps)
  4730. // Note that DSrc has been widened and the other lane may be undef, which
  4731. // contaminates the entire register.
  4732. MI.setDesc(get(ARM::VGETLNi32));
  4733. MIB.addReg(DstReg, RegState::Define)
  4734. .addReg(DReg, RegState::Undef)
  4735. .addImm(Lane)
  4736. .add(predOps(ARMCC::AL));
  4737. // The old source should be an implicit use, otherwise we might think it
  4738. // was dead before here.
  4739. MIB.addReg(SrcReg, RegState::Implicit);
  4740. break;
  4741. case ARM::VMOVSR: {
  4742. if (Domain != ExeNEON)
  4743. break;
  4744. assert(!isPredicated(MI) && "Cannot predicate a VSETLN");
  4745. // Source instruction is %SDst = VMOVSR %RSrc, 14, %noreg (; implicits)
  4746. DstReg = MI.getOperand(0).getReg();
  4747. SrcReg = MI.getOperand(1).getReg();
  4748. DReg = getCorrespondingDRegAndLane(TRI, DstReg, Lane);
  4749. unsigned ImplicitSReg;
  4750. if (!getImplicitSPRUseForDPRUse(TRI, MI, DReg, Lane, ImplicitSReg))
  4751. break;
  4752. for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
  4753. MI.removeOperand(i - 1);
  4754. // Convert to %DDst = VSETLNi32 %DDst, %RSrc, Lane, 14, %noreg (; imps)
  4755. // Again DDst may be undefined at the beginning of this instruction.
  4756. MI.setDesc(get(ARM::VSETLNi32));
  4757. MIB.addReg(DReg, RegState::Define)
  4758. .addReg(DReg, getUndefRegState(!MI.readsRegister(DReg, TRI)))
  4759. .addReg(SrcReg)
  4760. .addImm(Lane)
  4761. .add(predOps(ARMCC::AL));
  4762. // The narrower destination must be marked as set to keep previous chains
  4763. // in place.
  4764. MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
  4765. if (ImplicitSReg != 0)
  4766. MIB.addReg(ImplicitSReg, RegState::Implicit);
  4767. break;
  4768. }
  4769. case ARM::VMOVS: {
  4770. if (Domain != ExeNEON)
  4771. break;
  4772. // Source instruction is %SDst = VMOVS %SSrc, 14, %noreg (; implicits)
  4773. DstReg = MI.getOperand(0).getReg();
  4774. SrcReg = MI.getOperand(1).getReg();
  4775. unsigned DstLane = 0, SrcLane = 0, DDst, DSrc;
  4776. DDst = getCorrespondingDRegAndLane(TRI, DstReg, DstLane);
  4777. DSrc = getCorrespondingDRegAndLane(TRI, SrcReg, SrcLane);
  4778. unsigned ImplicitSReg;
  4779. if (!getImplicitSPRUseForDPRUse(TRI, MI, DSrc, SrcLane, ImplicitSReg))
  4780. break;
  4781. for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
  4782. MI.removeOperand(i - 1);
  4783. if (DSrc == DDst) {
  4784. // Destination can be:
  4785. // %DDst = VDUPLN32d %DDst, Lane, 14, %noreg (; implicits)
  4786. MI.setDesc(get(ARM::VDUPLN32d));
  4787. MIB.addReg(DDst, RegState::Define)
  4788. .addReg(DDst, getUndefRegState(!MI.readsRegister(DDst, TRI)))
  4789. .addImm(SrcLane)
  4790. .add(predOps(ARMCC::AL));
  4791. // Neither the source or the destination are naturally represented any
  4792. // more, so add them in manually.
  4793. MIB.addReg(DstReg, RegState::Implicit | RegState::Define);
  4794. MIB.addReg(SrcReg, RegState::Implicit);
  4795. if (ImplicitSReg != 0)
  4796. MIB.addReg(ImplicitSReg, RegState::Implicit);
  4797. break;
  4798. }
  4799. // In general there's no single instruction that can perform an S <-> S
  4800. // move in NEON space, but a pair of VEXT instructions *can* do the
  4801. // job. It turns out that the VEXTs needed will only use DSrc once, with
  4802. // the position based purely on the combination of lane-0 and lane-1
  4803. // involved. For example
  4804. // vmov s0, s2 -> vext.32 d0, d0, d1, #1 vext.32 d0, d0, d0, #1
  4805. // vmov s1, s3 -> vext.32 d0, d1, d0, #1 vext.32 d0, d0, d0, #1
  4806. // vmov s0, s3 -> vext.32 d0, d0, d0, #1 vext.32 d0, d1, d0, #1
  4807. // vmov s1, s2 -> vext.32 d0, d0, d0, #1 vext.32 d0, d0, d1, #1
  4808. //
  4809. // Pattern of the MachineInstrs is:
  4810. // %DDst = VEXTd32 %DSrc1, %DSrc2, Lane, 14, %noreg (;implicits)
  4811. MachineInstrBuilder NewMIB;
  4812. NewMIB = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(ARM::VEXTd32),
  4813. DDst);
  4814. // On the first instruction, both DSrc and DDst may be undef if present.
  4815. // Specifically when the original instruction didn't have them as an
  4816. // <imp-use>.
  4817. unsigned CurReg = SrcLane == 1 && DstLane == 1 ? DSrc : DDst;
  4818. bool CurUndef = !MI.readsRegister(CurReg, TRI);
  4819. NewMIB.addReg(CurReg, getUndefRegState(CurUndef));
  4820. CurReg = SrcLane == 0 && DstLane == 0 ? DSrc : DDst;
  4821. CurUndef = !MI.readsRegister(CurReg, TRI);
  4822. NewMIB.addReg(CurReg, getUndefRegState(CurUndef))
  4823. .addImm(1)
  4824. .add(predOps(ARMCC::AL));
  4825. if (SrcLane == DstLane)
  4826. NewMIB.addReg(SrcReg, RegState::Implicit);
  4827. MI.setDesc(get(ARM::VEXTd32));
  4828. MIB.addReg(DDst, RegState::Define);
  4829. // On the second instruction, DDst has definitely been defined above, so
  4830. // it is not undef. DSrc, if present, can be undef as above.
  4831. CurReg = SrcLane == 1 && DstLane == 0 ? DSrc : DDst;
  4832. CurUndef = CurReg == DSrc && !MI.readsRegister(CurReg, TRI);
  4833. MIB.addReg(CurReg, getUndefRegState(CurUndef));
  4834. CurReg = SrcLane == 0 && DstLane == 1 ? DSrc : DDst;
  4835. CurUndef = CurReg == DSrc && !MI.readsRegister(CurReg, TRI);
  4836. MIB.addReg(CurReg, getUndefRegState(CurUndef))
  4837. .addImm(1)
  4838. .add(predOps(ARMCC::AL));
  4839. if (SrcLane != DstLane)
  4840. MIB.addReg(SrcReg, RegState::Implicit);
  4841. // As before, the original destination is no longer represented, add it
  4842. // implicitly.
  4843. MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
  4844. if (ImplicitSReg != 0)
  4845. MIB.addReg(ImplicitSReg, RegState::Implicit);
  4846. break;
  4847. }
  4848. }
  4849. }
  4850. //===----------------------------------------------------------------------===//
  4851. // Partial register updates
  4852. //===----------------------------------------------------------------------===//
  4853. //
  4854. // Swift renames NEON registers with 64-bit granularity. That means any
  4855. // instruction writing an S-reg implicitly reads the containing D-reg. The
  4856. // problem is mostly avoided by translating f32 operations to v2f32 operations
  4857. // on D-registers, but f32 loads are still a problem.
  4858. //
  4859. // These instructions can load an f32 into a NEON register:
  4860. //
  4861. // VLDRS - Only writes S, partial D update.
  4862. // VLD1LNd32 - Writes all D-regs, explicit partial D update, 2 uops.
  4863. // VLD1DUPd32 - Writes all D-regs, no partial reg update, 2 uops.
  4864. //
  4865. // FCONSTD can be used as a dependency-breaking instruction.
  4866. unsigned ARMBaseInstrInfo::getPartialRegUpdateClearance(
  4867. const MachineInstr &MI, unsigned OpNum,
  4868. const TargetRegisterInfo *TRI) const {
  4869. auto PartialUpdateClearance = Subtarget.getPartialUpdateClearance();
  4870. if (!PartialUpdateClearance)
  4871. return 0;
  4872. assert(TRI && "Need TRI instance");
  4873. const MachineOperand &MO = MI.getOperand(OpNum);
  4874. if (MO.readsReg())
  4875. return 0;
  4876. Register Reg = MO.getReg();
  4877. int UseOp = -1;
  4878. switch (MI.getOpcode()) {
  4879. // Normal instructions writing only an S-register.
  4880. case ARM::VLDRS:
  4881. case ARM::FCONSTS:
  4882. case ARM::VMOVSR:
  4883. case ARM::VMOVv8i8:
  4884. case ARM::VMOVv4i16:
  4885. case ARM::VMOVv2i32:
  4886. case ARM::VMOVv2f32:
  4887. case ARM::VMOVv1i64:
  4888. UseOp = MI.findRegisterUseOperandIdx(Reg, false, TRI);
  4889. break;
  4890. // Explicitly reads the dependency.
  4891. case ARM::VLD1LNd32:
  4892. UseOp = 3;
  4893. break;
  4894. default:
  4895. return 0;
  4896. }
  4897. // If this instruction actually reads a value from Reg, there is no unwanted
  4898. // dependency.
  4899. if (UseOp != -1 && MI.getOperand(UseOp).readsReg())
  4900. return 0;
  4901. // We must be able to clobber the whole D-reg.
  4902. if (Reg.isVirtual()) {
  4903. // Virtual register must be a def undef foo:ssub_0 operand.
  4904. if (!MO.getSubReg() || MI.readsVirtualRegister(Reg))
  4905. return 0;
  4906. } else if (ARM::SPRRegClass.contains(Reg)) {
  4907. // Physical register: MI must define the full D-reg.
  4908. unsigned DReg = TRI->getMatchingSuperReg(Reg, ARM::ssub_0,
  4909. &ARM::DPRRegClass);
  4910. if (!DReg || !MI.definesRegister(DReg, TRI))
  4911. return 0;
  4912. }
  4913. // MI has an unwanted D-register dependency.
  4914. // Avoid defs in the previous N instructrions.
  4915. return PartialUpdateClearance;
  4916. }
  4917. // Break a partial register dependency after getPartialRegUpdateClearance
  4918. // returned non-zero.
  4919. void ARMBaseInstrInfo::breakPartialRegDependency(
  4920. MachineInstr &MI, unsigned OpNum, const TargetRegisterInfo *TRI) const {
  4921. assert(OpNum < MI.getDesc().getNumDefs() && "OpNum is not a def");
  4922. assert(TRI && "Need TRI instance");
  4923. const MachineOperand &MO = MI.getOperand(OpNum);
  4924. Register Reg = MO.getReg();
  4925. assert(Reg.isPhysical() && "Can't break virtual register dependencies.");
  4926. unsigned DReg = Reg;
  4927. // If MI defines an S-reg, find the corresponding D super-register.
  4928. if (ARM::SPRRegClass.contains(Reg)) {
  4929. DReg = ARM::D0 + (Reg - ARM::S0) / 2;
  4930. assert(TRI->isSuperRegister(Reg, DReg) && "Register enums broken");
  4931. }
  4932. assert(ARM::DPRRegClass.contains(DReg) && "Can only break D-reg deps");
  4933. assert(MI.definesRegister(DReg, TRI) && "MI doesn't clobber full D-reg");
  4934. // FIXME: In some cases, VLDRS can be changed to a VLD1DUPd32 which defines
  4935. // the full D-register by loading the same value to both lanes. The
  4936. // instruction is micro-coded with 2 uops, so don't do this until we can
  4937. // properly schedule micro-coded instructions. The dispatcher stalls cause
  4938. // too big regressions.
  4939. // Insert the dependency-breaking FCONSTD before MI.
  4940. // 96 is the encoding of 0.5, but the actual value doesn't matter here.
  4941. BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(ARM::FCONSTD), DReg)
  4942. .addImm(96)
  4943. .add(predOps(ARMCC::AL));
  4944. MI.addRegisterKilled(DReg, TRI, true);
  4945. }
  4946. bool ARMBaseInstrInfo::hasNOP() const {
  4947. return Subtarget.getFeatureBits()[ARM::HasV6KOps];
  4948. }
  4949. bool ARMBaseInstrInfo::isSwiftFastImmShift(const MachineInstr *MI) const {
  4950. if (MI->getNumOperands() < 4)
  4951. return true;
  4952. unsigned ShOpVal = MI->getOperand(3).getImm();
  4953. unsigned ShImm = ARM_AM::getSORegOffset(ShOpVal);
  4954. // Swift supports faster shifts for: lsl 2, lsl 1, and lsr 1.
  4955. if ((ShImm == 1 && ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsr) ||
  4956. ((ShImm == 1 || ShImm == 2) &&
  4957. ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsl))
  4958. return true;
  4959. return false;
  4960. }
  4961. bool ARMBaseInstrInfo::getRegSequenceLikeInputs(
  4962. const MachineInstr &MI, unsigned DefIdx,
  4963. SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
  4964. assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index");
  4965. assert(MI.isRegSequenceLike() && "Invalid kind of instruction");
  4966. switch (MI.getOpcode()) {
  4967. case ARM::VMOVDRR:
  4968. // dX = VMOVDRR rY, rZ
  4969. // is the same as:
  4970. // dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1
  4971. // Populate the InputRegs accordingly.
  4972. // rY
  4973. const MachineOperand *MOReg = &MI.getOperand(1);
  4974. if (!MOReg->isUndef())
  4975. InputRegs.push_back(RegSubRegPairAndIdx(MOReg->getReg(),
  4976. MOReg->getSubReg(), ARM::ssub_0));
  4977. // rZ
  4978. MOReg = &MI.getOperand(2);
  4979. if (!MOReg->isUndef())
  4980. InputRegs.push_back(RegSubRegPairAndIdx(MOReg->getReg(),
  4981. MOReg->getSubReg(), ARM::ssub_1));
  4982. return true;
  4983. }
  4984. llvm_unreachable("Target dependent opcode missing");
  4985. }
  4986. bool ARMBaseInstrInfo::getExtractSubregLikeInputs(
  4987. const MachineInstr &MI, unsigned DefIdx,
  4988. RegSubRegPairAndIdx &InputReg) const {
  4989. assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index");
  4990. assert(MI.isExtractSubregLike() && "Invalid kind of instruction");
  4991. switch (MI.getOpcode()) {
  4992. case ARM::VMOVRRD:
  4993. // rX, rY = VMOVRRD dZ
  4994. // is the same as:
  4995. // rX = EXTRACT_SUBREG dZ, ssub_0
  4996. // rY = EXTRACT_SUBREG dZ, ssub_1
  4997. const MachineOperand &MOReg = MI.getOperand(2);
  4998. if (MOReg.isUndef())
  4999. return false;
  5000. InputReg.Reg = MOReg.getReg();
  5001. InputReg.SubReg = MOReg.getSubReg();
  5002. InputReg.SubIdx = DefIdx == 0 ? ARM::ssub_0 : ARM::ssub_1;
  5003. return true;
  5004. }
  5005. llvm_unreachable("Target dependent opcode missing");
  5006. }
  5007. bool ARMBaseInstrInfo::getInsertSubregLikeInputs(
  5008. const MachineInstr &MI, unsigned DefIdx, RegSubRegPair &BaseReg,
  5009. RegSubRegPairAndIdx &InsertedReg) const {
  5010. assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index");
  5011. assert(MI.isInsertSubregLike() && "Invalid kind of instruction");
  5012. switch (MI.getOpcode()) {
  5013. case ARM::VSETLNi32:
  5014. case ARM::MVE_VMOV_to_lane_32:
  5015. // dX = VSETLNi32 dY, rZ, imm
  5016. // qX = MVE_VMOV_to_lane_32 qY, rZ, imm
  5017. const MachineOperand &MOBaseReg = MI.getOperand(1);
  5018. const MachineOperand &MOInsertedReg = MI.getOperand(2);
  5019. if (MOInsertedReg.isUndef())
  5020. return false;
  5021. const MachineOperand &MOIndex = MI.getOperand(3);
  5022. BaseReg.Reg = MOBaseReg.getReg();
  5023. BaseReg.SubReg = MOBaseReg.getSubReg();
  5024. InsertedReg.Reg = MOInsertedReg.getReg();
  5025. InsertedReg.SubReg = MOInsertedReg.getSubReg();
  5026. InsertedReg.SubIdx = ARM::ssub_0 + MOIndex.getImm();
  5027. return true;
  5028. }
  5029. llvm_unreachable("Target dependent opcode missing");
  5030. }
  5031. std::pair<unsigned, unsigned>
  5032. ARMBaseInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
  5033. const unsigned Mask = ARMII::MO_OPTION_MASK;
  5034. return std::make_pair(TF & Mask, TF & ~Mask);
  5035. }
  5036. ArrayRef<std::pair<unsigned, const char *>>
  5037. ARMBaseInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
  5038. using namespace ARMII;
  5039. static const std::pair<unsigned, const char *> TargetFlags[] = {
  5040. {MO_LO16, "arm-lo16"}, {MO_HI16, "arm-hi16"}};
  5041. return ArrayRef(TargetFlags);
  5042. }
  5043. ArrayRef<std::pair<unsigned, const char *>>
  5044. ARMBaseInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
  5045. using namespace ARMII;
  5046. static const std::pair<unsigned, const char *> TargetFlags[] = {
  5047. {MO_COFFSTUB, "arm-coffstub"},
  5048. {MO_GOT, "arm-got"},
  5049. {MO_SBREL, "arm-sbrel"},
  5050. {MO_DLLIMPORT, "arm-dllimport"},
  5051. {MO_SECREL, "arm-secrel"},
  5052. {MO_NONLAZY, "arm-nonlazy"}};
  5053. return ArrayRef(TargetFlags);
  5054. }
  5055. std::optional<RegImmPair>
  5056. ARMBaseInstrInfo::isAddImmediate(const MachineInstr &MI, Register Reg) const {
  5057. int Sign = 1;
  5058. unsigned Opcode = MI.getOpcode();
  5059. int64_t Offset = 0;
  5060. // TODO: Handle cases where Reg is a super- or sub-register of the
  5061. // destination register.
  5062. const MachineOperand &Op0 = MI.getOperand(0);
  5063. if (!Op0.isReg() || Reg != Op0.getReg())
  5064. return std::nullopt;
  5065. // We describe SUBri or ADDri instructions.
  5066. if (Opcode == ARM::SUBri)
  5067. Sign = -1;
  5068. else if (Opcode != ARM::ADDri)
  5069. return std::nullopt;
  5070. // TODO: Third operand can be global address (usually some string). Since
  5071. // strings can be relocated we cannot calculate their offsets for
  5072. // now.
  5073. if (!MI.getOperand(1).isReg() || !MI.getOperand(2).isImm())
  5074. return std::nullopt;
  5075. Offset = MI.getOperand(2).getImm() * Sign;
  5076. return RegImmPair{MI.getOperand(1).getReg(), Offset};
  5077. }
  5078. bool llvm::registerDefinedBetween(unsigned Reg,
  5079. MachineBasicBlock::iterator From,
  5080. MachineBasicBlock::iterator To,
  5081. const TargetRegisterInfo *TRI) {
  5082. for (auto I = From; I != To; ++I)
  5083. if (I->modifiesRegister(Reg, TRI))
  5084. return true;
  5085. return false;
  5086. }
  5087. MachineInstr *llvm::findCMPToFoldIntoCBZ(MachineInstr *Br,
  5088. const TargetRegisterInfo *TRI) {
  5089. // Search backwards to the instruction that defines CSPR. This may or not
  5090. // be a CMP, we check that after this loop. If we find another instruction
  5091. // that reads cpsr, we return nullptr.
  5092. MachineBasicBlock::iterator CmpMI = Br;
  5093. while (CmpMI != Br->getParent()->begin()) {
  5094. --CmpMI;
  5095. if (CmpMI->modifiesRegister(ARM::CPSR, TRI))
  5096. break;
  5097. if (CmpMI->readsRegister(ARM::CPSR, TRI))
  5098. break;
  5099. }
  5100. // Check that this inst is a CMP r[0-7], #0 and that the register
  5101. // is not redefined between the cmp and the br.
  5102. if (CmpMI->getOpcode() != ARM::tCMPi8 && CmpMI->getOpcode() != ARM::t2CMPri)
  5103. return nullptr;
  5104. Register Reg = CmpMI->getOperand(0).getReg();
  5105. Register PredReg;
  5106. ARMCC::CondCodes Pred = getInstrPredicate(*CmpMI, PredReg);
  5107. if (Pred != ARMCC::AL || CmpMI->getOperand(1).getImm() != 0)
  5108. return nullptr;
  5109. if (!isARMLowRegister(Reg))
  5110. return nullptr;
  5111. if (registerDefinedBetween(Reg, CmpMI->getNextNode(), Br, TRI))
  5112. return nullptr;
  5113. return &*CmpMI;
  5114. }
  5115. unsigned llvm::ConstantMaterializationCost(unsigned Val,
  5116. const ARMSubtarget *Subtarget,
  5117. bool ForCodesize) {
  5118. if (Subtarget->isThumb()) {
  5119. if (Val <= 255) // MOV
  5120. return ForCodesize ? 2 : 1;
  5121. if (Subtarget->hasV6T2Ops() && (Val <= 0xffff || // MOV
  5122. ARM_AM::getT2SOImmVal(Val) != -1 || // MOVW
  5123. ARM_AM::getT2SOImmVal(~Val) != -1)) // MVN
  5124. return ForCodesize ? 4 : 1;
  5125. if (Val <= 510) // MOV + ADDi8
  5126. return ForCodesize ? 4 : 2;
  5127. if (~Val <= 255) // MOV + MVN
  5128. return ForCodesize ? 4 : 2;
  5129. if (ARM_AM::isThumbImmShiftedVal(Val)) // MOV + LSL
  5130. return ForCodesize ? 4 : 2;
  5131. } else {
  5132. if (ARM_AM::getSOImmVal(Val) != -1) // MOV
  5133. return ForCodesize ? 4 : 1;
  5134. if (ARM_AM::getSOImmVal(~Val) != -1) // MVN
  5135. return ForCodesize ? 4 : 1;
  5136. if (Subtarget->hasV6T2Ops() && Val <= 0xffff) // MOVW
  5137. return ForCodesize ? 4 : 1;
  5138. if (ARM_AM::isSOImmTwoPartVal(Val)) // two instrs
  5139. return ForCodesize ? 8 : 2;
  5140. if (ARM_AM::isSOImmTwoPartValNeg(Val)) // two instrs
  5141. return ForCodesize ? 8 : 2;
  5142. }
  5143. if (Subtarget->useMovt()) // MOVW + MOVT
  5144. return ForCodesize ? 8 : 2;
  5145. return ForCodesize ? 8 : 3; // Literal pool load
  5146. }
  5147. bool llvm::HasLowerConstantMaterializationCost(unsigned Val1, unsigned Val2,
  5148. const ARMSubtarget *Subtarget,
  5149. bool ForCodesize) {
  5150. // Check with ForCodesize
  5151. unsigned Cost1 = ConstantMaterializationCost(Val1, Subtarget, ForCodesize);
  5152. unsigned Cost2 = ConstantMaterializationCost(Val2, Subtarget, ForCodesize);
  5153. if (Cost1 < Cost2)
  5154. return true;
  5155. if (Cost1 > Cost2)
  5156. return false;
  5157. // If they are equal, try with !ForCodesize
  5158. return ConstantMaterializationCost(Val1, Subtarget, !ForCodesize) <
  5159. ConstantMaterializationCost(Val2, Subtarget, !ForCodesize);
  5160. }
  5161. /// Constants defining how certain sequences should be outlined.
  5162. /// This encompasses how an outlined function should be called, and what kind of
  5163. /// frame should be emitted for that outlined function.
  5164. ///
  5165. /// \p MachineOutlinerTailCall implies that the function is being created from
  5166. /// a sequence of instructions ending in a return.
  5167. ///
  5168. /// That is,
  5169. ///
  5170. /// I1 OUTLINED_FUNCTION:
  5171. /// I2 --> B OUTLINED_FUNCTION I1
  5172. /// BX LR I2
  5173. /// BX LR
  5174. ///
  5175. /// +-------------------------+--------+-----+
  5176. /// | | Thumb2 | ARM |
  5177. /// +-------------------------+--------+-----+
  5178. /// | Call overhead in Bytes | 4 | 4 |
  5179. /// | Frame overhead in Bytes | 0 | 0 |
  5180. /// | Stack fixup required | No | No |
  5181. /// +-------------------------+--------+-----+
  5182. ///
  5183. /// \p MachineOutlinerThunk implies that the function is being created from
  5184. /// a sequence of instructions ending in a call. The outlined function is
  5185. /// called with a BL instruction, and the outlined function tail-calls the
  5186. /// original call destination.
  5187. ///
  5188. /// That is,
  5189. ///
  5190. /// I1 OUTLINED_FUNCTION:
  5191. /// I2 --> BL OUTLINED_FUNCTION I1
  5192. /// BL f I2
  5193. /// B f
  5194. ///
  5195. /// +-------------------------+--------+-----+
  5196. /// | | Thumb2 | ARM |
  5197. /// +-------------------------+--------+-----+
  5198. /// | Call overhead in Bytes | 4 | 4 |
  5199. /// | Frame overhead in Bytes | 0 | 0 |
  5200. /// | Stack fixup required | No | No |
  5201. /// +-------------------------+--------+-----+
  5202. ///
  5203. /// \p MachineOutlinerNoLRSave implies that the function should be called using
  5204. /// a BL instruction, but doesn't require LR to be saved and restored. This
  5205. /// happens when LR is known to be dead.
  5206. ///
  5207. /// That is,
  5208. ///
  5209. /// I1 OUTLINED_FUNCTION:
  5210. /// I2 --> BL OUTLINED_FUNCTION I1
  5211. /// I3 I2
  5212. /// I3
  5213. /// BX LR
  5214. ///
  5215. /// +-------------------------+--------+-----+
  5216. /// | | Thumb2 | ARM |
  5217. /// +-------------------------+--------+-----+
  5218. /// | Call overhead in Bytes | 4 | 4 |
  5219. /// | Frame overhead in Bytes | 2 | 4 |
  5220. /// | Stack fixup required | No | No |
  5221. /// +-------------------------+--------+-----+
  5222. ///
  5223. /// \p MachineOutlinerRegSave implies that the function should be called with a
  5224. /// save and restore of LR to an available register. This allows us to avoid
  5225. /// stack fixups. Note that this outlining variant is compatible with the
  5226. /// NoLRSave case.
  5227. ///
  5228. /// That is,
  5229. ///
  5230. /// I1 Save LR OUTLINED_FUNCTION:
  5231. /// I2 --> BL OUTLINED_FUNCTION I1
  5232. /// I3 Restore LR I2
  5233. /// I3
  5234. /// BX LR
  5235. ///
  5236. /// +-------------------------+--------+-----+
  5237. /// | | Thumb2 | ARM |
  5238. /// +-------------------------+--------+-----+
  5239. /// | Call overhead in Bytes | 8 | 12 |
  5240. /// | Frame overhead in Bytes | 2 | 4 |
  5241. /// | Stack fixup required | No | No |
  5242. /// +-------------------------+--------+-----+
  5243. ///
  5244. /// \p MachineOutlinerDefault implies that the function should be called with
  5245. /// a save and restore of LR to the stack.
  5246. ///
  5247. /// That is,
  5248. ///
  5249. /// I1 Save LR OUTLINED_FUNCTION:
  5250. /// I2 --> BL OUTLINED_FUNCTION I1
  5251. /// I3 Restore LR I2
  5252. /// I3
  5253. /// BX LR
  5254. ///
  5255. /// +-------------------------+--------+-----+
  5256. /// | | Thumb2 | ARM |
  5257. /// +-------------------------+--------+-----+
  5258. /// | Call overhead in Bytes | 8 | 12 |
  5259. /// | Frame overhead in Bytes | 2 | 4 |
  5260. /// | Stack fixup required | Yes | Yes |
  5261. /// +-------------------------+--------+-----+
  5262. enum MachineOutlinerClass {
  5263. MachineOutlinerTailCall,
  5264. MachineOutlinerThunk,
  5265. MachineOutlinerNoLRSave,
  5266. MachineOutlinerRegSave,
  5267. MachineOutlinerDefault
  5268. };
  5269. enum MachineOutlinerMBBFlags {
  5270. LRUnavailableSomewhere = 0x2,
  5271. HasCalls = 0x4,
  5272. UnsafeRegsDead = 0x8
  5273. };
  5274. struct OutlinerCosts {
  5275. int CallTailCall;
  5276. int FrameTailCall;
  5277. int CallThunk;
  5278. int FrameThunk;
  5279. int CallNoLRSave;
  5280. int FrameNoLRSave;
  5281. int CallRegSave;
  5282. int FrameRegSave;
  5283. int CallDefault;
  5284. int FrameDefault;
  5285. int SaveRestoreLROnStack;
  5286. OutlinerCosts(const ARMSubtarget &target)
  5287. : CallTailCall(target.isThumb() ? 4 : 4),
  5288. FrameTailCall(target.isThumb() ? 0 : 0),
  5289. CallThunk(target.isThumb() ? 4 : 4),
  5290. FrameThunk(target.isThumb() ? 0 : 0),
  5291. CallNoLRSave(target.isThumb() ? 4 : 4),
  5292. FrameNoLRSave(target.isThumb() ? 2 : 4),
  5293. CallRegSave(target.isThumb() ? 8 : 12),
  5294. FrameRegSave(target.isThumb() ? 2 : 4),
  5295. CallDefault(target.isThumb() ? 8 : 12),
  5296. FrameDefault(target.isThumb() ? 2 : 4),
  5297. SaveRestoreLROnStack(target.isThumb() ? 8 : 8) {}
  5298. };
  5299. Register
  5300. ARMBaseInstrInfo::findRegisterToSaveLRTo(outliner::Candidate &C) const {
  5301. MachineFunction *MF = C.getMF();
  5302. const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
  5303. const ARMBaseRegisterInfo *ARI =
  5304. static_cast<const ARMBaseRegisterInfo *>(&TRI);
  5305. BitVector regsReserved = ARI->getReservedRegs(*MF);
  5306. // Check if there is an available register across the sequence that we can
  5307. // use.
  5308. for (Register Reg : ARM::rGPRRegClass) {
  5309. if (!(Reg < regsReserved.size() && regsReserved.test(Reg)) &&
  5310. Reg != ARM::LR && // LR is not reserved, but don't use it.
  5311. Reg != ARM::R12 && // R12 is not guaranteed to be preserved.
  5312. C.isAvailableAcrossAndOutOfSeq(Reg, TRI) &&
  5313. C.isAvailableInsideSeq(Reg, TRI))
  5314. return Reg;
  5315. }
  5316. return Register();
  5317. }
  5318. // Compute liveness of LR at the point after the interval [I, E), which
  5319. // denotes a *backward* iteration through instructions. Used only for return
  5320. // basic blocks, which do not end with a tail call.
  5321. static bool isLRAvailable(const TargetRegisterInfo &TRI,
  5322. MachineBasicBlock::reverse_iterator I,
  5323. MachineBasicBlock::reverse_iterator E) {
  5324. // At the end of the function LR dead.
  5325. bool Live = false;
  5326. for (; I != E; ++I) {
  5327. const MachineInstr &MI = *I;
  5328. // Check defs of LR.
  5329. if (MI.modifiesRegister(ARM::LR, &TRI))
  5330. Live = false;
  5331. // Check uses of LR.
  5332. unsigned Opcode = MI.getOpcode();
  5333. if (Opcode == ARM::BX_RET || Opcode == ARM::MOVPCLR ||
  5334. Opcode == ARM::SUBS_PC_LR || Opcode == ARM::tBX_RET ||
  5335. Opcode == ARM::tBXNS_RET) {
  5336. // These instructions use LR, but it's not an (explicit or implicit)
  5337. // operand.
  5338. Live = true;
  5339. continue;
  5340. }
  5341. if (MI.readsRegister(ARM::LR, &TRI))
  5342. Live = true;
  5343. }
  5344. return !Live;
  5345. }
  5346. outliner::OutlinedFunction ARMBaseInstrInfo::getOutliningCandidateInfo(
  5347. std::vector<outliner::Candidate> &RepeatedSequenceLocs) const {
  5348. outliner::Candidate &FirstCand = RepeatedSequenceLocs[0];
  5349. unsigned SequenceSize =
  5350. std::accumulate(FirstCand.front(), std::next(FirstCand.back()), 0,
  5351. [this](unsigned Sum, const MachineInstr &MI) {
  5352. return Sum + getInstSizeInBytes(MI);
  5353. });
  5354. // Properties about candidate MBBs that hold for all of them.
  5355. unsigned FlagsSetInAll = 0xF;
  5356. // Compute liveness information for each candidate, and set FlagsSetInAll.
  5357. const TargetRegisterInfo &TRI = getRegisterInfo();
  5358. for (outliner::Candidate &C : RepeatedSequenceLocs)
  5359. FlagsSetInAll &= C.Flags;
  5360. // According to the ARM Procedure Call Standard, the following are
  5361. // undefined on entry/exit from a function call:
  5362. //
  5363. // * Register R12(IP),
  5364. // * Condition codes (and thus the CPSR register)
  5365. //
  5366. // Since we control the instructions which are part of the outlined regions
  5367. // we don't need to be fully compliant with the AAPCS, but we have to
  5368. // guarantee that if a veneer is inserted at link time the code is still
  5369. // correct. Because of this, we can't outline any sequence of instructions
  5370. // where one of these registers is live into/across it. Thus, we need to
  5371. // delete those candidates.
  5372. auto CantGuaranteeValueAcrossCall = [&TRI](outliner::Candidate &C) {
  5373. // If the unsafe registers in this block are all dead, then we don't need
  5374. // to compute liveness here.
  5375. if (C.Flags & UnsafeRegsDead)
  5376. return false;
  5377. return C.isAnyUnavailableAcrossOrOutOfSeq({ARM::R12, ARM::CPSR}, TRI);
  5378. };
  5379. // Are there any candidates where those registers are live?
  5380. if (!(FlagsSetInAll & UnsafeRegsDead)) {
  5381. // Erase every candidate that violates the restrictions above. (It could be
  5382. // true that we have viable candidates, so it's not worth bailing out in
  5383. // the case that, say, 1 out of 20 candidates violate the restructions.)
  5384. llvm::erase_if(RepeatedSequenceLocs, CantGuaranteeValueAcrossCall);
  5385. // If the sequence doesn't have enough candidates left, then we're done.
  5386. if (RepeatedSequenceLocs.size() < 2)
  5387. return outliner::OutlinedFunction();
  5388. }
  5389. // We expect the majority of the outlining candidates to be in consensus with
  5390. // regard to return address sign and authentication, and branch target
  5391. // enforcement, in other words, partitioning according to all the four
  5392. // possible combinations of PAC-RET and BTI is going to yield one big subset
  5393. // and three small (likely empty) subsets. That allows us to cull incompatible
  5394. // candidates separately for PAC-RET and BTI.
  5395. // Partition the candidates in two sets: one with BTI enabled and one with BTI
  5396. // disabled. Remove the candidates from the smaller set. If they are the same
  5397. // number prefer the non-BTI ones for outlining, since they have less
  5398. // overhead.
  5399. auto NoBTI =
  5400. llvm::partition(RepeatedSequenceLocs, [](const outliner::Candidate &C) {
  5401. const ARMFunctionInfo &AFI = *C.getMF()->getInfo<ARMFunctionInfo>();
  5402. return AFI.branchTargetEnforcement();
  5403. });
  5404. if (std::distance(RepeatedSequenceLocs.begin(), NoBTI) >
  5405. std::distance(NoBTI, RepeatedSequenceLocs.end()))
  5406. RepeatedSequenceLocs.erase(NoBTI, RepeatedSequenceLocs.end());
  5407. else
  5408. RepeatedSequenceLocs.erase(RepeatedSequenceLocs.begin(), NoBTI);
  5409. if (RepeatedSequenceLocs.size() < 2)
  5410. return outliner::OutlinedFunction();
  5411. // Likewise, partition the candidates according to PAC-RET enablement.
  5412. auto NoPAC =
  5413. llvm::partition(RepeatedSequenceLocs, [](const outliner::Candidate &C) {
  5414. const ARMFunctionInfo &AFI = *C.getMF()->getInfo<ARMFunctionInfo>();
  5415. // If the function happens to not spill the LR, do not disqualify it
  5416. // from the outlining.
  5417. return AFI.shouldSignReturnAddress(true);
  5418. });
  5419. if (std::distance(RepeatedSequenceLocs.begin(), NoPAC) >
  5420. std::distance(NoPAC, RepeatedSequenceLocs.end()))
  5421. RepeatedSequenceLocs.erase(NoPAC, RepeatedSequenceLocs.end());
  5422. else
  5423. RepeatedSequenceLocs.erase(RepeatedSequenceLocs.begin(), NoPAC);
  5424. if (RepeatedSequenceLocs.size() < 2)
  5425. return outliner::OutlinedFunction();
  5426. // At this point, we have only "safe" candidates to outline. Figure out
  5427. // frame + call instruction information.
  5428. unsigned LastInstrOpcode = RepeatedSequenceLocs[0].back()->getOpcode();
  5429. // Helper lambda which sets call information for every candidate.
  5430. auto SetCandidateCallInfo =
  5431. [&RepeatedSequenceLocs](unsigned CallID, unsigned NumBytesForCall) {
  5432. for (outliner::Candidate &C : RepeatedSequenceLocs)
  5433. C.setCallInfo(CallID, NumBytesForCall);
  5434. };
  5435. OutlinerCosts Costs(Subtarget);
  5436. const auto &SomeMFI =
  5437. *RepeatedSequenceLocs.front().getMF()->getInfo<ARMFunctionInfo>();
  5438. // Adjust costs to account for the BTI instructions.
  5439. if (SomeMFI.branchTargetEnforcement()) {
  5440. Costs.FrameDefault += 4;
  5441. Costs.FrameNoLRSave += 4;
  5442. Costs.FrameRegSave += 4;
  5443. Costs.FrameTailCall += 4;
  5444. Costs.FrameThunk += 4;
  5445. }
  5446. // Adjust costs to account for sign and authentication instructions.
  5447. if (SomeMFI.shouldSignReturnAddress(true)) {
  5448. Costs.CallDefault += 8; // +PAC instr, +AUT instr
  5449. Costs.SaveRestoreLROnStack += 8; // +PAC instr, +AUT instr
  5450. }
  5451. unsigned FrameID = MachineOutlinerDefault;
  5452. unsigned NumBytesToCreateFrame = Costs.FrameDefault;
  5453. // If the last instruction in any candidate is a terminator, then we should
  5454. // tail call all of the candidates.
  5455. if (RepeatedSequenceLocs[0].back()->isTerminator()) {
  5456. FrameID = MachineOutlinerTailCall;
  5457. NumBytesToCreateFrame = Costs.FrameTailCall;
  5458. SetCandidateCallInfo(MachineOutlinerTailCall, Costs.CallTailCall);
  5459. } else if (LastInstrOpcode == ARM::BL || LastInstrOpcode == ARM::BLX ||
  5460. LastInstrOpcode == ARM::BLX_noip || LastInstrOpcode == ARM::tBL ||
  5461. LastInstrOpcode == ARM::tBLXr ||
  5462. LastInstrOpcode == ARM::tBLXr_noip ||
  5463. LastInstrOpcode == ARM::tBLXi) {
  5464. FrameID = MachineOutlinerThunk;
  5465. NumBytesToCreateFrame = Costs.FrameThunk;
  5466. SetCandidateCallInfo(MachineOutlinerThunk, Costs.CallThunk);
  5467. } else {
  5468. // We need to decide how to emit calls + frames. We can always emit the same
  5469. // frame if we don't need to save to the stack. If we have to save to the
  5470. // stack, then we need a different frame.
  5471. unsigned NumBytesNoStackCalls = 0;
  5472. std::vector<outliner::Candidate> CandidatesWithoutStackFixups;
  5473. for (outliner::Candidate &C : RepeatedSequenceLocs) {
  5474. // LR liveness is overestimated in return blocks, unless they end with a
  5475. // tail call.
  5476. const auto Last = C.getMBB()->rbegin();
  5477. const bool LRIsAvailable =
  5478. C.getMBB()->isReturnBlock() && !Last->isCall()
  5479. ? isLRAvailable(TRI, Last,
  5480. (MachineBasicBlock::reverse_iterator)C.front())
  5481. : C.isAvailableAcrossAndOutOfSeq(ARM::LR, TRI);
  5482. if (LRIsAvailable) {
  5483. FrameID = MachineOutlinerNoLRSave;
  5484. NumBytesNoStackCalls += Costs.CallNoLRSave;
  5485. C.setCallInfo(MachineOutlinerNoLRSave, Costs.CallNoLRSave);
  5486. CandidatesWithoutStackFixups.push_back(C);
  5487. }
  5488. // Is an unused register available? If so, we won't modify the stack, so
  5489. // we can outline with the same frame type as those that don't save LR.
  5490. else if (findRegisterToSaveLRTo(C)) {
  5491. FrameID = MachineOutlinerRegSave;
  5492. NumBytesNoStackCalls += Costs.CallRegSave;
  5493. C.setCallInfo(MachineOutlinerRegSave, Costs.CallRegSave);
  5494. CandidatesWithoutStackFixups.push_back(C);
  5495. }
  5496. // Is SP used in the sequence at all? If not, we don't have to modify
  5497. // the stack, so we are guaranteed to get the same frame.
  5498. else if (C.isAvailableInsideSeq(ARM::SP, TRI)) {
  5499. NumBytesNoStackCalls += Costs.CallDefault;
  5500. C.setCallInfo(MachineOutlinerDefault, Costs.CallDefault);
  5501. CandidatesWithoutStackFixups.push_back(C);
  5502. }
  5503. // If we outline this, we need to modify the stack. Pretend we don't
  5504. // outline this by saving all of its bytes.
  5505. else
  5506. NumBytesNoStackCalls += SequenceSize;
  5507. }
  5508. // If there are no places where we have to save LR, then note that we don't
  5509. // have to update the stack. Otherwise, give every candidate the default
  5510. // call type
  5511. if (NumBytesNoStackCalls <=
  5512. RepeatedSequenceLocs.size() * Costs.CallDefault) {
  5513. RepeatedSequenceLocs = CandidatesWithoutStackFixups;
  5514. FrameID = MachineOutlinerNoLRSave;
  5515. } else
  5516. SetCandidateCallInfo(MachineOutlinerDefault, Costs.CallDefault);
  5517. }
  5518. // Does every candidate's MBB contain a call? If so, then we might have a
  5519. // call in the range.
  5520. if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
  5521. // check if the range contains a call. These require a save + restore of
  5522. // the link register.
  5523. if (std::any_of(FirstCand.front(), FirstCand.back(),
  5524. [](const MachineInstr &MI) { return MI.isCall(); }))
  5525. NumBytesToCreateFrame += Costs.SaveRestoreLROnStack;
  5526. // Handle the last instruction separately. If it is tail call, then the
  5527. // last instruction is a call, we don't want to save + restore in this
  5528. // case. However, it could be possible that the last instruction is a
  5529. // call without it being valid to tail call this sequence. We should
  5530. // consider this as well.
  5531. else if (FrameID != MachineOutlinerThunk &&
  5532. FrameID != MachineOutlinerTailCall && FirstCand.back()->isCall())
  5533. NumBytesToCreateFrame += Costs.SaveRestoreLROnStack;
  5534. }
  5535. return outliner::OutlinedFunction(RepeatedSequenceLocs, SequenceSize,
  5536. NumBytesToCreateFrame, FrameID);
  5537. }
  5538. bool ARMBaseInstrInfo::checkAndUpdateStackOffset(MachineInstr *MI,
  5539. int64_t Fixup,
  5540. bool Updt) const {
  5541. int SPIdx = MI->findRegisterUseOperandIdx(ARM::SP);
  5542. unsigned AddrMode = (MI->getDesc().TSFlags & ARMII::AddrModeMask);
  5543. if (SPIdx < 0)
  5544. // No SP operand
  5545. return true;
  5546. else if (SPIdx != 1 && (AddrMode != ARMII::AddrModeT2_i8s4 || SPIdx != 2))
  5547. // If SP is not the base register we can't do much
  5548. return false;
  5549. // Stack might be involved but addressing mode doesn't handle any offset.
  5550. // Rq: AddrModeT1_[1|2|4] don't operate on SP
  5551. if (AddrMode == ARMII::AddrMode1 || // Arithmetic instructions
  5552. AddrMode == ARMII::AddrMode4 || // Load/Store Multiple
  5553. AddrMode == ARMII::AddrMode6 || // Neon Load/Store Multiple
  5554. AddrMode == ARMII::AddrModeT2_so || // SP can't be used as based register
  5555. AddrMode == ARMII::AddrModeT2_pc || // PCrel access
  5556. AddrMode == ARMII::AddrMode2 || // Used by PRE and POST indexed LD/ST
  5557. AddrMode == ARMII::AddrModeT2_i7 || // v8.1-M MVE
  5558. AddrMode == ARMII::AddrModeT2_i7s2 || // v8.1-M MVE
  5559. AddrMode == ARMII::AddrModeT2_i7s4 || // v8.1-M sys regs VLDR/VSTR
  5560. AddrMode == ARMII::AddrModeNone ||
  5561. AddrMode == ARMII::AddrModeT2_i8 || // Pre/Post inc instructions
  5562. AddrMode == ARMII::AddrModeT2_i8neg) // Always negative imm
  5563. return false;
  5564. unsigned NumOps = MI->getDesc().getNumOperands();
  5565. unsigned ImmIdx = NumOps - 3;
  5566. const MachineOperand &Offset = MI->getOperand(ImmIdx);
  5567. assert(Offset.isImm() && "Is not an immediate");
  5568. int64_t OffVal = Offset.getImm();
  5569. if (OffVal < 0)
  5570. // Don't override data if the are below SP.
  5571. return false;
  5572. unsigned NumBits = 0;
  5573. unsigned Scale = 1;
  5574. switch (AddrMode) {
  5575. case ARMII::AddrMode3:
  5576. if (ARM_AM::getAM3Op(OffVal) == ARM_AM::sub)
  5577. return false;
  5578. OffVal = ARM_AM::getAM3Offset(OffVal);
  5579. NumBits = 8;
  5580. break;
  5581. case ARMII::AddrMode5:
  5582. if (ARM_AM::getAM5Op(OffVal) == ARM_AM::sub)
  5583. return false;
  5584. OffVal = ARM_AM::getAM5Offset(OffVal);
  5585. NumBits = 8;
  5586. Scale = 4;
  5587. break;
  5588. case ARMII::AddrMode5FP16:
  5589. if (ARM_AM::getAM5FP16Op(OffVal) == ARM_AM::sub)
  5590. return false;
  5591. OffVal = ARM_AM::getAM5FP16Offset(OffVal);
  5592. NumBits = 8;
  5593. Scale = 2;
  5594. break;
  5595. case ARMII::AddrModeT2_i8pos:
  5596. NumBits = 8;
  5597. break;
  5598. case ARMII::AddrModeT2_i8s4:
  5599. // FIXME: Values are already scaled in this addressing mode.
  5600. assert((Fixup & 3) == 0 && "Can't encode this offset!");
  5601. NumBits = 10;
  5602. break;
  5603. case ARMII::AddrModeT2_ldrex:
  5604. NumBits = 8;
  5605. Scale = 4;
  5606. break;
  5607. case ARMII::AddrModeT2_i12:
  5608. case ARMII::AddrMode_i12:
  5609. NumBits = 12;
  5610. break;
  5611. case ARMII::AddrModeT1_s: // SP-relative LD/ST
  5612. NumBits = 8;
  5613. Scale = 4;
  5614. break;
  5615. default:
  5616. llvm_unreachable("Unsupported addressing mode!");
  5617. }
  5618. // Make sure the offset is encodable for instructions that scale the
  5619. // immediate.
  5620. assert(((OffVal * Scale + Fixup) & (Scale - 1)) == 0 &&
  5621. "Can't encode this offset!");
  5622. OffVal += Fixup / Scale;
  5623. unsigned Mask = (1 << NumBits) - 1;
  5624. if (OffVal <= Mask) {
  5625. if (Updt)
  5626. MI->getOperand(ImmIdx).setImm(OffVal);
  5627. return true;
  5628. }
  5629. return false;
  5630. }
  5631. void ARMBaseInstrInfo::mergeOutliningCandidateAttributes(
  5632. Function &F, std::vector<outliner::Candidate> &Candidates) const {
  5633. outliner::Candidate &C = Candidates.front();
  5634. // branch-target-enforcement is guaranteed to be consistent between all
  5635. // candidates, so we only need to look at one.
  5636. const Function &CFn = C.getMF()->getFunction();
  5637. if (CFn.hasFnAttribute("branch-target-enforcement"))
  5638. F.addFnAttr(CFn.getFnAttribute("branch-target-enforcement"));
  5639. ARMGenInstrInfo::mergeOutliningCandidateAttributes(F, Candidates);
  5640. }
  5641. bool ARMBaseInstrInfo::isFunctionSafeToOutlineFrom(
  5642. MachineFunction &MF, bool OutlineFromLinkOnceODRs) const {
  5643. const Function &F = MF.getFunction();
  5644. // Can F be deduplicated by the linker? If it can, don't outline from it.
  5645. if (!OutlineFromLinkOnceODRs && F.hasLinkOnceODRLinkage())
  5646. return false;
  5647. // Don't outline from functions with section markings; the program could
  5648. // expect that all the code is in the named section.
  5649. // FIXME: Allow outlining from multiple functions with the same section
  5650. // marking.
  5651. if (F.hasSection())
  5652. return false;
  5653. // FIXME: Thumb1 outlining is not handled
  5654. if (MF.getInfo<ARMFunctionInfo>()->isThumb1OnlyFunction())
  5655. return false;
  5656. // It's safe to outline from MF.
  5657. return true;
  5658. }
  5659. bool ARMBaseInstrInfo::isMBBSafeToOutlineFrom(MachineBasicBlock &MBB,
  5660. unsigned &Flags) const {
  5661. // Check if LR is available through all of the MBB. If it's not, then set
  5662. // a flag.
  5663. assert(MBB.getParent()->getRegInfo().tracksLiveness() &&
  5664. "Suitable Machine Function for outlining must track liveness");
  5665. LiveRegUnits LRU(getRegisterInfo());
  5666. for (MachineInstr &MI : llvm::reverse(MBB))
  5667. LRU.accumulate(MI);
  5668. // Check if each of the unsafe registers are available...
  5669. bool R12AvailableInBlock = LRU.available(ARM::R12);
  5670. bool CPSRAvailableInBlock = LRU.available(ARM::CPSR);
  5671. // If all of these are dead (and not live out), we know we don't have to check
  5672. // them later.
  5673. if (R12AvailableInBlock && CPSRAvailableInBlock)
  5674. Flags |= MachineOutlinerMBBFlags::UnsafeRegsDead;
  5675. // Now, add the live outs to the set.
  5676. LRU.addLiveOuts(MBB);
  5677. // If any of these registers is available in the MBB, but also a live out of
  5678. // the block, then we know outlining is unsafe.
  5679. if (R12AvailableInBlock && !LRU.available(ARM::R12))
  5680. return false;
  5681. if (CPSRAvailableInBlock && !LRU.available(ARM::CPSR))
  5682. return false;
  5683. // Check if there's a call inside this MachineBasicBlock. If there is, then
  5684. // set a flag.
  5685. if (any_of(MBB, [](MachineInstr &MI) { return MI.isCall(); }))
  5686. Flags |= MachineOutlinerMBBFlags::HasCalls;
  5687. // LR liveness is overestimated in return blocks.
  5688. bool LRIsAvailable =
  5689. MBB.isReturnBlock() && !MBB.back().isCall()
  5690. ? isLRAvailable(getRegisterInfo(), MBB.rbegin(), MBB.rend())
  5691. : LRU.available(ARM::LR);
  5692. if (!LRIsAvailable)
  5693. Flags |= MachineOutlinerMBBFlags::LRUnavailableSomewhere;
  5694. return true;
  5695. }
  5696. outliner::InstrType
  5697. ARMBaseInstrInfo::getOutliningType(MachineBasicBlock::iterator &MIT,
  5698. unsigned Flags) const {
  5699. MachineInstr &MI = *MIT;
  5700. const TargetRegisterInfo *TRI = &getRegisterInfo();
  5701. // Be conservative with inline ASM
  5702. if (MI.isInlineAsm())
  5703. return outliner::InstrType::Illegal;
  5704. // Don't allow debug values to impact outlining type.
  5705. if (MI.isDebugInstr() || MI.isIndirectDebugValue())
  5706. return outliner::InstrType::Invisible;
  5707. // At this point, KILL or IMPLICIT_DEF instructions don't really tell us much
  5708. // so we can go ahead and skip over them.
  5709. if (MI.isKill() || MI.isImplicitDef())
  5710. return outliner::InstrType::Invisible;
  5711. // PIC instructions contain labels, outlining them would break offset
  5712. // computing. unsigned Opc = MI.getOpcode();
  5713. unsigned Opc = MI.getOpcode();
  5714. if (Opc == ARM::tPICADD || Opc == ARM::PICADD || Opc == ARM::PICSTR ||
  5715. Opc == ARM::PICSTRB || Opc == ARM::PICSTRH || Opc == ARM::PICLDR ||
  5716. Opc == ARM::PICLDRB || Opc == ARM::PICLDRH || Opc == ARM::PICLDRSB ||
  5717. Opc == ARM::PICLDRSH || Opc == ARM::t2LDRpci_pic ||
  5718. Opc == ARM::t2MOVi16_ga_pcrel || Opc == ARM::t2MOVTi16_ga_pcrel ||
  5719. Opc == ARM::t2MOV_ga_pcrel)
  5720. return outliner::InstrType::Illegal;
  5721. // Be conservative with ARMv8.1 MVE instructions.
  5722. if (Opc == ARM::t2BF_LabelPseudo || Opc == ARM::t2DoLoopStart ||
  5723. Opc == ARM::t2DoLoopStartTP || Opc == ARM::t2WhileLoopStart ||
  5724. Opc == ARM::t2WhileLoopStartLR || Opc == ARM::t2WhileLoopStartTP ||
  5725. Opc == ARM::t2LoopDec || Opc == ARM::t2LoopEnd ||
  5726. Opc == ARM::t2LoopEndDec)
  5727. return outliner::InstrType::Illegal;
  5728. const MCInstrDesc &MCID = MI.getDesc();
  5729. uint64_t MIFlags = MCID.TSFlags;
  5730. if ((MIFlags & ARMII::DomainMask) == ARMII::DomainMVE)
  5731. return outliner::InstrType::Illegal;
  5732. // Is this a terminator for a basic block?
  5733. if (MI.isTerminator()) {
  5734. // Don't outline if the branch is not unconditional.
  5735. if (isPredicated(MI))
  5736. return outliner::InstrType::Illegal;
  5737. // Is this the end of a function?
  5738. if (MI.getParent()->succ_empty())
  5739. return outliner::InstrType::Legal;
  5740. // It's not, so don't outline it.
  5741. return outliner::InstrType::Illegal;
  5742. }
  5743. // Make sure none of the operands are un-outlinable.
  5744. for (const MachineOperand &MOP : MI.operands()) {
  5745. if (MOP.isCPI() || MOP.isJTI() || MOP.isCFIIndex() || MOP.isFI() ||
  5746. MOP.isTargetIndex())
  5747. return outliner::InstrType::Illegal;
  5748. }
  5749. // Don't outline if link register or program counter value are used.
  5750. if (MI.readsRegister(ARM::LR, TRI) || MI.readsRegister(ARM::PC, TRI))
  5751. return outliner::InstrType::Illegal;
  5752. if (MI.isCall()) {
  5753. // Get the function associated with the call. Look at each operand and find
  5754. // the one that represents the calle and get its name.
  5755. const Function *Callee = nullptr;
  5756. for (const MachineOperand &MOP : MI.operands()) {
  5757. if (MOP.isGlobal()) {
  5758. Callee = dyn_cast<Function>(MOP.getGlobal());
  5759. break;
  5760. }
  5761. }
  5762. // Dont't outline calls to "mcount" like functions, in particular Linux
  5763. // kernel function tracing relies on it.
  5764. if (Callee &&
  5765. (Callee->getName() == "\01__gnu_mcount_nc" ||
  5766. Callee->getName() == "\01mcount" || Callee->getName() == "__mcount"))
  5767. return outliner::InstrType::Illegal;
  5768. // If we don't know anything about the callee, assume it depends on the
  5769. // stack layout of the caller. In that case, it's only legal to outline
  5770. // as a tail-call. Explicitly list the call instructions we know about so
  5771. // we don't get unexpected results with call pseudo-instructions.
  5772. auto UnknownCallOutlineType = outliner::InstrType::Illegal;
  5773. if (Opc == ARM::BL || Opc == ARM::tBL || Opc == ARM::BLX ||
  5774. Opc == ARM::BLX_noip || Opc == ARM::tBLXr || Opc == ARM::tBLXr_noip ||
  5775. Opc == ARM::tBLXi)
  5776. UnknownCallOutlineType = outliner::InstrType::LegalTerminator;
  5777. if (!Callee)
  5778. return UnknownCallOutlineType;
  5779. // We have a function we have information about. Check if it's something we
  5780. // can safely outline.
  5781. MachineFunction *MF = MI.getParent()->getParent();
  5782. MachineFunction *CalleeMF = MF->getMMI().getMachineFunction(*Callee);
  5783. // We don't know what's going on with the callee at all. Don't touch it.
  5784. if (!CalleeMF)
  5785. return UnknownCallOutlineType;
  5786. // Check if we know anything about the callee saves on the function. If we
  5787. // don't, then don't touch it, since that implies that we haven't computed
  5788. // anything about its stack frame yet.
  5789. MachineFrameInfo &MFI = CalleeMF->getFrameInfo();
  5790. if (!MFI.isCalleeSavedInfoValid() || MFI.getStackSize() > 0 ||
  5791. MFI.getNumObjects() > 0)
  5792. return UnknownCallOutlineType;
  5793. // At this point, we can say that CalleeMF ought to not pass anything on the
  5794. // stack. Therefore, we can outline it.
  5795. return outliner::InstrType::Legal;
  5796. }
  5797. // Since calls are handled, don't touch LR or PC
  5798. if (MI.modifiesRegister(ARM::LR, TRI) || MI.modifiesRegister(ARM::PC, TRI))
  5799. return outliner::InstrType::Illegal;
  5800. // Does this use the stack?
  5801. if (MI.modifiesRegister(ARM::SP, TRI) || MI.readsRegister(ARM::SP, TRI)) {
  5802. // True if there is no chance that any outlined candidate from this range
  5803. // could require stack fixups. That is, both
  5804. // * LR is available in the range (No save/restore around call)
  5805. // * The range doesn't include calls (No save/restore in outlined frame)
  5806. // are true.
  5807. // These conditions also ensure correctness of the return address
  5808. // authentication - we insert sign and authentication instructions only if
  5809. // we save/restore LR on stack, but then this condition ensures that the
  5810. // outlined range does not modify the SP, therefore the SP value used for
  5811. // signing is the same as the one used for authentication.
  5812. // FIXME: This is very restrictive; the flags check the whole block,
  5813. // not just the bit we will try to outline.
  5814. bool MightNeedStackFixUp =
  5815. (Flags & (MachineOutlinerMBBFlags::LRUnavailableSomewhere |
  5816. MachineOutlinerMBBFlags::HasCalls));
  5817. if (!MightNeedStackFixUp)
  5818. return outliner::InstrType::Legal;
  5819. // Any modification of SP will break our code to save/restore LR.
  5820. // FIXME: We could handle some instructions which add a constant offset to
  5821. // SP, with a bit more work.
  5822. if (MI.modifiesRegister(ARM::SP, TRI))
  5823. return outliner::InstrType::Illegal;
  5824. // At this point, we have a stack instruction that we might need to fix up.
  5825. // up. We'll handle it if it's a load or store.
  5826. if (checkAndUpdateStackOffset(&MI, Subtarget.getStackAlignment().value(),
  5827. false))
  5828. return outliner::InstrType::Legal;
  5829. // We can't fix it up, so don't outline it.
  5830. return outliner::InstrType::Illegal;
  5831. }
  5832. // Be conservative with IT blocks.
  5833. if (MI.readsRegister(ARM::ITSTATE, TRI) ||
  5834. MI.modifiesRegister(ARM::ITSTATE, TRI))
  5835. return outliner::InstrType::Illegal;
  5836. // Don't outline positions.
  5837. if (MI.isPosition())
  5838. return outliner::InstrType::Illegal;
  5839. return outliner::InstrType::Legal;
  5840. }
  5841. void ARMBaseInstrInfo::fixupPostOutline(MachineBasicBlock &MBB) const {
  5842. for (MachineInstr &MI : MBB) {
  5843. checkAndUpdateStackOffset(&MI, Subtarget.getStackAlignment().value(), true);
  5844. }
  5845. }
  5846. void ARMBaseInstrInfo::saveLROnStack(MachineBasicBlock &MBB,
  5847. MachineBasicBlock::iterator It, bool CFI,
  5848. bool Auth) const {
  5849. int Align = std::max(Subtarget.getStackAlignment().value(), uint64_t(8));
  5850. assert(Align >= 8 && Align <= 256);
  5851. if (Auth) {
  5852. assert(Subtarget.isThumb2());
  5853. // Compute PAC in R12. Outlining ensures R12 is dead across the outlined
  5854. // sequence.
  5855. BuildMI(MBB, It, DebugLoc(), get(ARM::t2PAC))
  5856. .setMIFlags(MachineInstr::FrameSetup);
  5857. BuildMI(MBB, It, DebugLoc(), get(ARM::t2STRD_PRE), ARM::SP)
  5858. .addReg(ARM::R12, RegState::Kill)
  5859. .addReg(ARM::LR, RegState::Kill)
  5860. .addReg(ARM::SP)
  5861. .addImm(-Align)
  5862. .add(predOps(ARMCC::AL))
  5863. .setMIFlags(MachineInstr::FrameSetup);
  5864. } else {
  5865. unsigned Opc = Subtarget.isThumb() ? ARM::t2STR_PRE : ARM::STR_PRE_IMM;
  5866. BuildMI(MBB, It, DebugLoc(), get(Opc), ARM::SP)
  5867. .addReg(ARM::LR, RegState::Kill)
  5868. .addReg(ARM::SP)
  5869. .addImm(-Align)
  5870. .add(predOps(ARMCC::AL))
  5871. .setMIFlags(MachineInstr::FrameSetup);
  5872. }
  5873. if (!CFI)
  5874. return;
  5875. MachineFunction &MF = *MBB.getParent();
  5876. // Add a CFI, saying CFA is offset by Align bytes from SP.
  5877. int64_t StackPosEntry =
  5878. MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, Align));
  5879. BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
  5880. .addCFIIndex(StackPosEntry)
  5881. .setMIFlags(MachineInstr::FrameSetup);
  5882. // Add a CFI saying that the LR that we want to find is now higher than
  5883. // before.
  5884. int LROffset = Auth ? Align - 4 : Align;
  5885. const MCRegisterInfo *MRI = Subtarget.getRegisterInfo();
  5886. unsigned DwarfLR = MRI->getDwarfRegNum(ARM::LR, true);
  5887. int64_t LRPosEntry = MF.addFrameInst(
  5888. MCCFIInstruction::createOffset(nullptr, DwarfLR, -LROffset));
  5889. BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
  5890. .addCFIIndex(LRPosEntry)
  5891. .setMIFlags(MachineInstr::FrameSetup);
  5892. if (Auth) {
  5893. // Add a CFI for the location of the return adddress PAC.
  5894. unsigned DwarfRAC = MRI->getDwarfRegNum(ARM::RA_AUTH_CODE, true);
  5895. int64_t RACPosEntry = MF.addFrameInst(
  5896. MCCFIInstruction::createOffset(nullptr, DwarfRAC, -Align));
  5897. BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
  5898. .addCFIIndex(RACPosEntry)
  5899. .setMIFlags(MachineInstr::FrameSetup);
  5900. }
  5901. }
  5902. void ARMBaseInstrInfo::emitCFIForLRSaveToReg(MachineBasicBlock &MBB,
  5903. MachineBasicBlock::iterator It,
  5904. Register Reg) const {
  5905. MachineFunction &MF = *MBB.getParent();
  5906. const MCRegisterInfo *MRI = Subtarget.getRegisterInfo();
  5907. unsigned DwarfLR = MRI->getDwarfRegNum(ARM::LR, true);
  5908. unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
  5909. int64_t LRPosEntry = MF.addFrameInst(
  5910. MCCFIInstruction::createRegister(nullptr, DwarfLR, DwarfReg));
  5911. BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
  5912. .addCFIIndex(LRPosEntry)
  5913. .setMIFlags(MachineInstr::FrameSetup);
  5914. }
  5915. void ARMBaseInstrInfo::restoreLRFromStack(MachineBasicBlock &MBB,
  5916. MachineBasicBlock::iterator It,
  5917. bool CFI, bool Auth) const {
  5918. int Align = Subtarget.getStackAlignment().value();
  5919. if (Auth) {
  5920. assert(Subtarget.isThumb2());
  5921. // Restore return address PAC and LR.
  5922. BuildMI(MBB, It, DebugLoc(), get(ARM::t2LDRD_POST))
  5923. .addReg(ARM::R12, RegState::Define)
  5924. .addReg(ARM::LR, RegState::Define)
  5925. .addReg(ARM::SP, RegState::Define)
  5926. .addReg(ARM::SP)
  5927. .addImm(Align)
  5928. .add(predOps(ARMCC::AL))
  5929. .setMIFlags(MachineInstr::FrameDestroy);
  5930. // LR authentication is after the CFI instructions, below.
  5931. } else {
  5932. unsigned Opc = Subtarget.isThumb() ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
  5933. MachineInstrBuilder MIB = BuildMI(MBB, It, DebugLoc(), get(Opc), ARM::LR)
  5934. .addReg(ARM::SP, RegState::Define)
  5935. .addReg(ARM::SP);
  5936. if (!Subtarget.isThumb())
  5937. MIB.addReg(0);
  5938. MIB.addImm(Subtarget.getStackAlignment().value())
  5939. .add(predOps(ARMCC::AL))
  5940. .setMIFlags(MachineInstr::FrameDestroy);
  5941. }
  5942. if (CFI) {
  5943. // Now stack has moved back up...
  5944. MachineFunction &MF = *MBB.getParent();
  5945. const MCRegisterInfo *MRI = Subtarget.getRegisterInfo();
  5946. unsigned DwarfLR = MRI->getDwarfRegNum(ARM::LR, true);
  5947. int64_t StackPosEntry =
  5948. MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 0));
  5949. BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
  5950. .addCFIIndex(StackPosEntry)
  5951. .setMIFlags(MachineInstr::FrameDestroy);
  5952. // ... and we have restored LR.
  5953. int64_t LRPosEntry =
  5954. MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, DwarfLR));
  5955. BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
  5956. .addCFIIndex(LRPosEntry)
  5957. .setMIFlags(MachineInstr::FrameDestroy);
  5958. if (Auth) {
  5959. unsigned DwarfRAC = MRI->getDwarfRegNum(ARM::RA_AUTH_CODE, true);
  5960. int64_t Entry =
  5961. MF.addFrameInst(MCCFIInstruction::createUndefined(nullptr, DwarfRAC));
  5962. BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
  5963. .addCFIIndex(Entry)
  5964. .setMIFlags(MachineInstr::FrameDestroy);
  5965. }
  5966. }
  5967. if (Auth)
  5968. BuildMI(MBB, It, DebugLoc(), get(ARM::t2AUT));
  5969. }
  5970. void ARMBaseInstrInfo::emitCFIForLRRestoreFromReg(
  5971. MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
  5972. MachineFunction &MF = *MBB.getParent();
  5973. const MCRegisterInfo *MRI = Subtarget.getRegisterInfo();
  5974. unsigned DwarfLR = MRI->getDwarfRegNum(ARM::LR, true);
  5975. int64_t LRPosEntry =
  5976. MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, DwarfLR));
  5977. BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
  5978. .addCFIIndex(LRPosEntry)
  5979. .setMIFlags(MachineInstr::FrameDestroy);
  5980. }
  5981. void ARMBaseInstrInfo::buildOutlinedFrame(
  5982. MachineBasicBlock &MBB, MachineFunction &MF,
  5983. const outliner::OutlinedFunction &OF) const {
  5984. // For thunk outlining, rewrite the last instruction from a call to a
  5985. // tail-call.
  5986. if (OF.FrameConstructionID == MachineOutlinerThunk) {
  5987. MachineInstr *Call = &*--MBB.instr_end();
  5988. bool isThumb = Subtarget.isThumb();
  5989. unsigned FuncOp = isThumb ? 2 : 0;
  5990. unsigned Opc = Call->getOperand(FuncOp).isReg()
  5991. ? isThumb ? ARM::tTAILJMPr : ARM::TAILJMPr
  5992. : isThumb ? Subtarget.isTargetMachO() ? ARM::tTAILJMPd
  5993. : ARM::tTAILJMPdND
  5994. : ARM::TAILJMPd;
  5995. MachineInstrBuilder MIB = BuildMI(MBB, MBB.end(), DebugLoc(), get(Opc))
  5996. .add(Call->getOperand(FuncOp));
  5997. if (isThumb && !Call->getOperand(FuncOp).isReg())
  5998. MIB.add(predOps(ARMCC::AL));
  5999. Call->eraseFromParent();
  6000. }
  6001. // Is there a call in the outlined range?
  6002. auto IsNonTailCall = [](MachineInstr &MI) {
  6003. return MI.isCall() && !MI.isReturn();
  6004. };
  6005. if (llvm::any_of(MBB.instrs(), IsNonTailCall)) {
  6006. MachineBasicBlock::iterator It = MBB.begin();
  6007. MachineBasicBlock::iterator Et = MBB.end();
  6008. if (OF.FrameConstructionID == MachineOutlinerTailCall ||
  6009. OF.FrameConstructionID == MachineOutlinerThunk)
  6010. Et = std::prev(MBB.end());
  6011. // We have to save and restore LR, we need to add it to the liveins if it
  6012. // is not already part of the set. This is suffient since outlined
  6013. // functions only have one block.
  6014. if (!MBB.isLiveIn(ARM::LR))
  6015. MBB.addLiveIn(ARM::LR);
  6016. // Insert a save before the outlined region
  6017. bool Auth = OF.Candidates.front()
  6018. .getMF()
  6019. ->getInfo<ARMFunctionInfo>()
  6020. ->shouldSignReturnAddress(true);
  6021. saveLROnStack(MBB, It, true, Auth);
  6022. // Fix up the instructions in the range, since we're going to modify the
  6023. // stack.
  6024. assert(OF.FrameConstructionID != MachineOutlinerDefault &&
  6025. "Can only fix up stack references once");
  6026. fixupPostOutline(MBB);
  6027. // Insert a restore before the terminator for the function. Restore LR.
  6028. restoreLRFromStack(MBB, Et, true, Auth);
  6029. }
  6030. // If this is a tail call outlined function, then there's already a return.
  6031. if (OF.FrameConstructionID == MachineOutlinerTailCall ||
  6032. OF.FrameConstructionID == MachineOutlinerThunk)
  6033. return;
  6034. // Here we have to insert the return ourselves. Get the correct opcode from
  6035. // current feature set.
  6036. BuildMI(MBB, MBB.end(), DebugLoc(), get(Subtarget.getReturnOpcode()))
  6037. .add(predOps(ARMCC::AL));
  6038. // Did we have to modify the stack by saving the link register?
  6039. if (OF.FrameConstructionID != MachineOutlinerDefault &&
  6040. OF.Candidates[0].CallConstructionID != MachineOutlinerDefault)
  6041. return;
  6042. // We modified the stack.
  6043. // Walk over the basic block and fix up all the stack accesses.
  6044. fixupPostOutline(MBB);
  6045. }
  6046. MachineBasicBlock::iterator ARMBaseInstrInfo::insertOutlinedCall(
  6047. Module &M, MachineBasicBlock &MBB, MachineBasicBlock::iterator &It,
  6048. MachineFunction &MF, outliner::Candidate &C) const {
  6049. MachineInstrBuilder MIB;
  6050. MachineBasicBlock::iterator CallPt;
  6051. unsigned Opc;
  6052. bool isThumb = Subtarget.isThumb();
  6053. // Are we tail calling?
  6054. if (C.CallConstructionID == MachineOutlinerTailCall) {
  6055. // If yes, then we can just branch to the label.
  6056. Opc = isThumb
  6057. ? Subtarget.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND
  6058. : ARM::TAILJMPd;
  6059. MIB = BuildMI(MF, DebugLoc(), get(Opc))
  6060. .addGlobalAddress(M.getNamedValue(MF.getName()));
  6061. if (isThumb)
  6062. MIB.add(predOps(ARMCC::AL));
  6063. It = MBB.insert(It, MIB);
  6064. return It;
  6065. }
  6066. // Create the call instruction.
  6067. Opc = isThumb ? ARM::tBL : ARM::BL;
  6068. MachineInstrBuilder CallMIB = BuildMI(MF, DebugLoc(), get(Opc));
  6069. if (isThumb)
  6070. CallMIB.add(predOps(ARMCC::AL));
  6071. CallMIB.addGlobalAddress(M.getNamedValue(MF.getName()));
  6072. if (C.CallConstructionID == MachineOutlinerNoLRSave ||
  6073. C.CallConstructionID == MachineOutlinerThunk) {
  6074. // No, so just insert the call.
  6075. It = MBB.insert(It, CallMIB);
  6076. return It;
  6077. }
  6078. const ARMFunctionInfo &AFI = *C.getMF()->getInfo<ARMFunctionInfo>();
  6079. // Can we save to a register?
  6080. if (C.CallConstructionID == MachineOutlinerRegSave) {
  6081. Register Reg = findRegisterToSaveLRTo(C);
  6082. assert(Reg != 0 && "No callee-saved register available?");
  6083. // Save and restore LR from that register.
  6084. copyPhysReg(MBB, It, DebugLoc(), Reg, ARM::LR, true);
  6085. if (!AFI.isLRSpilled())
  6086. emitCFIForLRSaveToReg(MBB, It, Reg);
  6087. CallPt = MBB.insert(It, CallMIB);
  6088. copyPhysReg(MBB, It, DebugLoc(), ARM::LR, Reg, true);
  6089. if (!AFI.isLRSpilled())
  6090. emitCFIForLRRestoreFromReg(MBB, It);
  6091. It--;
  6092. return CallPt;
  6093. }
  6094. // We have the default case. Save and restore from SP.
  6095. if (!MBB.isLiveIn(ARM::LR))
  6096. MBB.addLiveIn(ARM::LR);
  6097. bool Auth = !AFI.isLRSpilled() && AFI.shouldSignReturnAddress(true);
  6098. saveLROnStack(MBB, It, !AFI.isLRSpilled(), Auth);
  6099. CallPt = MBB.insert(It, CallMIB);
  6100. restoreLRFromStack(MBB, It, !AFI.isLRSpilled(), Auth);
  6101. It--;
  6102. return CallPt;
  6103. }
  6104. bool ARMBaseInstrInfo::shouldOutlineFromFunctionByDefault(
  6105. MachineFunction &MF) const {
  6106. return Subtarget.isMClass() && MF.getFunction().hasMinSize();
  6107. }
  6108. bool ARMBaseInstrInfo::isReallyTriviallyReMaterializable(
  6109. const MachineInstr &MI) const {
  6110. // Try hard to rematerialize any VCTPs because if we spill P0, it will block
  6111. // the tail predication conversion. This means that the element count
  6112. // register has to be live for longer, but that has to be better than
  6113. // spill/restore and VPT predication.
  6114. return isVCTP(&MI) && !isPredicated(MI);
  6115. }
  6116. unsigned llvm::getBLXOpcode(const MachineFunction &MF) {
  6117. return (MF.getSubtarget<ARMSubtarget>().hardenSlsBlr()) ? ARM::BLX_noip
  6118. : ARM::BLX;
  6119. }
  6120. unsigned llvm::gettBLXrOpcode(const MachineFunction &MF) {
  6121. return (MF.getSubtarget<ARMSubtarget>().hardenSlsBlr()) ? ARM::tBLXr_noip
  6122. : ARM::tBLXr;
  6123. }
  6124. unsigned llvm::getBLXpredOpcode(const MachineFunction &MF) {
  6125. return (MF.getSubtarget<ARMSubtarget>().hardenSlsBlr()) ? ARM::BLX_pred_noip
  6126. : ARM::BLX_pred;
  6127. }
  6128. namespace {
  6129. class ARMPipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
  6130. MachineInstr *EndLoop, *LoopCount;
  6131. MachineFunction *MF;
  6132. const TargetInstrInfo *TII;
  6133. // Bitset[0 .. MAX_STAGES-1] ... iterations needed
  6134. // [LAST_IS_USE] : last reference to register in schedule is a use
  6135. // [SEEN_AS_LIVE] : Normal pressure algorithm believes register is live
  6136. static int constexpr MAX_STAGES = 30;
  6137. static int constexpr LAST_IS_USE = MAX_STAGES;
  6138. static int constexpr SEEN_AS_LIVE = MAX_STAGES + 1;
  6139. typedef std::bitset<MAX_STAGES + 2> IterNeed;
  6140. typedef std::map<unsigned, IterNeed> IterNeeds;
  6141. void bumpCrossIterationPressure(RegPressureTracker &RPT,
  6142. const IterNeeds &CIN);
  6143. bool tooMuchRegisterPressure(SwingSchedulerDAG &SSD, SMSchedule &SMS);
  6144. // Meanings of the various stuff with loop types:
  6145. // t2Bcc:
  6146. // EndLoop = branch at end of original BB that will become a kernel
  6147. // LoopCount = CC setter live into branch
  6148. // t2LoopEnd:
  6149. // EndLoop = branch at end of original BB
  6150. // LoopCount = t2LoopDec
  6151. public:
  6152. ARMPipelinerLoopInfo(MachineInstr *EndLoop, MachineInstr *LoopCount)
  6153. : EndLoop(EndLoop), LoopCount(LoopCount),
  6154. MF(EndLoop->getParent()->getParent()),
  6155. TII(MF->getSubtarget().getInstrInfo()) {}
  6156. bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
  6157. // Only ignore the terminator.
  6158. return MI == EndLoop || MI == LoopCount;
  6159. }
  6160. bool shouldUseSchedule(SwingSchedulerDAG &SSD, SMSchedule &SMS) override {
  6161. if (tooMuchRegisterPressure(SSD, SMS))
  6162. return false;
  6163. return true;
  6164. }
  6165. std::optional<bool> createTripCountGreaterCondition(
  6166. int TC, MachineBasicBlock &MBB,
  6167. SmallVectorImpl<MachineOperand> &Cond) override {
  6168. if (isCondBranchOpcode(EndLoop->getOpcode())) {
  6169. Cond.push_back(EndLoop->getOperand(1));
  6170. Cond.push_back(EndLoop->getOperand(2));
  6171. if (EndLoop->getOperand(0).getMBB() == EndLoop->getParent()) {
  6172. TII->reverseBranchCondition(Cond);
  6173. }
  6174. return {};
  6175. } else if (EndLoop->getOpcode() == ARM::t2LoopEnd) {
  6176. // General case just lets the unrolled t2LoopDec do the subtraction and
  6177. // therefore just needs to check if zero has been reached.
  6178. MachineInstr *LoopDec = nullptr;
  6179. for (auto &I : MBB.instrs())
  6180. if (I.getOpcode() == ARM::t2LoopDec)
  6181. LoopDec = &I;
  6182. assert(LoopDec && "Unable to find copied LoopDec");
  6183. // Check if we're done with the loop.
  6184. BuildMI(&MBB, LoopDec->getDebugLoc(), TII->get(ARM::t2CMPri))
  6185. .addReg(LoopDec->getOperand(0).getReg())
  6186. .addImm(0)
  6187. .addImm(ARMCC::AL)
  6188. .addReg(ARM::NoRegister);
  6189. Cond.push_back(MachineOperand::CreateImm(ARMCC::EQ));
  6190. Cond.push_back(MachineOperand::CreateReg(ARM::CPSR, false));
  6191. return {};
  6192. } else
  6193. llvm_unreachable("Unknown EndLoop");
  6194. }
  6195. void setPreheader(MachineBasicBlock *NewPreheader) override {}
  6196. void adjustTripCount(int TripCountAdjust) override {}
  6197. void disposed() override {}
  6198. };
  6199. void ARMPipelinerLoopInfo::bumpCrossIterationPressure(RegPressureTracker &RPT,
  6200. const IterNeeds &CIN) {
  6201. // Increase pressure by the amounts in CrossIterationNeeds
  6202. for (const auto &N : CIN) {
  6203. int Cnt = N.second.count() - N.second[SEEN_AS_LIVE] * 2;
  6204. for (int I = 0; I < Cnt; ++I)
  6205. RPT.increaseRegPressure(Register(N.first), LaneBitmask::getNone(),
  6206. LaneBitmask::getAll());
  6207. }
  6208. // Decrease pressure by the amounts in CrossIterationNeeds
  6209. for (const auto &N : CIN) {
  6210. int Cnt = N.second.count() - N.second[SEEN_AS_LIVE] * 2;
  6211. for (int I = 0; I < Cnt; ++I)
  6212. RPT.decreaseRegPressure(Register(N.first), LaneBitmask::getAll(),
  6213. LaneBitmask::getNone());
  6214. }
  6215. }
  6216. bool ARMPipelinerLoopInfo::tooMuchRegisterPressure(SwingSchedulerDAG &SSD,
  6217. SMSchedule &SMS) {
  6218. IterNeeds CrossIterationNeeds;
  6219. // Determine which values will be loop-carried after the schedule is
  6220. // applied
  6221. for (auto &SU : SSD.SUnits) {
  6222. const MachineInstr *MI = SU.getInstr();
  6223. int Stg = SMS.stageScheduled(const_cast<SUnit *>(&SU));
  6224. for (auto &S : SU.Succs)
  6225. if (MI->isPHI() && S.getKind() == SDep::Anti) {
  6226. Register Reg = S.getReg();
  6227. if (Reg.isVirtual())
  6228. CrossIterationNeeds.insert(std::make_pair(Reg.id(), IterNeed()))
  6229. .first->second.set(0);
  6230. } else if (S.isAssignedRegDep()) {
  6231. int OStg = SMS.stageScheduled(S.getSUnit());
  6232. if (OStg >= 0 && OStg != Stg) {
  6233. Register Reg = S.getReg();
  6234. if (Reg.isVirtual())
  6235. CrossIterationNeeds.insert(std::make_pair(Reg.id(), IterNeed()))
  6236. .first->second |= ((1 << (OStg - Stg)) - 1);
  6237. }
  6238. }
  6239. }
  6240. // Determine more-or-less what the proposed schedule (reversed) is going to
  6241. // be; it might not be quite the same because the within-cycle ordering
  6242. // created by SMSchedule depends upon changes to help with address offsets and
  6243. // the like.
  6244. std::vector<SUnit *> ProposedSchedule;
  6245. for (int Cycle = SMS.getFinalCycle(); Cycle >= SMS.getFirstCycle(); --Cycle)
  6246. for (int Stage = 0, StageEnd = SMS.getMaxStageCount(); Stage <= StageEnd;
  6247. ++Stage) {
  6248. std::deque<SUnit *> Instrs =
  6249. SMS.getInstructions(Cycle + Stage * SMS.getInitiationInterval());
  6250. std::sort(Instrs.begin(), Instrs.end(),
  6251. [](SUnit *A, SUnit *B) { return A->NodeNum > B->NodeNum; });
  6252. for (SUnit *SU : Instrs)
  6253. ProposedSchedule.push_back(SU);
  6254. }
  6255. // Learn whether the last use/def of each cross-iteration register is a use or
  6256. // def. If it is a def, RegisterPressure will implicitly increase max pressure
  6257. // and we do not have to add the pressure.
  6258. for (auto *SU : ProposedSchedule)
  6259. for (ConstMIBundleOperands OperI(*SU->getInstr()); OperI.isValid();
  6260. ++OperI) {
  6261. auto MO = *OperI;
  6262. if (!MO.isReg() || !MO.getReg())
  6263. continue;
  6264. Register Reg = MO.getReg();
  6265. auto CIter = CrossIterationNeeds.find(Reg.id());
  6266. if (CIter == CrossIterationNeeds.end() || CIter->second[LAST_IS_USE] ||
  6267. CIter->second[SEEN_AS_LIVE])
  6268. continue;
  6269. if (MO.isDef() && !MO.isDead())
  6270. CIter->second.set(SEEN_AS_LIVE);
  6271. else if (MO.isUse())
  6272. CIter->second.set(LAST_IS_USE);
  6273. }
  6274. for (auto &CI : CrossIterationNeeds)
  6275. CI.second.reset(LAST_IS_USE);
  6276. RegionPressure RecRegPressure;
  6277. RegPressureTracker RPTracker(RecRegPressure);
  6278. RegisterClassInfo RegClassInfo;
  6279. RegClassInfo.runOnMachineFunction(*MF);
  6280. RPTracker.init(MF, &RegClassInfo, nullptr, EndLoop->getParent(),
  6281. EndLoop->getParent()->end(), false, false);
  6282. const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
  6283. bumpCrossIterationPressure(RPTracker, CrossIterationNeeds);
  6284. for (auto *SU : ProposedSchedule) {
  6285. MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
  6286. RPTracker.setPos(std::next(CurInstI));
  6287. RPTracker.recede();
  6288. // Track what cross-iteration registers would be seen as live
  6289. for (ConstMIBundleOperands OperI(*CurInstI); OperI.isValid(); ++OperI) {
  6290. auto MO = *OperI;
  6291. if (!MO.isReg() || !MO.getReg())
  6292. continue;
  6293. Register Reg = MO.getReg();
  6294. if (MO.isDef() && !MO.isDead()) {
  6295. auto CIter = CrossIterationNeeds.find(Reg.id());
  6296. if (CIter != CrossIterationNeeds.end()) {
  6297. CIter->second.reset(0);
  6298. CIter->second.reset(SEEN_AS_LIVE);
  6299. }
  6300. }
  6301. }
  6302. for (auto &S : SU->Preds) {
  6303. auto Stg = SMS.stageScheduled(SU);
  6304. if (S.isAssignedRegDep()) {
  6305. Register Reg = S.getReg();
  6306. auto CIter = CrossIterationNeeds.find(Reg.id());
  6307. if (CIter != CrossIterationNeeds.end()) {
  6308. auto Stg2 = SMS.stageScheduled(const_cast<SUnit *>(S.getSUnit()));
  6309. assert(Stg2 <= Stg && "Data dependence upon earlier stage");
  6310. if (Stg - Stg2 < MAX_STAGES)
  6311. CIter->second.set(Stg - Stg2);
  6312. CIter->second.set(SEEN_AS_LIVE);
  6313. }
  6314. }
  6315. }
  6316. bumpCrossIterationPressure(RPTracker, CrossIterationNeeds);
  6317. }
  6318. auto &P = RPTracker.getPressure().MaxSetPressure;
  6319. for (unsigned I = 0, E = P.size(); I < E; ++I)
  6320. if (P[I] > TRI->getRegPressureSetLimit(*MF, I)) {
  6321. return true;
  6322. }
  6323. return false;
  6324. }
  6325. } // namespace
  6326. std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
  6327. ARMBaseInstrInfo::analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const {
  6328. MachineBasicBlock::iterator I = LoopBB->getFirstTerminator();
  6329. MachineBasicBlock *Preheader = *LoopBB->pred_begin();
  6330. if (Preheader == LoopBB)
  6331. Preheader = *std::next(LoopBB->pred_begin());
  6332. if (I != LoopBB->end() && I->getOpcode() == ARM::t2Bcc) {
  6333. // If the branch is a Bcc, then the CPSR should be set somewhere within the
  6334. // block. We need to determine the reaching definition of CPSR so that
  6335. // it can be marked as non-pipelineable, allowing the pipeliner to force
  6336. // it into stage 0 or give up if it cannot or will not do so.
  6337. MachineInstr *CCSetter = nullptr;
  6338. for (auto &L : LoopBB->instrs()) {
  6339. if (L.isCall())
  6340. return nullptr;
  6341. if (isCPSRDefined(L))
  6342. CCSetter = &L;
  6343. }
  6344. if (CCSetter)
  6345. return std::make_unique<ARMPipelinerLoopInfo>(&*I, CCSetter);
  6346. else
  6347. return nullptr; // Unable to find the CC setter, so unable to guarantee
  6348. // that pipeline will work
  6349. }
  6350. // Recognize:
  6351. // preheader:
  6352. // %1 = t2DoopLoopStart %0
  6353. // loop:
  6354. // %2 = phi %1, <not loop>, %..., %loop
  6355. // %3 = t2LoopDec %2, <imm>
  6356. // t2LoopEnd %3, %loop
  6357. if (I != LoopBB->end() && I->getOpcode() == ARM::t2LoopEnd) {
  6358. for (auto &L : LoopBB->instrs())
  6359. if (L.isCall())
  6360. return nullptr;
  6361. else if (isVCTP(&L))
  6362. return nullptr;
  6363. Register LoopDecResult = I->getOperand(0).getReg();
  6364. MachineRegisterInfo &MRI = LoopBB->getParent()->getRegInfo();
  6365. MachineInstr *LoopDec = MRI.getUniqueVRegDef(LoopDecResult);
  6366. if (!LoopDec || LoopDec->getOpcode() != ARM::t2LoopDec)
  6367. return nullptr;
  6368. MachineInstr *LoopStart = nullptr;
  6369. for (auto &J : Preheader->instrs())
  6370. if (J.getOpcode() == ARM::t2DoLoopStart)
  6371. LoopStart = &J;
  6372. if (!LoopStart)
  6373. return nullptr;
  6374. return std::make_unique<ARMPipelinerLoopInfo>(&*I, LoopDec);
  6375. }
  6376. return nullptr;
  6377. }