aoptx86.pas 683 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. { Attempts to allocate a volatile integer register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  79. { Attempts to allocate a volatile MM register for use between p and hp,
  80. using AUsedRegs for the current register usage information. Returns NR_NO
  81. if no free register could be found }
  82. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  83. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  84. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  85. { checks whether reading the value in reg1 depends on the value of reg2. This
  86. is very similar to SuperRegisterEquals, except it takes into account that
  87. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  88. depend on the value in AH). }
  89. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  90. { Replaces all references to AOldReg in a memory reference to ANewReg }
  91. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Replaces all references to AOldReg in an operand to ANewReg }
  93. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an instruction to ANewReg,
  95. except where the register is being written }
  96. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  97. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  98. or writes to a global symbol }
  99. class function IsRefSafe(const ref: PReference): Boolean; static;
  100. { Returns true if the given MOV instruction can be safely converted to CMOV }
  101. class function CanBeCMOV(p, cond_p: tai) : boolean; static;
  102. { Like UpdateUsedRegs, but ignores deallocations }
  103. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  104. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  105. class function IsBTXAcceptable(p : tai) : boolean; static;
  106. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  107. conversion was successful }
  108. function ConvertLEA(const p : taicpu): Boolean;
  109. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  110. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  111. procedure DebugMsg(const s : string; p : tai);inline;
  112. class function IsExitCode(p : tai) : boolean; static;
  113. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  114. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  115. procedure RemoveLastDeallocForFuncRes(p : tai);
  116. function DoArithCombineOpt(var p : tai) : Boolean;
  117. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  118. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  119. function PrePeepholeOptSxx(var p : tai) : boolean;
  120. function PrePeepholeOptIMUL(var p : tai) : boolean;
  121. function PrePeepholeOptAND(var p : tai) : boolean;
  122. function OptPass1Test(var p: tai): boolean;
  123. function OptPass1Add(var p: tai): boolean;
  124. function OptPass1AND(var p : tai) : boolean;
  125. function OptPass1_V_MOVAP(var p : tai) : boolean;
  126. function OptPass1VOP(var p : tai) : boolean;
  127. function OptPass1MOV(var p : tai) : boolean;
  128. function OptPass1Movx(var p : tai) : boolean;
  129. function OptPass1MOVXX(var p : tai) : boolean;
  130. function OptPass1OP(var p : tai) : boolean;
  131. function OptPass1LEA(var p : tai) : boolean;
  132. function OptPass1Sub(var p : tai) : boolean;
  133. function OptPass1SHLSAL(var p : tai) : boolean;
  134. function OptPass1SHR(var p : tai) : boolean;
  135. function OptPass1FSTP(var p : tai) : boolean;
  136. function OptPass1FLD(var p : tai) : boolean;
  137. function OptPass1Cmp(var p : tai) : boolean;
  138. function OptPass1PXor(var p : tai) : boolean;
  139. function OptPass1VPXor(var p: tai): boolean;
  140. function OptPass1Imul(var p : tai) : boolean;
  141. function OptPass1Jcc(var p : tai) : boolean;
  142. function OptPass1SHXX(var p: tai): boolean;
  143. function OptPass1VMOVDQ(var p: tai): Boolean;
  144. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  145. function OptPass2Movx(var p : tai): Boolean;
  146. function OptPass2MOV(var p : tai) : boolean;
  147. function OptPass2Imul(var p : tai) : boolean;
  148. function OptPass2Jmp(var p : tai) : boolean;
  149. function OptPass2Jcc(var p : tai) : boolean;
  150. function OptPass2Lea(var p: tai): Boolean;
  151. function OptPass2SUB(var p: tai): Boolean;
  152. function OptPass2ADD(var p : tai): Boolean;
  153. function OptPass2SETcc(var p : tai) : boolean;
  154. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  155. function PostPeepholeOptMov(var p : tai) : Boolean;
  156. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  157. function PostPeepholeOptXor(var p : tai) : Boolean;
  158. function PostPeepholeOptAnd(var p : tai) : boolean;
  159. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  160. function PostPeepholeOptCmp(var p : tai) : Boolean;
  161. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  162. function PostPeepholeOptCall(var p : tai) : Boolean;
  163. function PostPeepholeOptLea(var p : tai) : Boolean;
  164. function PostPeepholeOptPush(var p: tai): Boolean;
  165. function PostPeepholeOptShr(var p : tai) : boolean;
  166. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  167. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  168. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  169. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  170. function TrySwapMovOp(var p, hp1: tai): Boolean;
  171. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  172. { Processor-dependent reference optimisation }
  173. class procedure OptimizeRefs(var p: taicpu); static;
  174. end;
  175. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  176. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  177. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  178. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  179. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  180. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  181. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  182. {$if max_operands>2}
  183. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  184. {$endif max_operands>2}
  185. function RefsEqual(const r1, r2: treference): boolean;
  186. { Note that Result is set to True if the references COULD overlap but the
  187. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  188. might still overlap because %reg2 could be equal to %reg1-4 }
  189. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  190. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  191. { returns true, if ref is a reference using only the registers passed as base and index
  192. and having an offset }
  193. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  194. implementation
  195. uses
  196. cutils,verbose,
  197. systems,
  198. globals,
  199. cpuinfo,
  200. procinfo,
  201. paramgr,
  202. aasmbase,
  203. aoptbase,aoptutils,
  204. symconst,symsym,
  205. cgx86,
  206. itcpugas;
  207. {$ifdef DEBUG_AOPTCPU}
  208. const
  209. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  210. {$else DEBUG_AOPTCPU}
  211. { Empty strings help the optimizer to remove string concatenations that won't
  212. ever appear to the user on release builds. [Kit] }
  213. const
  214. SPeepholeOptimization = '';
  215. {$endif DEBUG_AOPTCPU}
  216. LIST_STEP_SIZE = 4;
  217. {$ifndef 8086}
  218. MAX_CMOV_INSTRUCTIONS = 4;
  219. MAX_CMOV_REGISTERS = 8;
  220. {$endif 8086}
  221. type
  222. TJumpTrackingItem = class(TLinkedListItem)
  223. private
  224. FSymbol: TAsmSymbol;
  225. FRefs: LongInt;
  226. public
  227. constructor Create(ASymbol: TAsmSymbol);
  228. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  229. property Symbol: TAsmSymbol read FSymbol;
  230. property Refs: LongInt read FRefs;
  231. end;
  232. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  233. begin
  234. inherited Create;
  235. FSymbol := ASymbol;
  236. FRefs := 0;
  237. end;
  238. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  239. begin
  240. Inc(FRefs);
  241. end;
  242. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  243. begin
  244. result :=
  245. (instr.typ = ait_instruction) and
  246. (taicpu(instr).opcode = op) and
  247. ((opsize = []) or (taicpu(instr).opsize in opsize));
  248. end;
  249. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  250. begin
  251. result :=
  252. (instr.typ = ait_instruction) and
  253. ((taicpu(instr).opcode = op1) or
  254. (taicpu(instr).opcode = op2)
  255. ) and
  256. ((opsize = []) or (taicpu(instr).opsize in opsize));
  257. end;
  258. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  259. begin
  260. result :=
  261. (instr.typ = ait_instruction) and
  262. ((taicpu(instr).opcode = op1) or
  263. (taicpu(instr).opcode = op2) or
  264. (taicpu(instr).opcode = op3)
  265. ) and
  266. ((opsize = []) or (taicpu(instr).opsize in opsize));
  267. end;
  268. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  269. const opsize : topsizes) : boolean;
  270. var
  271. op : TAsmOp;
  272. begin
  273. result:=false;
  274. if (instr.typ <> ait_instruction) or
  275. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  276. exit;
  277. for op in ops do
  278. begin
  279. if taicpu(instr).opcode = op then
  280. begin
  281. result:=true;
  282. exit;
  283. end;
  284. end;
  285. end;
  286. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  287. begin
  288. result := (oper.typ = top_reg) and (oper.reg = reg);
  289. end;
  290. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  291. begin
  292. result := (oper.typ = top_const) and (oper.val = a);
  293. end;
  294. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  295. begin
  296. result := oper1.typ = oper2.typ;
  297. if result then
  298. case oper1.typ of
  299. top_const:
  300. Result:=oper1.val = oper2.val;
  301. top_reg:
  302. Result:=oper1.reg = oper2.reg;
  303. top_ref:
  304. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  305. else
  306. internalerror(2013102801);
  307. end
  308. end;
  309. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  310. begin
  311. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  312. if result then
  313. case oper1.typ of
  314. top_const:
  315. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  316. top_reg:
  317. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  318. top_ref:
  319. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  320. else
  321. internalerror(2020052401);
  322. end
  323. end;
  324. function RefsEqual(const r1, r2: treference): boolean;
  325. begin
  326. RefsEqual :=
  327. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  328. (r1.relsymbol = r2.relsymbol) and
  329. (r1.segment = r2.segment) and (r1.base = r2.base) and
  330. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  331. (r1.offset = r2.offset) and
  332. (r1.volatility + r2.volatility = []);
  333. end;
  334. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  335. begin
  336. if (r1.symbol<>r2.symbol) then
  337. { If the index registers are different, there's a chance one could
  338. be set so it equals the other symbol }
  339. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  340. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  341. (r1.relsymbol = r2.relsymbol) and
  342. (r1.segment = r2.segment) and (r1.base = r2.base) and
  343. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  344. (r1.volatility + r2.volatility = []) then
  345. { In this case, it all depends on the offsets }
  346. Exit(abs(r1.offset - r2.offset) < Range);
  347. { There's a chance things MIGHT overlap, so take no chances }
  348. Result := True;
  349. end;
  350. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  351. begin
  352. Result:=(ref.offset=0) and
  353. (ref.scalefactor in [0,1]) and
  354. (ref.segment=NR_NO) and
  355. (ref.symbol=nil) and
  356. (ref.relsymbol=nil) and
  357. ((base=NR_INVALID) or
  358. (ref.base=base)) and
  359. ((index=NR_INVALID) or
  360. (ref.index=index)) and
  361. (ref.volatility=[]);
  362. end;
  363. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  364. begin
  365. Result:=(ref.scalefactor in [0,1]) and
  366. (ref.segment=NR_NO) and
  367. (ref.symbol=nil) and
  368. (ref.relsymbol=nil) and
  369. ((base=NR_INVALID) or
  370. (ref.base=base)) and
  371. ((index=NR_INVALID) or
  372. (ref.index=index)) and
  373. (ref.volatility=[]);
  374. end;
  375. function InstrReadsFlags(p: tai): boolean;
  376. begin
  377. InstrReadsFlags := true;
  378. case p.typ of
  379. ait_instruction:
  380. if InsProp[taicpu(p).opcode].Ch*
  381. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  382. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  383. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  384. exit;
  385. ait_label:
  386. exit;
  387. else
  388. ;
  389. end;
  390. InstrReadsFlags := false;
  391. end;
  392. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  393. begin
  394. Next:=Current;
  395. repeat
  396. Result:=GetNextInstruction(Next,Next);
  397. until not (Result) or
  398. not(cs_opt_level3 in current_settings.optimizerswitches) or
  399. (Next.typ<>ait_instruction) or
  400. RegInInstruction(reg,Next) or
  401. is_calljmp(taicpu(Next).opcode);
  402. end;
  403. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  404. var
  405. GetNextResult: Boolean;
  406. begin
  407. Result:=0;
  408. Next:=Current;
  409. repeat
  410. GetNextResult := GetNextInstruction(Next,Next);
  411. if GetNextResult then
  412. Inc(Result)
  413. else
  414. { Must return zero upon hitting the end of the linked list without a match }
  415. Result := 0;
  416. until not (GetNextResult) or
  417. not(cs_opt_level3 in current_settings.optimizerswitches) or
  418. (Next.typ<>ait_instruction) or
  419. RegInInstruction(reg,Next) or
  420. is_calljmp(taicpu(Next).opcode);
  421. end;
  422. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  423. procedure TrackJump(Symbol: TAsmSymbol);
  424. var
  425. Search: TJumpTrackingItem;
  426. begin
  427. { See if an entry already exists in our jump tracking list
  428. (faster to search backwards due to the higher chance of
  429. matching destinations) }
  430. Search := TJumpTrackingItem(JumpTracking.Last);
  431. while Assigned(Search) do
  432. begin
  433. if Search.Symbol = Symbol then
  434. begin
  435. { Found it - remove it so it can be pushed to the front }
  436. JumpTracking.Remove(Search);
  437. Break;
  438. end;
  439. Search := TJumpTrackingItem(Search.Previous);
  440. end;
  441. if not Assigned(Search) then
  442. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  443. JumpTracking.Concat(Search);
  444. Search.IncRefs;
  445. end;
  446. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  447. var
  448. Search: TJumpTrackingItem;
  449. begin
  450. Result := False;
  451. { See if this label appears in the tracking list }
  452. Search := TJumpTrackingItem(JumpTracking.Last);
  453. while Assigned(Search) do
  454. begin
  455. if Search.Symbol = Symbol then
  456. begin
  457. { Found it - let's see what we can discover }
  458. if Search.Symbol.getrefs = Search.Refs then
  459. begin
  460. { Success - all the references are accounted for }
  461. JumpTracking.Remove(Search);
  462. Search.Free;
  463. { It is logically impossible for CrossJump to be false here
  464. because we must have run into a conditional jump for
  465. this label at some point }
  466. if not CrossJump then
  467. InternalError(2022041710);
  468. if JumpTracking.First = nil then
  469. { Tracking list is now empty - no more cross jumps }
  470. CrossJump := False;
  471. Result := True;
  472. Exit;
  473. end;
  474. { If the references don't match, it's possible to enter
  475. this label through other means, so drop out }
  476. Exit;
  477. end;
  478. Search := TJumpTrackingItem(Search.Previous);
  479. end;
  480. end;
  481. var
  482. Next_Label: tai;
  483. begin
  484. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  485. Next := Current;
  486. repeat
  487. Result := GetNextInstruction(Next,Next);
  488. if not Result then
  489. Break;
  490. if Next.typ = ait_align then
  491. Result := SkipAligns(Next, Next);
  492. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  493. if is_calljmpuncondret(taicpu(Next).opcode) then
  494. begin
  495. if (taicpu(Next).opcode = A_JMP) and
  496. { Remove dead code now to save time }
  497. RemoveDeadCodeAfterJump(taicpu(Next)) then
  498. { A jump was removed, but not the current instruction, and
  499. Result doesn't necessarily translate into an optimisation
  500. routine's Result, so use the "Force New Iteration" flag so
  501. mark a new pass }
  502. Include(OptsToCheck, aoc_ForceNewIteration);
  503. if not Assigned(JumpTracking) then
  504. begin
  505. { Cross-label optimisations often causes other optimisations
  506. to perform worse because they're not given the chance to
  507. optimise locally. In this case, don't do the cross-label
  508. optimisations yet, but flag them as a potential possibility
  509. for the next iteration of Pass 1 }
  510. if not NotFirstIteration then
  511. Include(OptsToCheck, aoc_ForceNewIteration);
  512. end
  513. else if IsJumpToLabel(taicpu(Next)) and
  514. GetNextInstruction(Next, Next_Label) and
  515. SkipAligns(Next_Label, Next_Label) then
  516. begin
  517. { If we have JMP .lbl, and the label after it has all of its
  518. references tracked, then this is probably an if-else style of
  519. block and we can keep tracking. If the label for this jump
  520. then appears later and is fully tracked, then it's the end
  521. of the if-else blocks and the code paths converge (thus
  522. marking the end of the cross-jump) }
  523. if (Next_Label.typ = ait_label) then
  524. begin
  525. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  526. begin
  527. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  528. Next := Next_Label;
  529. { CrossJump gets set to false by LabelAccountedFor if the
  530. list is completely emptied (as it indicates that all
  531. code paths have converged). We could avoid this nuance
  532. by moving the TrackJump call to before the
  533. LabelAccountedFor call, but this is slower in situations
  534. where LabelAccountedFor would return False due to the
  535. creation of a new object that is not used and destroyed
  536. soon after. }
  537. CrossJump := True;
  538. Continue;
  539. end;
  540. end
  541. else if (Next_Label.typ <> ait_marker) then
  542. { We just did a RemoveDeadCodeAfterJump, so either we find
  543. a label, the end of the procedure or some kind of marker}
  544. InternalError(2022041720);
  545. end;
  546. Result := False;
  547. Exit;
  548. end
  549. else
  550. begin
  551. if not Assigned(JumpTracking) then
  552. begin
  553. { Cross-label optimisations often causes other optimisations
  554. to perform worse because they're not given the chance to
  555. optimise locally. In this case, don't do the cross-label
  556. optimisations yet, but flag them as a potential possibility
  557. for the next iteration of Pass 1 }
  558. if not NotFirstIteration then
  559. Include(OptsToCheck, aoc_ForceNewIteration);
  560. end
  561. else if IsJumpToLabel(taicpu(Next)) then
  562. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  563. else
  564. { Conditional jumps should always be a jump to label }
  565. InternalError(2022041701);
  566. CrossJump := True;
  567. Continue;
  568. end;
  569. if Next.typ = ait_label then
  570. begin
  571. if not Assigned(JumpTracking) then
  572. begin
  573. { Cross-label optimisations often causes other optimisations
  574. to perform worse because they're not given the chance to
  575. optimise locally. In this case, don't do the cross-label
  576. optimisations yet, but flag them as a potential possibility
  577. for the next iteration of Pass 1 }
  578. if not NotFirstIteration then
  579. Include(OptsToCheck, aoc_ForceNewIteration);
  580. end
  581. else if LabelAccountedFor(tai_label(Next).labsym) then
  582. Continue;
  583. { If we reach here, we're at a label that hasn't been seen before
  584. (or JumpTracking was nil) }
  585. Break;
  586. end;
  587. until not Result or
  588. not (cs_opt_level3 in current_settings.optimizerswitches) or
  589. not (Next.typ in [ait_label, ait_instruction]) or
  590. RegInInstruction(reg,Next);
  591. end;
  592. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  593. begin
  594. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  595. begin
  596. Result:=GetNextInstruction(Current,Next);
  597. exit;
  598. end;
  599. Next:=tai(Current.Next);
  600. Result:=false;
  601. while assigned(Next) do
  602. begin
  603. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  604. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  605. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  606. exit
  607. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  608. begin
  609. Result:=true;
  610. exit;
  611. end;
  612. Next:=tai(Next.Next);
  613. end;
  614. end;
  615. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  616. begin
  617. Result:=RegReadByInstruction(reg,hp);
  618. end;
  619. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  620. var
  621. p: taicpu;
  622. opcount: longint;
  623. begin
  624. RegReadByInstruction := false;
  625. if hp.typ <> ait_instruction then
  626. exit;
  627. p := taicpu(hp);
  628. case p.opcode of
  629. A_CALL:
  630. regreadbyinstruction := true;
  631. A_IMUL:
  632. case p.ops of
  633. 1:
  634. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  635. (
  636. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  637. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  638. );
  639. 2,3:
  640. regReadByInstruction :=
  641. reginop(reg,p.oper[0]^) or
  642. reginop(reg,p.oper[1]^);
  643. else
  644. InternalError(2019112801);
  645. end;
  646. A_MUL:
  647. begin
  648. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  649. (
  650. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  651. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  652. );
  653. end;
  654. A_IDIV,A_DIV:
  655. begin
  656. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  657. (
  658. (getregtype(reg)=R_INTREGISTER) and
  659. (
  660. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  661. )
  662. );
  663. end;
  664. else
  665. begin
  666. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  667. begin
  668. RegReadByInstruction := false;
  669. exit;
  670. end;
  671. for opcount := 0 to p.ops-1 do
  672. if (p.oper[opCount]^.typ = top_ref) and
  673. RegInRef(reg,p.oper[opcount]^.ref^) then
  674. begin
  675. RegReadByInstruction := true;
  676. exit
  677. end;
  678. { special handling for SSE MOVSD }
  679. if (p.opcode=A_MOVSD) and (p.ops>0) then
  680. begin
  681. if p.ops<>2 then
  682. internalerror(2017042702);
  683. regReadByInstruction := reginop(reg,p.oper[0]^) or
  684. (
  685. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  686. );
  687. exit;
  688. end;
  689. with insprop[p.opcode] do
  690. begin
  691. case getregtype(reg) of
  692. R_INTREGISTER:
  693. begin
  694. case getsupreg(reg) of
  695. RS_EAX:
  696. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  697. begin
  698. RegReadByInstruction := true;
  699. exit
  700. end;
  701. RS_ECX:
  702. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  703. begin
  704. RegReadByInstruction := true;
  705. exit
  706. end;
  707. RS_EDX:
  708. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  709. begin
  710. RegReadByInstruction := true;
  711. exit
  712. end;
  713. RS_EBX:
  714. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  715. begin
  716. RegReadByInstruction := true;
  717. exit
  718. end;
  719. RS_ESP:
  720. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  721. begin
  722. RegReadByInstruction := true;
  723. exit
  724. end;
  725. RS_EBP:
  726. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  727. begin
  728. RegReadByInstruction := true;
  729. exit
  730. end;
  731. RS_ESI:
  732. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  733. begin
  734. RegReadByInstruction := true;
  735. exit
  736. end;
  737. RS_EDI:
  738. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  739. begin
  740. RegReadByInstruction := true;
  741. exit
  742. end;
  743. end;
  744. end;
  745. R_MMREGISTER:
  746. begin
  747. case getsupreg(reg) of
  748. RS_XMM0:
  749. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  750. begin
  751. RegReadByInstruction := true;
  752. exit
  753. end;
  754. end;
  755. end;
  756. else
  757. ;
  758. end;
  759. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  760. begin
  761. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  762. begin
  763. case p.condition of
  764. C_A,C_NBE, { CF=0 and ZF=0 }
  765. C_BE,C_NA: { CF=1 or ZF=1 }
  766. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  767. C_AE,C_NB,C_NC, { CF=0 }
  768. C_B,C_NAE,C_C: { CF=1 }
  769. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  770. C_NE,C_NZ, { ZF=0 }
  771. C_E,C_Z: { ZF=1 }
  772. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  773. C_G,C_NLE, { ZF=0 and SF=OF }
  774. C_LE,C_NG: { ZF=1 or SF<>OF }
  775. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  776. C_GE,C_NL, { SF=OF }
  777. C_L,C_NGE: { SF<>OF }
  778. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  779. C_NO, { OF=0 }
  780. C_O: { OF=1 }
  781. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  782. C_NP,C_PO, { PF=0 }
  783. C_P,C_PE: { PF=1 }
  784. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  785. C_NS, { SF=0 }
  786. C_S: { SF=1 }
  787. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  788. else
  789. internalerror(2017042701);
  790. end;
  791. if RegReadByInstruction then
  792. exit;
  793. end;
  794. case getsubreg(reg) of
  795. R_SUBW,R_SUBD,R_SUBQ:
  796. RegReadByInstruction :=
  797. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  798. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  799. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  800. R_SUBFLAGCARRY:
  801. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  802. R_SUBFLAGPARITY:
  803. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  804. R_SUBFLAGAUXILIARY:
  805. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  806. R_SUBFLAGZERO:
  807. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  808. R_SUBFLAGSIGN:
  809. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  810. R_SUBFLAGOVERFLOW:
  811. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  812. R_SUBFLAGINTERRUPT:
  813. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  814. R_SUBFLAGDIRECTION:
  815. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  816. else
  817. internalerror(2017042601);
  818. end;
  819. exit;
  820. end;
  821. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  822. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  823. (p.oper[0]^.reg=p.oper[1]^.reg) then
  824. exit;
  825. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  826. begin
  827. RegReadByInstruction := true;
  828. exit
  829. end;
  830. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  831. begin
  832. RegReadByInstruction := true;
  833. exit
  834. end;
  835. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  836. begin
  837. RegReadByInstruction := true;
  838. exit
  839. end;
  840. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  841. begin
  842. RegReadByInstruction := true;
  843. exit
  844. end;
  845. end;
  846. end;
  847. end;
  848. end;
  849. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  850. begin
  851. result:=false;
  852. if p1.typ<>ait_instruction then
  853. exit;
  854. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  855. exit(true);
  856. if (getregtype(reg)=R_INTREGISTER) and
  857. { change information for xmm movsd are not correct }
  858. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  859. begin
  860. case getsupreg(reg) of
  861. { RS_EAX = RS_RAX on x86-64 }
  862. RS_EAX:
  863. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  864. RS_ECX:
  865. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  866. RS_EDX:
  867. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  868. RS_EBX:
  869. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  870. RS_ESP:
  871. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  872. RS_EBP:
  873. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  874. RS_ESI:
  875. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  876. RS_EDI:
  877. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  878. else
  879. ;
  880. end;
  881. if result then
  882. exit;
  883. end
  884. else if getregtype(reg)=R_MMREGISTER then
  885. begin
  886. case getsupreg(reg) of
  887. RS_XMM0:
  888. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  889. else
  890. ;
  891. end;
  892. if result then
  893. exit;
  894. end
  895. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  896. begin
  897. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  898. exit(true);
  899. case getsubreg(reg) of
  900. R_SUBFLAGCARRY:
  901. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  902. R_SUBFLAGPARITY:
  903. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  904. R_SUBFLAGAUXILIARY:
  905. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  906. R_SUBFLAGZERO:
  907. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  908. R_SUBFLAGSIGN:
  909. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  910. R_SUBFLAGOVERFLOW:
  911. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  912. R_SUBFLAGINTERRUPT:
  913. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  914. R_SUBFLAGDIRECTION:
  915. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  916. R_SUBW,R_SUBD,R_SUBQ:
  917. { Everything except the direction bits }
  918. Result:=
  919. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  920. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  921. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  922. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  923. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  924. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  925. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  926. else
  927. ;
  928. end;
  929. if result then
  930. exit;
  931. end
  932. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  933. exit(true);
  934. Result:=inherited RegInInstruction(Reg, p1);
  935. end;
  936. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  937. const
  938. WriteOps: array[0..3] of set of TInsChange =
  939. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  940. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  941. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  942. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  943. var
  944. OperIdx: Integer;
  945. begin
  946. Result := False;
  947. if p1.typ <> ait_instruction then
  948. exit;
  949. with insprop[taicpu(p1).opcode] do
  950. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  951. begin
  952. case getsubreg(reg) of
  953. R_SUBW,R_SUBD,R_SUBQ:
  954. Result :=
  955. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  956. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  957. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  958. R_SUBFLAGCARRY:
  959. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  960. R_SUBFLAGPARITY:
  961. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  962. R_SUBFLAGAUXILIARY:
  963. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  964. R_SUBFLAGZERO:
  965. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  966. R_SUBFLAGSIGN:
  967. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  968. R_SUBFLAGOVERFLOW:
  969. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  970. R_SUBFLAGINTERRUPT:
  971. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  972. R_SUBFLAGDIRECTION:
  973. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  974. else
  975. internalerror(2017042602);
  976. end;
  977. exit;
  978. end;
  979. case taicpu(p1).opcode of
  980. A_CALL:
  981. { We could potentially set Result to False if the register in
  982. question is non-volatile for the subroutine's calling convention,
  983. but this would require detecting the calling convention in use and
  984. also assuming that the routine doesn't contain malformed assembly
  985. language, for example... so it could only be done under -O4 as it
  986. would be considered a side-effect. [Kit] }
  987. Result := True;
  988. A_MOVSD:
  989. { special handling for SSE MOVSD }
  990. if (taicpu(p1).ops>0) then
  991. begin
  992. if taicpu(p1).ops<>2 then
  993. internalerror(2017042703);
  994. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  995. end;
  996. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  997. so fix it here (FK)
  998. }
  999. A_VMOVSS,
  1000. A_VMOVSD:
  1001. begin
  1002. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1003. exit;
  1004. end;
  1005. A_IMUL:
  1006. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1007. else
  1008. ;
  1009. end;
  1010. if Result then
  1011. exit;
  1012. with insprop[taicpu(p1).opcode] do
  1013. begin
  1014. if getregtype(reg)=R_INTREGISTER then
  1015. begin
  1016. case getsupreg(reg) of
  1017. RS_EAX:
  1018. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1019. begin
  1020. Result := True;
  1021. exit
  1022. end;
  1023. RS_ECX:
  1024. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1025. begin
  1026. Result := True;
  1027. exit
  1028. end;
  1029. RS_EDX:
  1030. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1031. begin
  1032. Result := True;
  1033. exit
  1034. end;
  1035. RS_EBX:
  1036. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1037. begin
  1038. Result := True;
  1039. exit
  1040. end;
  1041. RS_ESP:
  1042. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1043. begin
  1044. Result := True;
  1045. exit
  1046. end;
  1047. RS_EBP:
  1048. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1049. begin
  1050. Result := True;
  1051. exit
  1052. end;
  1053. RS_ESI:
  1054. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1055. begin
  1056. Result := True;
  1057. exit
  1058. end;
  1059. RS_EDI:
  1060. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1061. begin
  1062. Result := True;
  1063. exit
  1064. end;
  1065. end;
  1066. end;
  1067. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1068. if (WriteOps[OperIdx]*Ch<>[]) and
  1069. { The register doesn't get modified inside a reference }
  1070. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1071. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1072. begin
  1073. Result := true;
  1074. exit
  1075. end;
  1076. end;
  1077. end;
  1078. {$ifdef DEBUG_AOPTCPU}
  1079. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1080. begin
  1081. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1082. end;
  1083. function debug_tostr(i: tcgint): string; inline;
  1084. begin
  1085. Result := tostr(i);
  1086. end;
  1087. function debug_hexstr(i: tcgint): string;
  1088. begin
  1089. Result := '0x';
  1090. case i of
  1091. 0..$FF:
  1092. Result := Result + hexstr(i, 2);
  1093. $100..$FFFF:
  1094. Result := Result + hexstr(i, 4);
  1095. $10000..$FFFFFF:
  1096. Result := Result + hexstr(i, 6);
  1097. $1000000..$FFFFFFFF:
  1098. Result := Result + hexstr(i, 8);
  1099. else
  1100. Result := Result + hexstr(i, 16);
  1101. end;
  1102. end;
  1103. function debug_regname(r: TRegister): string; inline;
  1104. begin
  1105. Result := '%' + std_regname(r);
  1106. end;
  1107. { Debug output function - creates a string representation of an operator }
  1108. function debug_operstr(oper: TOper): string;
  1109. begin
  1110. case oper.typ of
  1111. top_const:
  1112. Result := '$' + debug_tostr(oper.val);
  1113. top_reg:
  1114. Result := debug_regname(oper.reg);
  1115. top_ref:
  1116. begin
  1117. if oper.ref^.offset <> 0 then
  1118. Result := debug_tostr(oper.ref^.offset) + '('
  1119. else
  1120. Result := '(';
  1121. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1122. begin
  1123. Result := Result + debug_regname(oper.ref^.base);
  1124. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1125. Result := Result + ',' + debug_regname(oper.ref^.index);
  1126. end
  1127. else
  1128. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1129. Result := Result + debug_regname(oper.ref^.index);
  1130. if (oper.ref^.scalefactor > 1) then
  1131. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1132. else
  1133. Result := Result + ')';
  1134. end;
  1135. else
  1136. Result := '[UNKNOWN]';
  1137. end;
  1138. end;
  1139. function debug_op2str(opcode: tasmop): string; inline;
  1140. begin
  1141. Result := std_op2str[opcode];
  1142. end;
  1143. function debug_opsize2str(opsize: topsize): string; inline;
  1144. begin
  1145. Result := gas_opsize2str[opsize];
  1146. end;
  1147. {$else DEBUG_AOPTCPU}
  1148. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1149. begin
  1150. end;
  1151. function debug_tostr(i: tcgint): string; inline;
  1152. begin
  1153. Result := '';
  1154. end;
  1155. function debug_hexstr(i: tcgint): string; inline;
  1156. begin
  1157. Result := '';
  1158. end;
  1159. function debug_regname(r: TRegister): string; inline;
  1160. begin
  1161. Result := '';
  1162. end;
  1163. function debug_operstr(oper: TOper): string; inline;
  1164. begin
  1165. Result := '';
  1166. end;
  1167. function debug_op2str(opcode: tasmop): string; inline;
  1168. begin
  1169. Result := '';
  1170. end;
  1171. function debug_opsize2str(opsize: topsize): string; inline;
  1172. begin
  1173. Result := '';
  1174. end;
  1175. {$endif DEBUG_AOPTCPU}
  1176. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1177. begin
  1178. {$ifdef x86_64}
  1179. { Always fine on x86-64 }
  1180. Result := True;
  1181. {$else x86_64}
  1182. Result :=
  1183. {$ifdef i8086}
  1184. (current_settings.cputype >= cpu_386) and
  1185. {$endif i8086}
  1186. (
  1187. { Always accept if optimising for size }
  1188. (cs_opt_size in current_settings.optimizerswitches) or
  1189. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1190. (current_settings.optimizecputype >= cpu_Pentium2)
  1191. );
  1192. {$endif x86_64}
  1193. end;
  1194. { Attempts to allocate a volatile integer register for use between p and hp,
  1195. using AUsedRegs for the current register usage information. Returns NR_NO
  1196. if no free register could be found }
  1197. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1198. var
  1199. RegSet: TCPURegisterSet;
  1200. CurrentSuperReg: Integer;
  1201. CurrentReg: TRegister;
  1202. Currentp: tai;
  1203. Breakout: Boolean;
  1204. begin
  1205. Result := NR_NO;
  1206. RegSet :=
  1207. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1208. current_procinfo.saved_regs_int;
  1209. (*
  1210. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1211. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1212. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1213. *)
  1214. for CurrentSuperReg in RegSet do
  1215. begin
  1216. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1217. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1218. {$if defined(i386) or defined(i8086)}
  1219. { If the target size is 8-bit, make sure we can actually encode it }
  1220. and (
  1221. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1222. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1223. )
  1224. {$endif i386 or i8086}
  1225. then
  1226. begin
  1227. Currentp := p;
  1228. Breakout := False;
  1229. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1230. begin
  1231. case Currentp.typ of
  1232. ait_instruction:
  1233. begin
  1234. if RegInInstruction(CurrentReg, Currentp) then
  1235. begin
  1236. Breakout := True;
  1237. Break;
  1238. end;
  1239. { Cannot allocate across an unconditional jump }
  1240. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1241. Exit;
  1242. end;
  1243. ait_marker:
  1244. { Don't try anything more if a marker is hit }
  1245. Exit;
  1246. ait_regalloc:
  1247. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1248. begin
  1249. Breakout := True;
  1250. Break;
  1251. end;
  1252. else
  1253. ;
  1254. end;
  1255. end;
  1256. if Breakout then
  1257. { Try the next register }
  1258. Continue;
  1259. { We have a free register available }
  1260. Result := CurrentReg;
  1261. if not DontAlloc then
  1262. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1263. Exit;
  1264. end;
  1265. end;
  1266. end;
  1267. { Attempts to allocate a volatile MM register for use between p and hp,
  1268. using AUsedRegs for the current register usage information. Returns NR_NO
  1269. if no free register could be found }
  1270. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1271. var
  1272. RegSet: TCPURegisterSet;
  1273. CurrentSuperReg: Integer;
  1274. CurrentReg: TRegister;
  1275. Currentp: tai;
  1276. Breakout: Boolean;
  1277. begin
  1278. Result := NR_NO;
  1279. RegSet :=
  1280. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1281. current_procinfo.saved_regs_mm;
  1282. for CurrentSuperReg in RegSet do
  1283. begin
  1284. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1285. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1286. begin
  1287. Currentp := p;
  1288. Breakout := False;
  1289. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1290. begin
  1291. case Currentp.typ of
  1292. ait_instruction:
  1293. begin
  1294. if RegInInstruction(CurrentReg, Currentp) then
  1295. begin
  1296. Breakout := True;
  1297. Break;
  1298. end;
  1299. { Cannot allocate across an unconditional jump }
  1300. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1301. Exit;
  1302. end;
  1303. ait_marker:
  1304. { Don't try anything more if a marker is hit }
  1305. Exit;
  1306. ait_regalloc:
  1307. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1308. begin
  1309. Breakout := True;
  1310. Break;
  1311. end;
  1312. else
  1313. ;
  1314. end;
  1315. end;
  1316. if Breakout then
  1317. { Try the next register }
  1318. Continue;
  1319. { We have a free register available }
  1320. Result := CurrentReg;
  1321. if not DontAlloc then
  1322. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1323. Exit;
  1324. end;
  1325. end;
  1326. end;
  1327. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1328. begin
  1329. if not SuperRegistersEqual(reg1,reg2) then
  1330. exit(false);
  1331. if getregtype(reg1)<>R_INTREGISTER then
  1332. exit(true); {because SuperRegisterEqual is true}
  1333. case getsubreg(reg1) of
  1334. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1335. higher, it preserves the high bits, so the new value depends on
  1336. reg2's previous value. In other words, it is equivalent to doing:
  1337. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1338. R_SUBL:
  1339. exit(getsubreg(reg2)=R_SUBL);
  1340. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1341. higher, it actually does a:
  1342. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1343. R_SUBH:
  1344. exit(getsubreg(reg2)=R_SUBH);
  1345. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1346. bits of reg2:
  1347. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1348. R_SUBW:
  1349. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1350. { a write to R_SUBD always overwrites every other subregister,
  1351. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1352. R_SUBD,
  1353. R_SUBQ:
  1354. exit(true);
  1355. else
  1356. internalerror(2017042801);
  1357. end;
  1358. end;
  1359. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1360. begin
  1361. if not SuperRegistersEqual(reg1,reg2) then
  1362. exit(false);
  1363. if getregtype(reg1)<>R_INTREGISTER then
  1364. exit(true); {because SuperRegisterEqual is true}
  1365. case getsubreg(reg1) of
  1366. R_SUBL:
  1367. exit(getsubreg(reg2)<>R_SUBH);
  1368. R_SUBH:
  1369. exit(getsubreg(reg2)<>R_SUBL);
  1370. R_SUBW,
  1371. R_SUBD,
  1372. R_SUBQ:
  1373. exit(true);
  1374. else
  1375. internalerror(2017042802);
  1376. end;
  1377. end;
  1378. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1379. var
  1380. hp1 : tai;
  1381. l : TCGInt;
  1382. begin
  1383. result:=false;
  1384. if not(GetNextInstruction(p, hp1)) then
  1385. exit;
  1386. { changes the code sequence
  1387. shr/sar const1, x
  1388. shl const2, x
  1389. to
  1390. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1391. if (taicpu(p).oper[0]^.typ = top_const) and
  1392. MatchInstruction(hp1,A_SHL,[]) and
  1393. (taicpu(hp1).oper[0]^.typ = top_const) and
  1394. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1395. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1396. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1397. begin
  1398. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1399. not(cs_opt_size in current_settings.optimizerswitches) then
  1400. begin
  1401. { shr/sar const1, %reg
  1402. shl const2, %reg
  1403. with const1 > const2 }
  1404. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1405. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1406. taicpu(hp1).opcode := A_AND;
  1407. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1408. case taicpu(p).opsize Of
  1409. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1410. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1411. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1412. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1413. else
  1414. Internalerror(2017050703)
  1415. end;
  1416. end
  1417. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1418. not(cs_opt_size in current_settings.optimizerswitches) then
  1419. begin
  1420. { shr/sar const1, %reg
  1421. shl const2, %reg
  1422. with const1 < const2 }
  1423. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1424. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1425. taicpu(p).opcode := A_AND;
  1426. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1427. case taicpu(p).opsize Of
  1428. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1429. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1430. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1431. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1432. else
  1433. Internalerror(2017050702)
  1434. end;
  1435. end
  1436. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1437. begin
  1438. { shr/sar const1, %reg
  1439. shl const2, %reg
  1440. with const1 = const2 }
  1441. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1442. taicpu(p).opcode := A_AND;
  1443. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1444. case taicpu(p).opsize Of
  1445. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1446. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1447. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1448. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1449. else
  1450. Internalerror(2017050701)
  1451. end;
  1452. RemoveInstruction(hp1);
  1453. end;
  1454. end;
  1455. end;
  1456. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1457. var
  1458. opsize : topsize;
  1459. hp1, hp2 : tai;
  1460. tmpref : treference;
  1461. ShiftValue : Cardinal;
  1462. BaseValue : TCGInt;
  1463. begin
  1464. result:=false;
  1465. opsize:=taicpu(p).opsize;
  1466. { changes certain "imul const, %reg"'s to lea sequences }
  1467. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1468. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1469. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1470. if (taicpu(p).oper[0]^.val = 1) then
  1471. if (taicpu(p).ops = 2) then
  1472. { remove "imul $1, reg" }
  1473. begin
  1474. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1475. Result := RemoveCurrentP(p);
  1476. end
  1477. else
  1478. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1479. begin
  1480. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1481. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1482. asml.InsertAfter(hp1, p);
  1483. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1484. RemoveCurrentP(p, hp1);
  1485. Result := True;
  1486. end
  1487. else if ((taicpu(p).ops <= 2) or
  1488. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1489. not(cs_opt_size in current_settings.optimizerswitches) and
  1490. (not(GetNextInstruction(p, hp1)) or
  1491. not((tai(hp1).typ = ait_instruction) and
  1492. ((taicpu(hp1).opcode=A_Jcc) and
  1493. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1494. begin
  1495. {
  1496. imul X, reg1, reg2 to
  1497. lea (reg1,reg1,Y), reg2
  1498. shl ZZ,reg2
  1499. imul XX, reg1 to
  1500. lea (reg1,reg1,YY), reg1
  1501. shl ZZ,reg2
  1502. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1503. it does not exist as a separate optimization target in FPC though.
  1504. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1505. at most two zeros
  1506. }
  1507. reference_reset(tmpref,1,[]);
  1508. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1509. begin
  1510. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1511. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1512. TmpRef.base := taicpu(p).oper[1]^.reg;
  1513. TmpRef.index := taicpu(p).oper[1]^.reg;
  1514. if not(BaseValue in [3,5,9]) then
  1515. Internalerror(2018110101);
  1516. TmpRef.ScaleFactor := BaseValue-1;
  1517. if (taicpu(p).ops = 2) then
  1518. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1519. else
  1520. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1521. AsmL.InsertAfter(hp1,p);
  1522. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1523. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1524. RemoveCurrentP(p, hp1);
  1525. if ShiftValue>0 then
  1526. begin
  1527. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1528. AsmL.InsertAfter(hp2,hp1);
  1529. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1530. end;
  1531. Result := True;
  1532. end;
  1533. end;
  1534. end;
  1535. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1536. begin
  1537. Result := False;
  1538. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1539. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1540. begin
  1541. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1542. taicpu(p).opcode := A_MOV;
  1543. Result := True;
  1544. end;
  1545. end;
  1546. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1547. var
  1548. p: taicpu absolute hp; { Implicit typecast }
  1549. i: Integer;
  1550. begin
  1551. Result := False;
  1552. if not assigned(hp) or
  1553. (hp.typ <> ait_instruction) then
  1554. Exit;
  1555. Prefetch(insprop[p.opcode]);
  1556. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1557. with insprop[p.opcode] do
  1558. begin
  1559. case getsubreg(reg) of
  1560. R_SUBW,R_SUBD,R_SUBQ:
  1561. Result:=
  1562. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1563. uncommon flags are checked first }
  1564. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1565. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1566. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1567. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1568. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1569. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1570. R_SUBFLAGCARRY:
  1571. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1572. R_SUBFLAGPARITY:
  1573. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1574. R_SUBFLAGAUXILIARY:
  1575. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1576. R_SUBFLAGZERO:
  1577. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1578. R_SUBFLAGSIGN:
  1579. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1580. R_SUBFLAGOVERFLOW:
  1581. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1582. R_SUBFLAGINTERRUPT:
  1583. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1584. R_SUBFLAGDIRECTION:
  1585. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1586. else
  1587. internalerror(2017050501);
  1588. end;
  1589. exit;
  1590. end;
  1591. { Handle special cases first }
  1592. case p.opcode of
  1593. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1594. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1595. begin
  1596. Result :=
  1597. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1598. (p.oper[1]^.typ = top_reg) and
  1599. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1600. (
  1601. (p.oper[0]^.typ = top_const) or
  1602. (
  1603. (p.oper[0]^.typ = top_reg) and
  1604. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1605. ) or (
  1606. (p.oper[0]^.typ = top_ref) and
  1607. not RegInRef(reg,p.oper[0]^.ref^)
  1608. )
  1609. );
  1610. end;
  1611. A_MUL, A_IMUL:
  1612. Result :=
  1613. (
  1614. (p.ops=3) and { IMUL only }
  1615. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1616. (
  1617. (
  1618. (p.oper[1]^.typ=top_reg) and
  1619. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1620. ) or (
  1621. (p.oper[1]^.typ=top_ref) and
  1622. not RegInRef(reg,p.oper[1]^.ref^)
  1623. )
  1624. )
  1625. ) or (
  1626. (
  1627. (p.ops=1) and
  1628. (
  1629. (
  1630. (
  1631. (p.oper[0]^.typ=top_reg) and
  1632. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1633. )
  1634. ) or (
  1635. (p.oper[0]^.typ=top_ref) and
  1636. not RegInRef(reg,p.oper[0]^.ref^)
  1637. )
  1638. ) and (
  1639. (
  1640. (p.opsize=S_B) and
  1641. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1642. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1643. ) or (
  1644. (p.opsize=S_W) and
  1645. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1646. ) or (
  1647. (p.opsize=S_L) and
  1648. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1649. {$ifdef x86_64}
  1650. ) or (
  1651. (p.opsize=S_Q) and
  1652. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1653. {$endif x86_64}
  1654. )
  1655. )
  1656. )
  1657. );
  1658. A_CBW:
  1659. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1660. {$ifndef x86_64}
  1661. A_LDS:
  1662. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1663. A_LES:
  1664. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1665. {$endif not x86_64}
  1666. A_LFS:
  1667. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1668. A_LGS:
  1669. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1670. A_LSS:
  1671. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1672. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1673. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1674. A_LODSB:
  1675. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1676. A_LODSW:
  1677. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1678. {$ifdef x86_64}
  1679. A_LODSQ:
  1680. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1681. {$endif x86_64}
  1682. A_LODSD:
  1683. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1684. A_FSTSW, A_FNSTSW:
  1685. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1686. else
  1687. begin
  1688. with insprop[p.opcode] do
  1689. begin
  1690. if (
  1691. { xor %reg,%reg etc. is classed as a new value }
  1692. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1693. MatchOpType(p, top_reg, top_reg) and
  1694. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1695. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1696. ) then
  1697. begin
  1698. Result := True;
  1699. Exit;
  1700. end;
  1701. { Make sure the entire register is overwritten }
  1702. if (getregtype(reg) = R_INTREGISTER) then
  1703. begin
  1704. if (p.ops > 0) then
  1705. begin
  1706. if RegInOp(reg, p.oper[0]^) then
  1707. begin
  1708. if (p.oper[0]^.typ = top_ref) then
  1709. begin
  1710. if RegInRef(reg, p.oper[0]^.ref^) then
  1711. begin
  1712. Result := False;
  1713. Exit;
  1714. end;
  1715. end
  1716. else if (p.oper[0]^.typ = top_reg) then
  1717. begin
  1718. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1719. begin
  1720. Result := False;
  1721. Exit;
  1722. end
  1723. else if ([Ch_WOp1]*Ch<>[]) then
  1724. begin
  1725. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1726. Result := True
  1727. else
  1728. begin
  1729. Result := False;
  1730. Exit;
  1731. end;
  1732. end;
  1733. end;
  1734. end;
  1735. if (p.ops > 1) then
  1736. begin
  1737. if RegInOp(reg, p.oper[1]^) then
  1738. begin
  1739. if (p.oper[1]^.typ = top_ref) then
  1740. begin
  1741. if RegInRef(reg, p.oper[1]^.ref^) then
  1742. begin
  1743. Result := False;
  1744. Exit;
  1745. end;
  1746. end
  1747. else if (p.oper[1]^.typ = top_reg) then
  1748. begin
  1749. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1750. begin
  1751. Result := False;
  1752. Exit;
  1753. end
  1754. else if ([Ch_WOp2]*Ch<>[]) then
  1755. begin
  1756. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1757. Result := True
  1758. else
  1759. begin
  1760. Result := False;
  1761. Exit;
  1762. end;
  1763. end;
  1764. end;
  1765. end;
  1766. if (p.ops > 2) then
  1767. begin
  1768. if RegInOp(reg, p.oper[2]^) then
  1769. begin
  1770. if (p.oper[2]^.typ = top_ref) then
  1771. begin
  1772. if RegInRef(reg, p.oper[2]^.ref^) then
  1773. begin
  1774. Result := False;
  1775. Exit;
  1776. end;
  1777. end
  1778. else if (p.oper[2]^.typ = top_reg) then
  1779. begin
  1780. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1781. begin
  1782. Result := False;
  1783. Exit;
  1784. end
  1785. else if ([Ch_WOp3]*Ch<>[]) then
  1786. begin
  1787. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1788. Result := True
  1789. else
  1790. begin
  1791. Result := False;
  1792. Exit;
  1793. end;
  1794. end;
  1795. end;
  1796. end;
  1797. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1798. begin
  1799. if (p.oper[3]^.typ = top_ref) then
  1800. begin
  1801. if RegInRef(reg, p.oper[3]^.ref^) then
  1802. begin
  1803. Result := False;
  1804. Exit;
  1805. end;
  1806. end
  1807. else if (p.oper[3]^.typ = top_reg) then
  1808. begin
  1809. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1810. begin
  1811. Result := False;
  1812. Exit;
  1813. end
  1814. else if ([Ch_WOp4]*Ch<>[]) then
  1815. begin
  1816. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1817. Result := True
  1818. else
  1819. begin
  1820. Result := False;
  1821. Exit;
  1822. end;
  1823. end;
  1824. end;
  1825. end;
  1826. end;
  1827. end;
  1828. end;
  1829. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1830. case getsupreg(reg) of
  1831. RS_EAX:
  1832. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1833. begin
  1834. Result := True;
  1835. Exit;
  1836. end;
  1837. RS_ECX:
  1838. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1839. begin
  1840. Result := True;
  1841. Exit;
  1842. end;
  1843. RS_EDX:
  1844. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1845. begin
  1846. Result := True;
  1847. Exit;
  1848. end;
  1849. RS_EBX:
  1850. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1851. begin
  1852. Result := True;
  1853. Exit;
  1854. end;
  1855. RS_ESP:
  1856. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1857. begin
  1858. Result := True;
  1859. Exit;
  1860. end;
  1861. RS_EBP:
  1862. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1863. begin
  1864. Result := True;
  1865. Exit;
  1866. end;
  1867. RS_ESI:
  1868. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1869. begin
  1870. Result := True;
  1871. Exit;
  1872. end;
  1873. RS_EDI:
  1874. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1875. begin
  1876. Result := True;
  1877. Exit;
  1878. end;
  1879. else
  1880. ;
  1881. end;
  1882. end;
  1883. end;
  1884. end;
  1885. end;
  1886. end;
  1887. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1888. var
  1889. hp2,hp3 : tai;
  1890. begin
  1891. { some x86-64 issue a NOP before the real exit code }
  1892. if MatchInstruction(p,A_NOP,[]) then
  1893. GetNextInstruction(p,p);
  1894. result:=assigned(p) and (p.typ=ait_instruction) and
  1895. ((taicpu(p).opcode = A_RET) or
  1896. ((taicpu(p).opcode=A_LEAVE) and
  1897. GetNextInstruction(p,hp2) and
  1898. MatchInstruction(hp2,A_RET,[S_NO])
  1899. ) or
  1900. (((taicpu(p).opcode=A_LEA) and
  1901. MatchOpType(taicpu(p),top_ref,top_reg) and
  1902. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1903. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1904. ) and
  1905. GetNextInstruction(p,hp2) and
  1906. MatchInstruction(hp2,A_RET,[S_NO])
  1907. ) or
  1908. ((((taicpu(p).opcode=A_MOV) and
  1909. MatchOpType(taicpu(p),top_reg,top_reg) and
  1910. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1911. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1912. ((taicpu(p).opcode=A_LEA) and
  1913. MatchOpType(taicpu(p),top_ref,top_reg) and
  1914. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1915. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1916. )
  1917. ) and
  1918. GetNextInstruction(p,hp2) and
  1919. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1920. MatchOpType(taicpu(hp2),top_reg) and
  1921. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1922. GetNextInstruction(hp2,hp3) and
  1923. MatchInstruction(hp3,A_RET,[S_NO])
  1924. )
  1925. );
  1926. end;
  1927. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1928. begin
  1929. isFoldableArithOp := False;
  1930. case hp1.opcode of
  1931. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1932. isFoldableArithOp :=
  1933. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1934. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1935. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1936. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1937. (taicpu(hp1).oper[1]^.reg = reg);
  1938. A_INC,A_DEC,A_NEG,A_NOT:
  1939. isFoldableArithOp :=
  1940. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1941. (taicpu(hp1).oper[0]^.reg = reg);
  1942. else
  1943. ;
  1944. end;
  1945. end;
  1946. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1947. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1948. var
  1949. hp2: tai;
  1950. begin
  1951. hp2 := p;
  1952. repeat
  1953. hp2 := tai(hp2.previous);
  1954. if assigned(hp2) and
  1955. (hp2.typ = ait_regalloc) and
  1956. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1957. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1958. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1959. begin
  1960. RemoveInstruction(hp2);
  1961. break;
  1962. end;
  1963. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1964. end;
  1965. begin
  1966. case current_procinfo.procdef.returndef.typ of
  1967. arraydef,recorddef,pointerdef,
  1968. stringdef,enumdef,procdef,objectdef,errordef,
  1969. filedef,setdef,procvardef,
  1970. classrefdef,forwarddef:
  1971. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1972. orddef:
  1973. if current_procinfo.procdef.returndef.size <> 0 then
  1974. begin
  1975. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1976. { for int64/qword }
  1977. if current_procinfo.procdef.returndef.size = 8 then
  1978. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1979. end;
  1980. else
  1981. ;
  1982. end;
  1983. end;
  1984. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1985. var
  1986. hp1,hp2 : tai;
  1987. begin
  1988. result:=false;
  1989. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1990. begin
  1991. { vmova* reg1,reg1
  1992. =>
  1993. <nop> }
  1994. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  1995. begin
  1996. RemoveCurrentP(p);
  1997. result:=true;
  1998. exit;
  1999. end;
  2000. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2001. begin
  2002. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2003. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2004. begin
  2005. { vmova* reg1,reg2
  2006. vmova* reg2,reg3
  2007. dealloc reg2
  2008. =>
  2009. vmova* reg1,reg3 }
  2010. TransferUsedRegs(TmpUsedRegs);
  2011. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2012. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2013. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2014. begin
  2015. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2016. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2017. RemoveInstruction(hp1);
  2018. result:=true;
  2019. exit;
  2020. end;
  2021. { special case:
  2022. vmova* reg1,<op>
  2023. vmova* <op>,reg1
  2024. =>
  2025. vmova* reg1,<op> }
  2026. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2027. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2028. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2029. ) then
  2030. begin
  2031. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2032. RemoveInstruction(hp1);
  2033. result:=true;
  2034. exit;
  2035. end
  2036. end
  2037. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2038. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2039. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2040. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2041. ) and
  2042. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2043. begin
  2044. { vmova* reg1,reg2
  2045. vmovs* reg2,<op>
  2046. dealloc reg2
  2047. =>
  2048. vmovs* reg1,reg3 }
  2049. TransferUsedRegs(TmpUsedRegs);
  2050. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2051. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2052. begin
  2053. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2054. taicpu(p).opcode:=taicpu(hp1).opcode;
  2055. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2056. RemoveInstruction(hp1);
  2057. result:=true;
  2058. exit;
  2059. end
  2060. end;
  2061. end;
  2062. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2063. begin
  2064. if MatchInstruction(hp1,[A_VFMADDPD,
  2065. A_VFMADD132PD,
  2066. A_VFMADD132PS,
  2067. A_VFMADD132SD,
  2068. A_VFMADD132SS,
  2069. A_VFMADD213PD,
  2070. A_VFMADD213PS,
  2071. A_VFMADD213SD,
  2072. A_VFMADD213SS,
  2073. A_VFMADD231PD,
  2074. A_VFMADD231PS,
  2075. A_VFMADD231SD,
  2076. A_VFMADD231SS,
  2077. A_VFMADDSUB132PD,
  2078. A_VFMADDSUB132PS,
  2079. A_VFMADDSUB213PD,
  2080. A_VFMADDSUB213PS,
  2081. A_VFMADDSUB231PD,
  2082. A_VFMADDSUB231PS,
  2083. A_VFMSUB132PD,
  2084. A_VFMSUB132PS,
  2085. A_VFMSUB132SD,
  2086. A_VFMSUB132SS,
  2087. A_VFMSUB213PD,
  2088. A_VFMSUB213PS,
  2089. A_VFMSUB213SD,
  2090. A_VFMSUB213SS,
  2091. A_VFMSUB231PD,
  2092. A_VFMSUB231PS,
  2093. A_VFMSUB231SD,
  2094. A_VFMSUB231SS,
  2095. A_VFMSUBADD132PD,
  2096. A_VFMSUBADD132PS,
  2097. A_VFMSUBADD213PD,
  2098. A_VFMSUBADD213PS,
  2099. A_VFMSUBADD231PD,
  2100. A_VFMSUBADD231PS,
  2101. A_VFNMADD132PD,
  2102. A_VFNMADD132PS,
  2103. A_VFNMADD132SD,
  2104. A_VFNMADD132SS,
  2105. A_VFNMADD213PD,
  2106. A_VFNMADD213PS,
  2107. A_VFNMADD213SD,
  2108. A_VFNMADD213SS,
  2109. A_VFNMADD231PD,
  2110. A_VFNMADD231PS,
  2111. A_VFNMADD231SD,
  2112. A_VFNMADD231SS,
  2113. A_VFNMSUB132PD,
  2114. A_VFNMSUB132PS,
  2115. A_VFNMSUB132SD,
  2116. A_VFNMSUB132SS,
  2117. A_VFNMSUB213PD,
  2118. A_VFNMSUB213PS,
  2119. A_VFNMSUB213SD,
  2120. A_VFNMSUB213SS,
  2121. A_VFNMSUB231PD,
  2122. A_VFNMSUB231PS,
  2123. A_VFNMSUB231SD,
  2124. A_VFNMSUB231SS],[S_NO]) and
  2125. { we mix single and double opperations here because we assume that the compiler
  2126. generates vmovapd only after double operations and vmovaps only after single operations }
  2127. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2128. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2129. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2130. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2131. begin
  2132. TransferUsedRegs(TmpUsedRegs);
  2133. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2134. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2135. begin
  2136. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2137. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2138. RemoveCurrentP(p)
  2139. else
  2140. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2141. RemoveInstruction(hp2);
  2142. end;
  2143. end
  2144. else if (hp1.typ = ait_instruction) and
  2145. (((taicpu(p).opcode=A_MOVAPS) and
  2146. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2147. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2148. ((taicpu(p).opcode=A_MOVAPD) and
  2149. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2150. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2151. ) and
  2152. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2153. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2154. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2155. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2156. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2157. { change
  2158. movapX reg,reg2
  2159. addsX/subsX/... reg3, reg2
  2160. movapX reg2,reg
  2161. to
  2162. addsX/subsX/... reg3,reg
  2163. }
  2164. begin
  2165. TransferUsedRegs(TmpUsedRegs);
  2166. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2167. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2168. begin
  2169. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2170. debug_op2str(taicpu(p).opcode)+' '+
  2171. debug_op2str(taicpu(hp1).opcode)+' '+
  2172. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2173. { we cannot eliminate the first move if
  2174. the operations uses the same register for source and dest }
  2175. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2176. { Remember that hp1 is not necessarily the immediate
  2177. next instruction }
  2178. RemoveCurrentP(p);
  2179. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2180. RemoveInstruction(hp2);
  2181. result:=true;
  2182. end;
  2183. end
  2184. else if (hp1.typ = ait_instruction) and
  2185. (((taicpu(p).opcode=A_VMOVAPD) and
  2186. (taicpu(hp1).opcode=A_VCOMISD)) or
  2187. ((taicpu(p).opcode=A_VMOVAPS) and
  2188. ((taicpu(hp1).opcode=A_VCOMISS))
  2189. )
  2190. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2191. { change
  2192. movapX reg,reg1
  2193. vcomisX reg1,reg1
  2194. to
  2195. vcomisX reg,reg
  2196. }
  2197. begin
  2198. TransferUsedRegs(TmpUsedRegs);
  2199. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2200. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2201. begin
  2202. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2203. debug_op2str(taicpu(p).opcode)+' '+
  2204. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2205. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2206. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2207. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2208. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2209. RemoveCurrentP(p);
  2210. result:=true;
  2211. exit;
  2212. end;
  2213. end
  2214. end;
  2215. end;
  2216. end;
  2217. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2218. var
  2219. hp1 : tai;
  2220. begin
  2221. result:=false;
  2222. { replace
  2223. V<Op>X %mreg1,%mreg2,%mreg3
  2224. VMovX %mreg3,%mreg4
  2225. dealloc %mreg3
  2226. by
  2227. V<Op>X %mreg1,%mreg2,%mreg4
  2228. ?
  2229. }
  2230. if GetNextInstruction(p,hp1) and
  2231. { we mix single and double operations here because we assume that the compiler
  2232. generates vmovapd only after double operations and vmovaps only after single operations }
  2233. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2234. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2235. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2236. begin
  2237. TransferUsedRegs(TmpUsedRegs);
  2238. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2239. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2240. begin
  2241. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2242. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2243. RemoveInstruction(hp1);
  2244. result:=true;
  2245. end;
  2246. end;
  2247. end;
  2248. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2249. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2250. begin
  2251. Result := False;
  2252. { For safety reasons, only check for exact register matches }
  2253. { Check base register }
  2254. if (ref.base = AOldReg) then
  2255. begin
  2256. ref.base := ANewReg;
  2257. Result := True;
  2258. end;
  2259. { Check index register }
  2260. if (ref.index = AOldReg) then
  2261. begin
  2262. ref.index := ANewReg;
  2263. Result := True;
  2264. end;
  2265. end;
  2266. { Replaces all references to AOldReg in an operand to ANewReg }
  2267. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2268. var
  2269. OldSupReg, NewSupReg: TSuperRegister;
  2270. OldSubReg, NewSubReg: TSubRegister;
  2271. OldRegType: TRegisterType;
  2272. ThisOper: POper;
  2273. begin
  2274. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2275. Result := False;
  2276. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2277. InternalError(2020011801);
  2278. OldSupReg := getsupreg(AOldReg);
  2279. OldSubReg := getsubreg(AOldReg);
  2280. OldRegType := getregtype(AOldReg);
  2281. NewSupReg := getsupreg(ANewReg);
  2282. NewSubReg := getsubreg(ANewReg);
  2283. if OldRegType <> getregtype(ANewReg) then
  2284. InternalError(2020011802);
  2285. if OldSubReg <> NewSubReg then
  2286. InternalError(2020011803);
  2287. case ThisOper^.typ of
  2288. top_reg:
  2289. if (
  2290. (ThisOper^.reg = AOldReg) or
  2291. (
  2292. (OldRegType = R_INTREGISTER) and
  2293. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2294. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2295. (
  2296. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2297. {$ifndef x86_64}
  2298. and (
  2299. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2300. don't have an 8-bit representation }
  2301. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2302. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2303. )
  2304. {$endif x86_64}
  2305. )
  2306. )
  2307. ) then
  2308. begin
  2309. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2310. Result := True;
  2311. end;
  2312. top_ref:
  2313. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2314. Result := True;
  2315. else
  2316. ;
  2317. end;
  2318. end;
  2319. { Replaces all references to AOldReg in an instruction to ANewReg }
  2320. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2321. const
  2322. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2323. var
  2324. OperIdx: Integer;
  2325. begin
  2326. Result := False;
  2327. for OperIdx := 0 to p.ops - 1 do
  2328. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2329. begin
  2330. { The shift and rotate instructions can only use CL }
  2331. if not (
  2332. (OperIdx = 0) and
  2333. { This second condition just helps to avoid unnecessarily
  2334. calling MatchInstruction for 10 different opcodes }
  2335. (p.oper[0]^.reg = NR_CL) and
  2336. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2337. ) then
  2338. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2339. end
  2340. else if p.oper[OperIdx]^.typ = top_ref then
  2341. { It's okay to replace registers in references that get written to }
  2342. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2343. end;
  2344. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2345. begin
  2346. Result :=
  2347. (ref^.index = NR_NO) and
  2348. (
  2349. {$ifdef x86_64}
  2350. (
  2351. (ref^.base = NR_RIP) and
  2352. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2353. ) or
  2354. {$endif x86_64}
  2355. (ref^.refaddr = addr_full) or
  2356. (ref^.base = NR_STACK_POINTER_REG) or
  2357. (ref^.base = current_procinfo.framepointer)
  2358. );
  2359. end;
  2360. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2361. var
  2362. l: asizeint;
  2363. begin
  2364. Result := False;
  2365. { Should have been checked previously }
  2366. if p.opcode <> A_LEA then
  2367. InternalError(2020072501);
  2368. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2369. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2370. not(cs_opt_size in current_settings.optimizerswitches) then
  2371. exit;
  2372. with p.oper[0]^.ref^ do
  2373. begin
  2374. if (base <> p.oper[1]^.reg) or
  2375. (index <> NR_NO) or
  2376. assigned(symbol) then
  2377. exit;
  2378. l:=offset;
  2379. if (l=1) and UseIncDec then
  2380. begin
  2381. p.opcode:=A_INC;
  2382. p.loadreg(0,p.oper[1]^.reg);
  2383. p.ops:=1;
  2384. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2385. end
  2386. else if (l=-1) and UseIncDec then
  2387. begin
  2388. p.opcode:=A_DEC;
  2389. p.loadreg(0,p.oper[1]^.reg);
  2390. p.ops:=1;
  2391. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2392. end
  2393. else
  2394. begin
  2395. if (l<0) and (l<>-2147483648) then
  2396. begin
  2397. p.opcode:=A_SUB;
  2398. p.loadConst(0,-l);
  2399. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2400. end
  2401. else
  2402. begin
  2403. p.opcode:=A_ADD;
  2404. p.loadConst(0,l);
  2405. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2406. end;
  2407. end;
  2408. end;
  2409. Result := True;
  2410. end;
  2411. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2412. var
  2413. CurrentReg, ReplaceReg: TRegister;
  2414. begin
  2415. Result := False;
  2416. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2417. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2418. case hp.opcode of
  2419. A_FSTSW, A_FNSTSW,
  2420. A_IN, A_INS, A_OUT, A_OUTS,
  2421. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2422. { These routines have explicit operands, but they are restricted in
  2423. what they can be (e.g. IN and OUT can only read from AL, AX or
  2424. EAX. }
  2425. Exit;
  2426. A_IMUL:
  2427. begin
  2428. { The 1-operand version writes to implicit registers
  2429. The 2-operand version reads from the first operator, and reads
  2430. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2431. the 3-operand version reads from a register that it doesn't write to
  2432. }
  2433. case hp.ops of
  2434. 1:
  2435. if (
  2436. (
  2437. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2438. ) or
  2439. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2440. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2441. begin
  2442. Result := True;
  2443. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2444. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2445. end;
  2446. 2:
  2447. { Only modify the first parameter }
  2448. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2449. begin
  2450. Result := True;
  2451. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2452. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2453. end;
  2454. 3:
  2455. { Only modify the second parameter }
  2456. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2457. begin
  2458. Result := True;
  2459. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2460. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2461. end;
  2462. else
  2463. InternalError(2020012901);
  2464. end;
  2465. end;
  2466. else
  2467. if (hp.ops > 0) and
  2468. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2469. begin
  2470. Result := True;
  2471. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2472. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2473. end;
  2474. end;
  2475. end;
  2476. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2477. var
  2478. hp2: tai;
  2479. p_SourceReg, p_TargetReg: TRegister;
  2480. begin
  2481. Result := False;
  2482. { Backward optimisation. If we have:
  2483. func. %reg1,%reg2
  2484. mov %reg2,%reg3
  2485. (dealloc %reg2)
  2486. Change to:
  2487. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2488. Perform similar optimisations with 1, 3 and 4-operand instructions
  2489. that only have one output.
  2490. }
  2491. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2492. begin
  2493. p_SourceReg := taicpu(p).oper[0]^.reg;
  2494. p_TargetReg := taicpu(p).oper[1]^.reg;
  2495. TransferUsedRegs(TmpUsedRegs);
  2496. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2497. GetLastInstruction(p, hp2) and
  2498. (hp2.typ = ait_instruction) and
  2499. { Have to make sure it's an instruction that only reads from
  2500. the first operands and only writes (not reads or modifies) to
  2501. the last one; in essence, a pure function such as BSR, POPCNT
  2502. or ANDN }
  2503. (
  2504. (
  2505. (taicpu(hp2).ops = 1) and
  2506. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2507. ) or
  2508. (
  2509. (taicpu(hp2).ops = 2) and
  2510. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2511. ) or
  2512. (
  2513. (taicpu(hp2).ops = 3) and
  2514. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2515. ) or
  2516. (
  2517. (taicpu(hp2).ops = 4) and
  2518. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2519. )
  2520. ) and
  2521. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2522. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2523. begin
  2524. case taicpu(hp2).opcode of
  2525. A_FSTSW, A_FNSTSW,
  2526. A_IN, A_INS, A_OUT, A_OUTS,
  2527. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2528. { These routines have explicit operands, but they are restricted in
  2529. what they can be (e.g. IN and OUT can only read from AL, AX or
  2530. EAX. }
  2531. ;
  2532. else
  2533. begin
  2534. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2535. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2536. if not RegInInstruction(p_TargetReg, hp2) then
  2537. begin
  2538. { Since we're allocating from an earlier point, we
  2539. need to remove the register from the tracking }
  2540. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2541. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2542. end;
  2543. RemoveCurrentp(p, hp1);
  2544. { If the Func was another MOV instruction, we might get
  2545. "mov %reg,%reg" that doesn't get removed in Pass 2
  2546. otherwise, so deal with it here (also do something
  2547. similar with lea (%reg),%reg}
  2548. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2549. begin
  2550. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2551. if p = hp2 then
  2552. RemoveCurrentp(p)
  2553. else
  2554. RemoveInstruction(hp2);
  2555. end;
  2556. Result := True;
  2557. Exit;
  2558. end;
  2559. end;
  2560. end;
  2561. end;
  2562. end;
  2563. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2564. var
  2565. hp1, hp2, hp3: tai;
  2566. DoOptimisation, TempBool: Boolean;
  2567. {$ifdef x86_64}
  2568. NewConst: TCGInt;
  2569. {$endif x86_64}
  2570. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2571. begin
  2572. if taicpu(hp1).opcode = signed_movop then
  2573. begin
  2574. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2575. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2576. end
  2577. else
  2578. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2579. end;
  2580. function TryConstMerge(var p1, p2: tai): Boolean;
  2581. var
  2582. ThisRef: TReference;
  2583. begin
  2584. Result := False;
  2585. ThisRef := taicpu(p2).oper[1]^.ref^;
  2586. { Only permit writes to the stack, since we can guarantee alignment with that }
  2587. if (ThisRef.index = NR_NO) and
  2588. (
  2589. (ThisRef.base = NR_STACK_POINTER_REG) or
  2590. (ThisRef.base = current_procinfo.framepointer)
  2591. ) then
  2592. begin
  2593. case taicpu(p).opsize of
  2594. S_B:
  2595. begin
  2596. { Word writes must be on a 2-byte boundary }
  2597. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2598. begin
  2599. { Reduce offset of second reference to see if it is sequential with the first }
  2600. Dec(ThisRef.offset, 1);
  2601. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2602. begin
  2603. { Make sure the constants aren't represented as a
  2604. negative number, as these won't merge properly }
  2605. taicpu(p1).opsize := S_W;
  2606. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2607. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2608. RemoveInstruction(p2);
  2609. Result := True;
  2610. end;
  2611. end;
  2612. end;
  2613. S_W:
  2614. begin
  2615. { Longword writes must be on a 4-byte boundary }
  2616. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2617. begin
  2618. { Reduce offset of second reference to see if it is sequential with the first }
  2619. Dec(ThisRef.offset, 2);
  2620. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2621. begin
  2622. { Make sure the constants aren't represented as a
  2623. negative number, as these won't merge properly }
  2624. taicpu(p1).opsize := S_L;
  2625. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2626. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2627. RemoveInstruction(p2);
  2628. Result := True;
  2629. end;
  2630. end;
  2631. end;
  2632. {$ifdef x86_64}
  2633. S_L:
  2634. begin
  2635. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2636. see if the constants can be encoded this way. }
  2637. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2638. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2639. { Quadword writes must be on an 8-byte boundary }
  2640. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2641. begin
  2642. { Reduce offset of second reference to see if it is sequential with the first }
  2643. Dec(ThisRef.offset, 4);
  2644. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2645. begin
  2646. { Make sure the constants aren't represented as a
  2647. negative number, as these won't merge properly }
  2648. taicpu(p1).opsize := S_Q;
  2649. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2650. taicpu(p1).oper[0]^.val := NewConst;
  2651. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2652. RemoveInstruction(p2);
  2653. Result := True;
  2654. end;
  2655. end;
  2656. end;
  2657. {$endif x86_64}
  2658. else
  2659. ;
  2660. end;
  2661. end;
  2662. end;
  2663. var
  2664. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2665. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2666. NewSize: topsize; NewOffset: asizeint;
  2667. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2668. SourceRef, TargetRef: TReference;
  2669. MovAligned, MovUnaligned: TAsmOp;
  2670. ThisRef: TReference;
  2671. JumpTracking: TLinkedList;
  2672. begin
  2673. Result:=false;
  2674. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2675. { remove mov reg1,reg1? }
  2676. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2677. then
  2678. begin
  2679. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2680. { take care of the register (de)allocs following p }
  2681. RemoveCurrentP(p, hp1);
  2682. Result:=true;
  2683. exit;
  2684. end;
  2685. { All the next optimisations require a next instruction }
  2686. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2687. Exit;
  2688. { Prevent compiler warnings }
  2689. p_TargetReg := NR_NO;
  2690. if taicpu(p).oper[1]^.typ = top_reg then
  2691. begin
  2692. { Saves on a large number of dereferences }
  2693. p_TargetReg := taicpu(p).oper[1]^.reg;
  2694. { Look for:
  2695. mov %reg1,%reg2
  2696. ??? %reg2,r/m
  2697. Change to:
  2698. mov %reg1,%reg2
  2699. ??? %reg1,r/m
  2700. }
  2701. if taicpu(p).oper[0]^.typ = top_reg then
  2702. begin
  2703. if RegReadByInstruction(p_TargetReg, hp1) and
  2704. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2705. begin
  2706. { A change has occurred, just not in p }
  2707. Result := True;
  2708. TransferUsedRegs(TmpUsedRegs);
  2709. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2710. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2711. { Just in case something didn't get modified (e.g. an
  2712. implicit register) }
  2713. not RegReadByInstruction(p_TargetReg, hp1) then
  2714. begin
  2715. { We can remove the original MOV }
  2716. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2717. RemoveCurrentp(p, hp1);
  2718. { UsedRegs got updated by RemoveCurrentp }
  2719. Result := True;
  2720. Exit;
  2721. end;
  2722. { If we know a MOV instruction has become a null operation, we might as well
  2723. get rid of it now to save time. }
  2724. if (taicpu(hp1).opcode = A_MOV) and
  2725. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2726. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2727. { Just being a register is enough to confirm it's a null operation }
  2728. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2729. begin
  2730. Result := True;
  2731. { Speed-up to reduce a pipeline stall... if we had something like...
  2732. movl %eax,%edx
  2733. movw %dx,%ax
  2734. ... the second instruction would change to movw %ax,%ax, but
  2735. given that it is now %ax that's active rather than %eax,
  2736. penalties might occur due to a partial register write, so instead,
  2737. change it to a MOVZX instruction when optimising for speed.
  2738. }
  2739. if not (cs_opt_size in current_settings.optimizerswitches) and
  2740. IsMOVZXAcceptable and
  2741. (taicpu(hp1).opsize < taicpu(p).opsize)
  2742. {$ifdef x86_64}
  2743. { operations already implicitly set the upper 64 bits to zero }
  2744. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2745. {$endif x86_64}
  2746. then
  2747. begin
  2748. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2749. case taicpu(p).opsize of
  2750. S_W:
  2751. if taicpu(hp1).opsize = S_B then
  2752. taicpu(hp1).opsize := S_BL
  2753. else
  2754. InternalError(2020012911);
  2755. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2756. case taicpu(hp1).opsize of
  2757. S_B:
  2758. taicpu(hp1).opsize := S_BL;
  2759. S_W:
  2760. taicpu(hp1).opsize := S_WL;
  2761. else
  2762. InternalError(2020012912);
  2763. end;
  2764. else
  2765. InternalError(2020012910);
  2766. end;
  2767. taicpu(hp1).opcode := A_MOVZX;
  2768. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2769. end
  2770. else
  2771. begin
  2772. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2773. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2774. RemoveInstruction(hp1);
  2775. { The instruction after what was hp1 is now the immediate next instruction,
  2776. so we can continue to make optimisations if it's present }
  2777. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2778. Exit;
  2779. hp1 := hp2;
  2780. end;
  2781. end;
  2782. end;
  2783. end;
  2784. end;
  2785. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2786. overwrites the original destination register. e.g.
  2787. movl ###,%reg2d
  2788. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2789. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2790. }
  2791. if (taicpu(p).oper[1]^.typ = top_reg) and
  2792. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2793. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2794. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2795. begin
  2796. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2797. begin
  2798. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2799. case taicpu(p).oper[0]^.typ of
  2800. top_const:
  2801. { We have something like:
  2802. movb $x, %regb
  2803. movzbl %regb,%regd
  2804. Change to:
  2805. movl $x, %regd
  2806. }
  2807. begin
  2808. case taicpu(hp1).opsize of
  2809. S_BW:
  2810. begin
  2811. convert_mov_value(A_MOVSX, $FF);
  2812. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2813. taicpu(p).opsize := S_W;
  2814. end;
  2815. S_BL:
  2816. begin
  2817. convert_mov_value(A_MOVSX, $FF);
  2818. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2819. taicpu(p).opsize := S_L;
  2820. end;
  2821. S_WL:
  2822. begin
  2823. convert_mov_value(A_MOVSX, $FFFF);
  2824. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2825. taicpu(p).opsize := S_L;
  2826. end;
  2827. {$ifdef x86_64}
  2828. S_BQ:
  2829. begin
  2830. convert_mov_value(A_MOVSX, $FF);
  2831. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2832. taicpu(p).opsize := S_Q;
  2833. end;
  2834. S_WQ:
  2835. begin
  2836. convert_mov_value(A_MOVSX, $FFFF);
  2837. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2838. taicpu(p).opsize := S_Q;
  2839. end;
  2840. S_LQ:
  2841. begin
  2842. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2843. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2844. taicpu(p).opsize := S_Q;
  2845. end;
  2846. {$endif x86_64}
  2847. else
  2848. { If hp1 was a MOV instruction, it should have been
  2849. optimised already }
  2850. InternalError(2020021001);
  2851. end;
  2852. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2853. RemoveInstruction(hp1);
  2854. Result := True;
  2855. Exit;
  2856. end;
  2857. top_ref:
  2858. begin
  2859. { We have something like:
  2860. movb mem, %regb
  2861. movzbl %regb,%regd
  2862. Change to:
  2863. movzbl mem, %regd
  2864. }
  2865. ThisRef := taicpu(p).oper[0]^.ref^;
  2866. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2867. begin
  2868. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2869. taicpu(hp1).loadref(0, ThisRef);
  2870. { Make sure any registers in the references are properly tracked }
  2871. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2872. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2873. if (ThisRef.index <> NR_NO) then
  2874. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2875. RemoveCurrentP(p, hp1);
  2876. Result := True;
  2877. Exit;
  2878. end;
  2879. end;
  2880. else
  2881. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2882. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2883. Exit;
  2884. end;
  2885. end
  2886. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2887. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2888. optimised }
  2889. else
  2890. begin
  2891. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2892. RemoveCurrentP(p, hp1);
  2893. Result := True;
  2894. Exit;
  2895. end;
  2896. end;
  2897. if (taicpu(hp1).opcode = A_AND) and
  2898. (taicpu(p).oper[1]^.typ = top_reg) and
  2899. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2900. begin
  2901. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2902. begin
  2903. case taicpu(p).opsize of
  2904. S_L:
  2905. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2906. begin
  2907. { Optimize out:
  2908. mov x, %reg
  2909. and ffffffffh, %reg
  2910. }
  2911. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2912. RemoveInstruction(hp1);
  2913. Result:=true;
  2914. exit;
  2915. end;
  2916. S_Q: { TODO: Confirm if this is even possible }
  2917. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2918. begin
  2919. { Optimize out:
  2920. mov x, %reg
  2921. and ffffffffffffffffh, %reg
  2922. }
  2923. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2924. RemoveInstruction(hp1);
  2925. Result:=true;
  2926. exit;
  2927. end;
  2928. else
  2929. ;
  2930. end;
  2931. if (
  2932. (taicpu(p).oper[0]^.typ=top_reg) or
  2933. (
  2934. (taicpu(p).oper[0]^.typ=top_ref) and
  2935. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2936. )
  2937. ) and
  2938. GetNextInstruction(hp1,hp2) and
  2939. MatchInstruction(hp2,A_TEST,[]) and
  2940. (
  2941. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2942. (
  2943. { If the register being tested is smaller than the one
  2944. that received a bitwise AND, permit it if the constant
  2945. fits into the smaller size }
  2946. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2947. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2948. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2949. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2950. (
  2951. (
  2952. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2953. (taicpu(hp1).oper[0]^.val <= $FF)
  2954. ) or
  2955. (
  2956. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2957. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2958. {$ifdef x86_64}
  2959. ) or
  2960. (
  2961. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2962. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2963. {$endif x86_64}
  2964. )
  2965. )
  2966. )
  2967. ) and
  2968. (
  2969. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2970. MatchOperand(taicpu(hp2).oper[0]^,-1)
  2971. ) and
  2972. GetNextInstruction(hp2,hp3) and
  2973. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2974. (taicpu(hp3).condition in [C_E,C_NE]) then
  2975. begin
  2976. TransferUsedRegs(TmpUsedRegs);
  2977. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2978. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2979. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2980. begin
  2981. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2982. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2983. taicpu(hp1).opcode:=A_TEST;
  2984. { Shrink the TEST instruction down to the smallest possible size }
  2985. case taicpu(hp1).oper[0]^.val of
  2986. 0..255:
  2987. if (taicpu(hp1).opsize <> S_B)
  2988. {$ifndef x86_64}
  2989. and (
  2990. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  2991. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  2992. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  2993. )
  2994. {$endif x86_64}
  2995. then
  2996. begin
  2997. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2998. { Only print debug message if the TEST instruction
  2999. is a different size before and after }
  3000. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3001. taicpu(hp1).opsize := S_B;
  3002. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3003. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3004. end;
  3005. 256..65535:
  3006. if (taicpu(hp1).opsize <> S_W) then
  3007. begin
  3008. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3009. { Only print debug message if the TEST instruction
  3010. is a different size before and after }
  3011. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3012. taicpu(hp1).opsize := S_W;
  3013. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3014. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3015. end;
  3016. {$ifdef x86_64}
  3017. 65536..$7FFFFFFF:
  3018. if (taicpu(hp1).opsize <> S_L) then
  3019. begin
  3020. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3021. { Only print debug message if the TEST instruction
  3022. is a different size before and after }
  3023. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3024. taicpu(hp1).opsize := S_L;
  3025. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3026. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3027. end;
  3028. {$endif x86_64}
  3029. else
  3030. ;
  3031. end;
  3032. RemoveInstruction(hp2);
  3033. RemoveCurrentP(p, hp1);
  3034. Result:=true;
  3035. exit;
  3036. end;
  3037. end;
  3038. end
  3039. else if IsMOVZXAcceptable and
  3040. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3041. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3042. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3043. then
  3044. begin
  3045. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3046. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3047. case taicpu(p).opsize of
  3048. S_B:
  3049. if (taicpu(hp1).oper[0]^.val = $ff) then
  3050. begin
  3051. { Convert:
  3052. movb x, %regl movb x, %regl
  3053. andw ffh, %regw andl ffh, %regd
  3054. To:
  3055. movzbw x, %regd movzbl x, %regd
  3056. (Identical registers, just different sizes)
  3057. }
  3058. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3059. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3060. case taicpu(hp1).opsize of
  3061. S_W: NewSize := S_BW;
  3062. S_L: NewSize := S_BL;
  3063. {$ifdef x86_64}
  3064. S_Q: NewSize := S_BQ;
  3065. {$endif x86_64}
  3066. else
  3067. InternalError(2018011510);
  3068. end;
  3069. end
  3070. else
  3071. NewSize := S_NO;
  3072. S_W:
  3073. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3074. begin
  3075. { Convert:
  3076. movw x, %regw
  3077. andl ffffh, %regd
  3078. To:
  3079. movzwl x, %regd
  3080. (Identical registers, just different sizes)
  3081. }
  3082. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3083. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3084. case taicpu(hp1).opsize of
  3085. S_L: NewSize := S_WL;
  3086. {$ifdef x86_64}
  3087. S_Q: NewSize := S_WQ;
  3088. {$endif x86_64}
  3089. else
  3090. InternalError(2018011511);
  3091. end;
  3092. end
  3093. else
  3094. NewSize := S_NO;
  3095. else
  3096. NewSize := S_NO;
  3097. end;
  3098. if NewSize <> S_NO then
  3099. begin
  3100. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3101. { The actual optimization }
  3102. taicpu(p).opcode := A_MOVZX;
  3103. taicpu(p).changeopsize(NewSize);
  3104. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3105. { Safeguard if "and" is followed by a conditional command }
  3106. TransferUsedRegs(TmpUsedRegs);
  3107. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3108. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3109. begin
  3110. { At this point, the "and" command is effectively equivalent to
  3111. "test %reg,%reg". This will be handled separately by the
  3112. Peephole Optimizer. [Kit] }
  3113. DebugMsg(SPeepholeOptimization + PreMessage +
  3114. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3115. end
  3116. else
  3117. begin
  3118. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3119. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3120. RemoveInstruction(hp1);
  3121. end;
  3122. Result := True;
  3123. Exit;
  3124. end;
  3125. end;
  3126. end;
  3127. if (taicpu(hp1).opcode = A_OR) and
  3128. (taicpu(p).oper[1]^.typ = top_reg) and
  3129. MatchOperand(taicpu(p).oper[0]^, 0) and
  3130. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3131. begin
  3132. { mov 0, %reg
  3133. or ###,%reg
  3134. Change to (only if the flags are not used):
  3135. mov ###,%reg
  3136. }
  3137. TransferUsedRegs(TmpUsedRegs);
  3138. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3139. DoOptimisation := True;
  3140. { Even if the flags are used, we might be able to do the optimisation
  3141. if the conditions are predictable }
  3142. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3143. begin
  3144. { Only perform if ### = %reg (the same register) or equal to 0,
  3145. so %reg is guaranteed to still have a value of zero }
  3146. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3147. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3148. begin
  3149. hp2 := hp1;
  3150. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3151. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3152. GetNextInstruction(hp2, hp3) do
  3153. begin
  3154. { Don't continue modifying if the flags state is getting changed }
  3155. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3156. Break;
  3157. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3158. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3159. begin
  3160. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3161. begin
  3162. { Condition is always true }
  3163. case taicpu(hp3).opcode of
  3164. A_Jcc:
  3165. begin
  3166. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3167. { Check for jump shortcuts before we destroy the condition }
  3168. DoJumpOptimizations(hp3, TempBool);
  3169. MakeUnconditional(taicpu(hp3));
  3170. Result := True;
  3171. end;
  3172. A_CMOVcc:
  3173. begin
  3174. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3175. taicpu(hp3).opcode := A_MOV;
  3176. taicpu(hp3).condition := C_None;
  3177. Result := True;
  3178. end;
  3179. A_SETcc:
  3180. begin
  3181. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3182. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3183. taicpu(hp3).opcode := A_MOV;
  3184. taicpu(hp3).ops := 2;
  3185. taicpu(hp3).condition := C_None;
  3186. taicpu(hp3).opsize := S_B;
  3187. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3188. taicpu(hp3).loadconst(0, 1);
  3189. Result := True;
  3190. end;
  3191. else
  3192. InternalError(2021090701);
  3193. end;
  3194. end
  3195. else if (taicpu(hp3).condition in [C_A, C_B, C_C, C_G, C_L, C_NE, C_NZ, C_O, C_S]) then
  3196. begin
  3197. { Condition is always false }
  3198. case taicpu(hp3).opcode of
  3199. A_Jcc:
  3200. begin
  3201. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3202. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3203. RemoveInstruction(hp3);
  3204. Result := True;
  3205. { Since hp3 was deleted, hp2 must not be updated }
  3206. Continue;
  3207. end;
  3208. A_CMOVcc:
  3209. begin
  3210. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3211. RemoveInstruction(hp3);
  3212. Result := True;
  3213. { Since hp3 was deleted, hp2 must not be updated }
  3214. Continue;
  3215. end;
  3216. A_SETcc:
  3217. begin
  3218. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3219. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3220. taicpu(hp3).opcode := A_MOV;
  3221. taicpu(hp3).ops := 2;
  3222. taicpu(hp3).condition := C_None;
  3223. taicpu(hp3).opsize := S_B;
  3224. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3225. taicpu(hp3).loadconst(0, 0);
  3226. Result := True;
  3227. end;
  3228. else
  3229. InternalError(2021090702);
  3230. end;
  3231. end
  3232. else
  3233. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3234. DoOptimisation := False;
  3235. end;
  3236. hp2 := hp3;
  3237. end;
  3238. { Flags are still in use - don't optimise }
  3239. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3240. DoOptimisation := False;
  3241. end
  3242. else
  3243. DoOptimisation := False;
  3244. end;
  3245. if DoOptimisation then
  3246. begin
  3247. {$ifdef x86_64}
  3248. { OR only supports 32-bit sign-extended constants for 64-bit
  3249. instructions, so compensate for this if the constant is
  3250. encoded as a value greater than or equal to 2^31 }
  3251. if (taicpu(hp1).opsize = S_Q) and
  3252. (taicpu(hp1).oper[0]^.typ = top_const) and
  3253. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3254. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3255. {$endif x86_64}
  3256. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3257. taicpu(hp1).opcode := A_MOV;
  3258. RemoveCurrentP(p, hp1);
  3259. Result := True;
  3260. Exit;
  3261. end;
  3262. end;
  3263. { Next instruction is also a MOV ? }
  3264. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3265. begin
  3266. if MatchOpType(taicpu(p), top_const, top_ref) and
  3267. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3268. TryConstMerge(p, hp1) then
  3269. begin
  3270. Result := True;
  3271. { In case we have four byte writes in a row, check for 2 more
  3272. right now so we don't have to wait for another iteration of
  3273. pass 1
  3274. }
  3275. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3276. case taicpu(p).opsize of
  3277. S_W:
  3278. begin
  3279. if GetNextInstruction(p, hp1) and
  3280. MatchInstruction(hp1, A_MOV, [S_B]) and
  3281. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3282. GetNextInstruction(hp1, hp2) and
  3283. MatchInstruction(hp2, A_MOV, [S_B]) and
  3284. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3285. { Try to merge the two bytes }
  3286. TryConstMerge(hp1, hp2) then
  3287. { Now try to merge the two words (hp2 will get deleted) }
  3288. TryConstMerge(p, hp1);
  3289. end;
  3290. S_L:
  3291. begin
  3292. { Though this only really benefits x86_64 and not i386, it
  3293. gets a potential optimisation done faster and hence
  3294. reduces the number of times OptPass1MOV is entered }
  3295. if GetNextInstruction(p, hp1) and
  3296. MatchInstruction(hp1, A_MOV, [S_W]) and
  3297. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3298. GetNextInstruction(hp1, hp2) and
  3299. MatchInstruction(hp2, A_MOV, [S_W]) and
  3300. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3301. { Try to merge the two words }
  3302. TryConstMerge(hp1, hp2) then
  3303. { This will always fail on i386, so don't bother
  3304. calling it unless we're doing x86_64 }
  3305. {$ifdef x86_64}
  3306. { Now try to merge the two longwords (hp2 will get deleted) }
  3307. TryConstMerge(p, hp1)
  3308. {$endif x86_64}
  3309. ;
  3310. end;
  3311. else
  3312. ;
  3313. end;
  3314. Exit;
  3315. end;
  3316. if (taicpu(p).oper[1]^.typ = top_reg) and
  3317. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3318. begin
  3319. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3320. TransferUsedRegs(TmpUsedRegs);
  3321. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3322. { we have
  3323. mov x, %treg
  3324. mov %treg, y
  3325. }
  3326. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3327. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3328. { we've got
  3329. mov x, %treg
  3330. mov %treg, y
  3331. with %treg is not used after }
  3332. case taicpu(p).oper[0]^.typ Of
  3333. { top_reg is covered by DeepMOVOpt }
  3334. top_const:
  3335. begin
  3336. { change
  3337. mov const, %treg
  3338. mov %treg, y
  3339. to
  3340. mov const, y
  3341. }
  3342. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3343. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3344. begin
  3345. if taicpu(hp1).oper[1]^.typ=top_reg then
  3346. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3347. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3348. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3349. RemoveInstruction(hp1);
  3350. Result:=true;
  3351. Exit;
  3352. end;
  3353. end;
  3354. top_ref:
  3355. case taicpu(hp1).oper[1]^.typ of
  3356. top_reg:
  3357. begin
  3358. { change
  3359. mov mem, %treg
  3360. mov %treg, %reg
  3361. to
  3362. mov mem, %reg"
  3363. }
  3364. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3365. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3366. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3367. RemoveInstruction(hp1);
  3368. Result:=true;
  3369. Exit;
  3370. end;
  3371. top_ref:
  3372. begin
  3373. {$ifdef x86_64}
  3374. { Look for the following to simplify:
  3375. mov x(mem1), %reg
  3376. mov %reg, y(mem2)
  3377. mov x+8(mem1), %reg
  3378. mov %reg, y+8(mem2)
  3379. Change to:
  3380. movdqu x(mem1), %xmmreg
  3381. movdqu %xmmreg, y(mem2)
  3382. ...but only as long as the memory blocks don't overlap
  3383. }
  3384. SourceRef := taicpu(p).oper[0]^.ref^;
  3385. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3386. if (taicpu(p).opsize = S_Q) and
  3387. GetNextInstruction(hp1, hp2) and
  3388. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3389. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3390. begin
  3391. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3392. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3393. Inc(SourceRef.offset, 8);
  3394. if UseAVX then
  3395. begin
  3396. MovAligned := A_VMOVDQA;
  3397. MovUnaligned := A_VMOVDQU;
  3398. end
  3399. else
  3400. begin
  3401. MovAligned := A_MOVDQA;
  3402. MovUnaligned := A_MOVDQU;
  3403. end;
  3404. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3405. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3406. begin
  3407. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3408. Inc(TargetRef.offset, 8);
  3409. if GetNextInstruction(hp2, hp3) and
  3410. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3411. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3412. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3413. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3414. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3415. begin
  3416. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3417. if NewMMReg <> NR_NO then
  3418. begin
  3419. { Remember that the offsets are 8 ahead }
  3420. if ((SourceRef.offset mod 16) = 8) and
  3421. (
  3422. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3423. (SourceRef.base = current_procinfo.framepointer) or
  3424. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3425. ) then
  3426. taicpu(p).opcode := MovAligned
  3427. else
  3428. taicpu(p).opcode := MovUnaligned;
  3429. taicpu(p).opsize := S_XMM;
  3430. taicpu(p).oper[1]^.reg := NewMMReg;
  3431. if ((TargetRef.offset mod 16) = 8) and
  3432. (
  3433. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3434. (TargetRef.base = current_procinfo.framepointer) or
  3435. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3436. ) then
  3437. taicpu(hp1).opcode := MovAligned
  3438. else
  3439. taicpu(hp1).opcode := MovUnaligned;
  3440. taicpu(hp1).opsize := S_XMM;
  3441. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3442. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3443. RemoveInstruction(hp2);
  3444. RemoveInstruction(hp3);
  3445. Result := True;
  3446. Exit;
  3447. end;
  3448. end;
  3449. end
  3450. else
  3451. begin
  3452. { See if the next references are 8 less rather than 8 greater }
  3453. Dec(SourceRef.offset, 16); { -8 the other way }
  3454. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3455. begin
  3456. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3457. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3458. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3459. GetNextInstruction(hp2, hp3) and
  3460. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3461. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3462. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3463. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3464. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3465. begin
  3466. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3467. if NewMMReg <> NR_NO then
  3468. begin
  3469. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3470. if ((SourceRef.offset mod 16) = 0) and
  3471. (
  3472. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3473. (SourceRef.base = current_procinfo.framepointer) or
  3474. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3475. ) then
  3476. taicpu(hp2).opcode := MovAligned
  3477. else
  3478. taicpu(hp2).opcode := MovUnaligned;
  3479. taicpu(hp2).opsize := S_XMM;
  3480. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3481. if ((TargetRef.offset mod 16) = 0) and
  3482. (
  3483. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3484. (TargetRef.base = current_procinfo.framepointer) or
  3485. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3486. ) then
  3487. taicpu(hp3).opcode := MovAligned
  3488. else
  3489. taicpu(hp3).opcode := MovUnaligned;
  3490. taicpu(hp3).opsize := S_XMM;
  3491. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3492. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3493. RemoveInstruction(hp1);
  3494. RemoveCurrentP(p, hp2);
  3495. Result := True;
  3496. Exit;
  3497. end;
  3498. end;
  3499. end;
  3500. end;
  3501. end;
  3502. {$endif x86_64}
  3503. end;
  3504. else
  3505. { The write target should be a reg or a ref }
  3506. InternalError(2021091601);
  3507. end;
  3508. else
  3509. ;
  3510. end
  3511. else
  3512. { %treg is used afterwards, but all eventualities
  3513. other than the first MOV instruction being a constant
  3514. are covered by DeepMOVOpt, so only check for that }
  3515. if (taicpu(p).oper[0]^.typ = top_const) and
  3516. (
  3517. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3518. not (cs_opt_size in current_settings.optimizerswitches) or
  3519. (taicpu(hp1).opsize = S_B)
  3520. ) and
  3521. (
  3522. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3523. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3524. ) then
  3525. begin
  3526. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3527. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3528. end;
  3529. end;
  3530. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3531. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3532. { mov reg1, mem1 or mov mem1, reg1
  3533. mov mem2, reg2 mov reg2, mem2}
  3534. begin
  3535. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3536. { mov reg1, mem1 or mov mem1, reg1
  3537. mov mem2, reg1 mov reg2, mem1}
  3538. begin
  3539. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3540. { Removes the second statement from
  3541. mov reg1, mem1/reg2
  3542. mov mem1/reg2, reg1 }
  3543. begin
  3544. if taicpu(p).oper[0]^.typ=top_reg then
  3545. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3546. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3547. RemoveInstruction(hp1);
  3548. Result:=true;
  3549. exit;
  3550. end
  3551. else
  3552. begin
  3553. TransferUsedRegs(TmpUsedRegs);
  3554. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3555. if (taicpu(p).oper[1]^.typ = top_ref) and
  3556. { mov reg1, mem1
  3557. mov mem2, reg1 }
  3558. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3559. GetNextInstruction(hp1, hp2) and
  3560. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3561. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3562. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3563. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3564. { change to
  3565. mov reg1, mem1 mov reg1, mem1
  3566. mov mem2, reg1 cmp reg1, mem2
  3567. cmp mem1, reg1
  3568. }
  3569. begin
  3570. RemoveInstruction(hp2);
  3571. taicpu(hp1).opcode := A_CMP;
  3572. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3573. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3574. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3575. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3576. end;
  3577. end;
  3578. end
  3579. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3580. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3581. begin
  3582. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3583. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3584. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3585. end
  3586. else
  3587. begin
  3588. TransferUsedRegs(TmpUsedRegs);
  3589. if GetNextInstruction(hp1, hp2) and
  3590. MatchOpType(taicpu(p),top_ref,top_reg) and
  3591. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3592. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3593. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3594. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3595. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3596. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3597. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3598. { mov mem1, %reg1
  3599. mov %reg1, mem2
  3600. mov mem2, reg2
  3601. to:
  3602. mov mem1, reg2
  3603. mov reg2, mem2}
  3604. begin
  3605. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3606. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3607. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3608. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3609. RemoveInstruction(hp2);
  3610. Result := True;
  3611. end
  3612. {$ifdef i386}
  3613. { this is enabled for i386 only, as the rules to create the reg sets below
  3614. are too complicated for x86-64, so this makes this code too error prone
  3615. on x86-64
  3616. }
  3617. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3618. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3619. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3620. { mov mem1, reg1 mov mem1, reg1
  3621. mov reg1, mem2 mov reg1, mem2
  3622. mov mem2, reg2 mov mem2, reg1
  3623. to: to:
  3624. mov mem1, reg1 mov mem1, reg1
  3625. mov mem1, reg2 mov reg1, mem2
  3626. mov reg1, mem2
  3627. or (if mem1 depends on reg1
  3628. and/or if mem2 depends on reg2)
  3629. to:
  3630. mov mem1, reg1
  3631. mov reg1, mem2
  3632. mov reg1, reg2
  3633. }
  3634. begin
  3635. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3636. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3637. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3638. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3639. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3640. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3641. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3642. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3643. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3644. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3645. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3646. end
  3647. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3648. begin
  3649. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3650. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3651. end
  3652. else
  3653. begin
  3654. RemoveInstruction(hp2);
  3655. end
  3656. {$endif i386}
  3657. ;
  3658. end;
  3659. end
  3660. { movl [mem1],reg1
  3661. movl [mem1],reg2
  3662. to
  3663. movl [mem1],reg1
  3664. movl reg1,reg2
  3665. }
  3666. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3667. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3668. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3669. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3670. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3671. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3672. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3673. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3674. begin
  3675. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3676. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3677. end;
  3678. { movl const1,[mem1]
  3679. movl [mem1],reg1
  3680. to
  3681. movl const1,reg1
  3682. movl reg1,[mem1]
  3683. }
  3684. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3685. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3686. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3687. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3688. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3689. begin
  3690. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3691. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3692. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3693. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3694. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3695. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3696. Result:=true;
  3697. exit;
  3698. end;
  3699. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3700. { Change:
  3701. movl %reg1,%reg2
  3702. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3703. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3704. To:
  3705. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3706. movl x(%reg1),%reg1
  3707. movl %reg1,%regX
  3708. }
  3709. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3710. begin
  3711. p_SourceReg := taicpu(p).oper[0]^.reg;
  3712. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3713. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3714. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3715. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3716. GetNextInstruction(hp1, hp2) and
  3717. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3718. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3719. begin
  3720. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3721. if RegInRef(p_TargetReg, SourceRef) and
  3722. { If %reg1 also appears in the second reference, then it will
  3723. not refer to the same memory block as the first reference }
  3724. not RegInRef(p_SourceReg, SourceRef) then
  3725. begin
  3726. { Check to see if the references match if %reg2 is changed to %reg1 }
  3727. if SourceRef.base = p_TargetReg then
  3728. SourceRef.base := p_SourceReg;
  3729. if SourceRef.index = p_TargetReg then
  3730. SourceRef.index := p_SourceReg;
  3731. { RefsEqual also checks to ensure both references are non-volatile }
  3732. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3733. begin
  3734. taicpu(hp2).loadreg(0, p_SourceReg);
  3735. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3736. Result := True;
  3737. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3738. begin
  3739. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3740. RemoveCurrentP(p, hp1);
  3741. Exit;
  3742. end
  3743. else
  3744. begin
  3745. { Check to see if %reg2 is no longer in use }
  3746. TransferUsedRegs(TmpUsedRegs);
  3747. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3748. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3749. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3750. begin
  3751. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3752. RemoveCurrentP(p, hp1);
  3753. Exit;
  3754. end;
  3755. end;
  3756. { If we reach this point, p and hp1 weren't actually modified,
  3757. so we can do a bit more work on this pass }
  3758. end;
  3759. end;
  3760. end;
  3761. end;
  3762. end;
  3763. {$ifdef x86_64}
  3764. { Change:
  3765. movl %reg1l,%reg2l
  3766. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3767. To:
  3768. movl %reg1l,%reg2l
  3769. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3770. If %reg1 = %reg3, convert to:
  3771. movl %reg1l,%reg2l
  3772. andl %reg1l,%reg1l
  3773. }
  3774. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3775. MatchOpType(taicpu(p), top_reg, top_reg) and
  3776. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3777. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3778. begin
  3779. TransferUsedRegs(TmpUsedRegs);
  3780. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3781. taicpu(hp1).opsize := S_L;
  3782. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3783. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3784. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3785. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3786. begin
  3787. { %reg1 = %reg3 }
  3788. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3789. taicpu(hp1).opcode := A_AND;
  3790. end
  3791. else
  3792. begin
  3793. { %reg1 <> %reg3 }
  3794. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3795. end;
  3796. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3797. begin
  3798. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3799. RemoveCurrentP(p, hp1);
  3800. Result := True;
  3801. Exit;
  3802. end
  3803. else
  3804. begin
  3805. { Initial instruction wasn't actually changed }
  3806. Include(OptsToCheck, aoc_ForceNewIteration);
  3807. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3808. appears below since %reg1 has technically changed }
  3809. if taicpu(hp1).opcode = A_AND then
  3810. Exit;
  3811. end;
  3812. end;
  3813. {$endif x86_64}
  3814. { search further than the next instruction for a mov (as long as it's not a jump) }
  3815. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3816. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3817. (taicpu(p).oper[1]^.typ = top_reg) and
  3818. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3819. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3820. begin
  3821. { we work with hp2 here, so hp1 can be still used later on when
  3822. checking for GetNextInstruction_p }
  3823. hp3 := hp1;
  3824. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3825. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3826. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3827. TransferUsedRegs(TmpUsedRegs);
  3828. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3829. if NotFirstIteration then
  3830. JumpTracking := TLinkedList.Create
  3831. else
  3832. JumpTracking := nil;
  3833. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3834. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3835. (hp2.typ=ait_instruction) do
  3836. begin
  3837. case taicpu(hp2).opcode of
  3838. A_POP:
  3839. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3840. begin
  3841. if not CrossJump and
  3842. not RegUsedBetween(p_TargetReg, p, hp2) then
  3843. begin
  3844. { We can remove the original MOV since the register
  3845. wasn't used between it and its popping from the stack }
  3846. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3847. RemoveCurrentp(p, hp1);
  3848. Result := True;
  3849. JumpTracking.Free;
  3850. Exit;
  3851. end;
  3852. { Can't go any further }
  3853. Break;
  3854. end;
  3855. A_MOV:
  3856. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3857. ((taicpu(p).oper[0]^.typ=top_const) or
  3858. ((taicpu(p).oper[0]^.typ=top_reg) and
  3859. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3860. )
  3861. ) then
  3862. begin
  3863. { we have
  3864. mov x, %treg
  3865. mov %treg, y
  3866. }
  3867. { We don't need to call UpdateUsedRegs for every instruction between
  3868. p and hp2 because the register we're concerned about will not
  3869. become deallocated (otherwise GetNextInstructionUsingReg would
  3870. have stopped at an earlier instruction). [Kit] }
  3871. TempRegUsed :=
  3872. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3873. RegReadByInstruction(p_TargetReg, hp3) or
  3874. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3875. case taicpu(p).oper[0]^.typ Of
  3876. top_reg:
  3877. begin
  3878. { change
  3879. mov %reg, %treg
  3880. mov %treg, y
  3881. to
  3882. mov %reg, y
  3883. }
  3884. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3885. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3886. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3887. begin
  3888. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3889. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3890. if TempRegUsed then
  3891. begin
  3892. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3893. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3894. { Set the start of the next GetNextInstructionUsingRegCond search
  3895. to start at the entry right before hp2 (which is about to be removed) }
  3896. hp3 := tai(hp2.Previous);
  3897. RemoveInstruction(hp2);
  3898. Include(OptsToCheck, aoc_ForceNewIteration);
  3899. { See if there's more we can optimise }
  3900. Continue;
  3901. end
  3902. else
  3903. begin
  3904. RemoveInstruction(hp2);
  3905. { We can remove the original MOV too }
  3906. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3907. RemoveCurrentP(p, hp1);
  3908. Result:=true;
  3909. JumpTracking.Free;
  3910. Exit;
  3911. end;
  3912. end
  3913. else
  3914. begin
  3915. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3916. taicpu(hp2).loadReg(0, p_SourceReg);
  3917. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3918. { Check to see if the register also appears in the reference }
  3919. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3920. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3921. { Don't remove the first instruction if the temporary register is in use }
  3922. if not TempRegUsed and
  3923. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3924. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3925. begin
  3926. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3927. RemoveCurrentP(p, hp1);
  3928. Result:=true;
  3929. JumpTracking.Free;
  3930. Exit;
  3931. end;
  3932. { No need to set Result to True here. If there's another instruction later
  3933. on that can be optimised, it will be detected when the main Pass 1 loop
  3934. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3935. end;
  3936. end;
  3937. top_const:
  3938. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3939. begin
  3940. { change
  3941. mov const, %treg
  3942. mov %treg, y
  3943. to
  3944. mov const, y
  3945. }
  3946. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3947. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3948. begin
  3949. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3950. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3951. if TempRegUsed then
  3952. begin
  3953. { Don't remove the first instruction if the temporary register is in use }
  3954. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3955. { No need to set Result to True. If there's another instruction later on
  3956. that can be optimised, it will be detected when the main Pass 1 loop
  3957. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3958. end
  3959. else
  3960. begin
  3961. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3962. RemoveCurrentP(p, hp1);
  3963. Result:=true;
  3964. Exit;
  3965. end;
  3966. end;
  3967. end;
  3968. else
  3969. Internalerror(2019103001);
  3970. end;
  3971. end
  3972. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3973. begin
  3974. if not CrossJump and
  3975. not RegUsedBetween(p_TargetReg, p, hp2) and
  3976. not RegReadByInstruction(p_TargetReg, hp2) then
  3977. begin
  3978. { Register is not used before it is overwritten }
  3979. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3980. RemoveCurrentp(p, hp1);
  3981. Result := True;
  3982. Exit;
  3983. end;
  3984. if (taicpu(p).oper[0]^.typ = top_const) and
  3985. (taicpu(hp2).oper[0]^.typ = top_const) then
  3986. begin
  3987. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3988. begin
  3989. { Same value - register hasn't changed }
  3990. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3991. RemoveInstruction(hp2);
  3992. Include(OptsToCheck, aoc_ForceNewIteration);
  3993. { See if there's more we can optimise }
  3994. Continue;
  3995. end;
  3996. end;
  3997. {$ifdef x86_64}
  3998. end
  3999. { Change:
  4000. movl %reg1l,%reg2l
  4001. ...
  4002. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4003. To:
  4004. movl %reg1l,%reg2l
  4005. ...
  4006. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4007. If %reg1 = %reg3, convert to:
  4008. movl %reg1l,%reg2l
  4009. ...
  4010. andl %reg1l,%reg1l
  4011. }
  4012. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4013. (taicpu(p).oper[0]^.typ = top_reg) and
  4014. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4015. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4016. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4017. begin
  4018. TempRegUsed :=
  4019. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4020. RegReadByInstruction(p_TargetReg, hp3) or
  4021. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4022. taicpu(hp2).opsize := S_L;
  4023. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4024. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4025. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4026. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4027. begin
  4028. { %reg1 = %reg3 }
  4029. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4030. taicpu(hp2).opcode := A_AND;
  4031. end
  4032. else
  4033. begin
  4034. { %reg1 <> %reg3 }
  4035. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4036. end;
  4037. if not TempRegUsed then
  4038. begin
  4039. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4040. RemoveCurrentP(p, hp1);
  4041. Result := True;
  4042. Exit;
  4043. end
  4044. else
  4045. begin
  4046. { Initial instruction wasn't actually changed }
  4047. Include(OptsToCheck, aoc_ForceNewIteration);
  4048. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4049. appears below since %reg1 has technically changed }
  4050. if taicpu(hp2).opcode = A_AND then
  4051. Break;
  4052. end;
  4053. {$endif x86_64}
  4054. end;
  4055. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4056. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4057. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4058. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4059. begin
  4060. {
  4061. Change from:
  4062. mov ###, %reg
  4063. ...
  4064. movs/z %reg,%reg (Same register, just different sizes)
  4065. To:
  4066. movs/z ###, %reg (Longer version)
  4067. ...
  4068. (remove)
  4069. }
  4070. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4071. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4072. { Keep the first instruction as mov if ### is a constant }
  4073. if taicpu(p).oper[0]^.typ = top_const then
  4074. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4075. else
  4076. begin
  4077. taicpu(p).opcode := taicpu(hp2).opcode;
  4078. taicpu(p).opsize := taicpu(hp2).opsize;
  4079. end;
  4080. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4081. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4082. RemoveInstruction(hp2);
  4083. Result := True;
  4084. JumpTracking.Free;
  4085. Exit;
  4086. end;
  4087. else
  4088. { Move down to the if-block below };
  4089. end;
  4090. { Also catches MOV/S/Z instructions that aren't modified }
  4091. if taicpu(p).oper[0]^.typ = top_reg then
  4092. begin
  4093. p_SourceReg := taicpu(p).oper[0]^.reg;
  4094. if
  4095. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4096. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4097. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4098. begin
  4099. Result := True;
  4100. { Just in case something didn't get modified (e.g. an
  4101. implicit register). Also, if it does read from this
  4102. register, then there's no longer an advantage to
  4103. changing the register on subsequent instructions.}
  4104. if not RegReadByInstruction(p_TargetReg, hp2) then
  4105. begin
  4106. { If a conditional jump was crossed, do not delete
  4107. the original MOV no matter what }
  4108. if not CrossJump and
  4109. { RegEndOfLife returns True if the register is
  4110. deallocated before the next instruction or has
  4111. been loaded with a new value }
  4112. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4113. begin
  4114. { We can remove the original MOV }
  4115. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4116. RemoveCurrentp(p, hp1);
  4117. JumpTracking.Free;
  4118. Result := True;
  4119. Exit;
  4120. end;
  4121. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4122. begin
  4123. { See if there's more we can optimise }
  4124. hp3 := hp2;
  4125. Continue;
  4126. end;
  4127. end;
  4128. end;
  4129. end;
  4130. { Break out of the while loop under normal circumstances }
  4131. Break;
  4132. end;
  4133. JumpTracking.Free;
  4134. end;
  4135. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4136. (taicpu(p).oper[1]^.typ = top_reg) and
  4137. (taicpu(p).opsize = S_L) and
  4138. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4139. (hp2.typ = ait_instruction) and
  4140. (taicpu(hp2).opcode = A_AND) and
  4141. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4142. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4143. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4144. ) then
  4145. begin
  4146. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4147. begin
  4148. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4149. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4150. begin
  4151. { Optimize out:
  4152. mov x, %reg
  4153. and ffffffffh, %reg
  4154. }
  4155. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4156. RemoveInstruction(hp2);
  4157. Result:=true;
  4158. exit;
  4159. end;
  4160. end;
  4161. end;
  4162. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4163. x >= RetOffset) as it doesn't do anything (it writes either to a
  4164. parameter or to the temporary storage room for the function
  4165. result)
  4166. }
  4167. if IsExitCode(hp1) and
  4168. (taicpu(p).oper[1]^.typ = top_ref) and
  4169. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4170. (
  4171. (
  4172. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4173. not (
  4174. assigned(current_procinfo.procdef.funcretsym) and
  4175. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4176. )
  4177. ) or
  4178. { Also discard writes to the stack that are below the base pointer,
  4179. as this is temporary storage rather than a function result on the
  4180. stack, say. }
  4181. (
  4182. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4183. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4184. )
  4185. ) then
  4186. begin
  4187. RemoveCurrentp(p, hp1);
  4188. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4189. RemoveLastDeallocForFuncRes(p);
  4190. Result:=true;
  4191. exit;
  4192. end;
  4193. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4194. begin
  4195. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4196. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4197. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4198. begin
  4199. { change
  4200. mov reg1, mem1
  4201. test/cmp x, mem1
  4202. to
  4203. mov reg1, mem1
  4204. test/cmp x, reg1
  4205. }
  4206. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4207. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4208. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4209. Result := True;
  4210. Exit;
  4211. end;
  4212. if DoMovCmpMemOpt(p, hp1, True) then
  4213. begin
  4214. Result := True;
  4215. Exit;
  4216. end;
  4217. end;
  4218. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4219. { If the flags register is in use, don't change the instruction to an
  4220. ADD otherwise this will scramble the flags. [Kit] }
  4221. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4222. begin
  4223. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4224. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4225. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4226. ) or
  4227. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4228. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4229. )
  4230. ) then
  4231. { mov reg1,ref
  4232. lea reg2,[reg1,reg2]
  4233. to
  4234. add reg2,ref}
  4235. begin
  4236. TransferUsedRegs(TmpUsedRegs);
  4237. { reg1 may not be used afterwards }
  4238. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4239. begin
  4240. Taicpu(hp1).opcode:=A_ADD;
  4241. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4242. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4243. RemoveCurrentp(p, hp1);
  4244. result:=true;
  4245. exit;
  4246. end;
  4247. end;
  4248. { If the LEA instruction can be converted into an arithmetic instruction,
  4249. it may be possible to then fold it in the next optimisation, otherwise
  4250. there's nothing more that can be optimised here. }
  4251. if not ConvertLEA(taicpu(hp1)) then
  4252. Exit;
  4253. end;
  4254. if (taicpu(p).oper[1]^.typ = top_reg) and
  4255. (hp1.typ = ait_instruction) and
  4256. GetNextInstruction(hp1, hp2) and
  4257. MatchInstruction(hp2,A_MOV,[]) and
  4258. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4259. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4260. (
  4261. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4262. {$ifdef x86_64}
  4263. or
  4264. (
  4265. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4266. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4267. )
  4268. {$endif x86_64}
  4269. ) then
  4270. begin
  4271. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4272. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4273. { change movsX/movzX reg/ref, reg2
  4274. add/sub/or/... reg3/$const, reg2
  4275. mov reg2 reg/ref
  4276. dealloc reg2
  4277. to
  4278. add/sub/or/... reg3/$const, reg/ref }
  4279. begin
  4280. TransferUsedRegs(TmpUsedRegs);
  4281. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4282. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4283. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4284. begin
  4285. { by example:
  4286. movswl %si,%eax movswl %si,%eax p
  4287. decl %eax addl %edx,%eax hp1
  4288. movw %ax,%si movw %ax,%si hp2
  4289. ->
  4290. movswl %si,%eax movswl %si,%eax p
  4291. decw %eax addw %edx,%eax hp1
  4292. movw %ax,%si movw %ax,%si hp2
  4293. }
  4294. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4295. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4296. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4297. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4298. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4299. {
  4300. ->
  4301. movswl %si,%eax movswl %si,%eax p
  4302. decw %si addw %dx,%si hp1
  4303. movw %ax,%si movw %ax,%si hp2
  4304. }
  4305. case taicpu(hp1).ops of
  4306. 1:
  4307. begin
  4308. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4309. if taicpu(hp1).oper[0]^.typ=top_reg then
  4310. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4311. end;
  4312. 2:
  4313. begin
  4314. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4315. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4316. (taicpu(hp1).opcode<>A_SHL) and
  4317. (taicpu(hp1).opcode<>A_SHR) and
  4318. (taicpu(hp1).opcode<>A_SAR) then
  4319. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4320. end;
  4321. else
  4322. internalerror(2008042701);
  4323. end;
  4324. {
  4325. ->
  4326. decw %si addw %dx,%si p
  4327. }
  4328. RemoveInstruction(hp2);
  4329. RemoveCurrentP(p, hp1);
  4330. Result:=True;
  4331. Exit;
  4332. end;
  4333. end;
  4334. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4335. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4336. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4337. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4338. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4339. )
  4340. {$ifdef i386}
  4341. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4342. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4343. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4344. {$endif i386}
  4345. then
  4346. { change movsX/movzX reg/ref, reg2
  4347. add/sub/or/... regX/$const, reg2
  4348. mov reg2, reg3
  4349. dealloc reg2
  4350. to
  4351. movsX/movzX reg/ref, reg3
  4352. add/sub/or/... reg3/$const, reg3
  4353. }
  4354. begin
  4355. TransferUsedRegs(TmpUsedRegs);
  4356. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4357. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4358. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4359. begin
  4360. { by example:
  4361. movswl %si,%eax movswl %si,%eax p
  4362. decl %eax addl %edx,%eax hp1
  4363. movw %ax,%si movw %ax,%si hp2
  4364. ->
  4365. movswl %si,%eax movswl %si,%eax p
  4366. decw %eax addw %edx,%eax hp1
  4367. movw %ax,%si movw %ax,%si hp2
  4368. }
  4369. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4370. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4371. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4372. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4373. { limit size of constants as well to avoid assembler errors, but
  4374. check opsize to avoid overflow when left shifting the 1 }
  4375. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4376. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4377. {$ifdef x86_64}
  4378. { Be careful of, for example:
  4379. movl %reg1,%reg2
  4380. addl %reg3,%reg2
  4381. movq %reg2,%reg4
  4382. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4383. }
  4384. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4385. begin
  4386. taicpu(hp2).changeopsize(S_L);
  4387. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4388. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4389. end;
  4390. {$endif x86_64}
  4391. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4392. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4393. if taicpu(p).oper[0]^.typ=top_reg then
  4394. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4395. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4396. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4397. {
  4398. ->
  4399. movswl %si,%eax movswl %si,%eax p
  4400. decw %si addw %dx,%si hp1
  4401. movw %ax,%si movw %ax,%si hp2
  4402. }
  4403. case taicpu(hp1).ops of
  4404. 1:
  4405. begin
  4406. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4407. if taicpu(hp1).oper[0]^.typ=top_reg then
  4408. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4409. end;
  4410. 2:
  4411. begin
  4412. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4413. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4414. (taicpu(hp1).opcode<>A_SHL) and
  4415. (taicpu(hp1).opcode<>A_SHR) and
  4416. (taicpu(hp1).opcode<>A_SAR) then
  4417. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4418. end;
  4419. else
  4420. internalerror(2018111801);
  4421. end;
  4422. {
  4423. ->
  4424. decw %si addw %dx,%si p
  4425. }
  4426. RemoveInstruction(hp2);
  4427. end;
  4428. end;
  4429. end;
  4430. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4431. GetNextInstruction(hp1, hp2) and
  4432. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4433. MatchOperand(Taicpu(p).oper[0]^,0) and
  4434. (Taicpu(p).oper[1]^.typ = top_reg) and
  4435. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4436. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4437. { mov reg1,0
  4438. bts reg1,operand1 --> mov reg1,operand2
  4439. or reg1,operand2 bts reg1,operand1}
  4440. begin
  4441. Taicpu(hp2).opcode:=A_MOV;
  4442. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4443. asml.remove(hp1);
  4444. insertllitem(hp2,hp2.next,hp1);
  4445. RemoveCurrentp(p, hp1);
  4446. Result:=true;
  4447. exit;
  4448. end;
  4449. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4450. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4451. GetNextInstruction(hp1, hp2) and
  4452. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4453. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4454. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4455. { change
  4456. mov reg1,reg2
  4457. sub reg3,reg2
  4458. cmp reg3,reg1
  4459. into
  4460. mov reg1,reg2
  4461. sub reg3,reg2
  4462. }
  4463. begin
  4464. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4465. RemoveInstruction(hp2);
  4466. Result:=true;
  4467. exit;
  4468. end;
  4469. {
  4470. mov ref,reg0
  4471. <op> reg0,reg1
  4472. dealloc reg0
  4473. to
  4474. <op> ref,reg1
  4475. }
  4476. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4477. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4478. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4479. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4480. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4481. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4482. begin
  4483. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4484. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4485. RemoveCurrentp(p, hp1);
  4486. Result:=true;
  4487. exit;
  4488. end;
  4489. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4490. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4491. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4492. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4493. begin
  4494. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4495. {$ifdef x86_64}
  4496. { Convert:
  4497. movq x(ref),%reg64
  4498. shrq y,%reg64
  4499. To:
  4500. movl x+4(ref),%reg32
  4501. shrl y-32,%reg32 (Remove if y = 32)
  4502. }
  4503. if (taicpu(p).opsize = S_Q) and
  4504. (taicpu(hp1).opcode = A_SHR) and
  4505. (taicpu(hp1).oper[0]^.val >= 32) then
  4506. begin
  4507. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4508. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4509. { Convert to 32-bit }
  4510. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4511. taicpu(p).opsize := S_L;
  4512. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4513. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4514. if (taicpu(hp1).oper[0]^.val = 32) then
  4515. begin
  4516. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4517. RemoveInstruction(hp1);
  4518. end
  4519. else
  4520. begin
  4521. { This will potentially open up more arithmetic operations since
  4522. the peephole optimizer now has a big hint that only the lower
  4523. 32 bits are currently in use (and opcodes are smaller in size) }
  4524. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4525. taicpu(hp1).opsize := S_L;
  4526. Dec(taicpu(hp1).oper[0]^.val, 32);
  4527. DebugMsg(SPeepholeOptimization + PreMessage +
  4528. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4529. end;
  4530. Result := True;
  4531. Exit;
  4532. end;
  4533. {$endif x86_64}
  4534. { Convert:
  4535. movl x(ref),%reg
  4536. shrl $24,%reg
  4537. To:
  4538. movzbl x+3(ref),%reg
  4539. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4540. Also accept sar instead of shr, but convert to movsx instead of movzx
  4541. }
  4542. if taicpu(hp1).opcode = A_SHR then
  4543. MovUnaligned := A_MOVZX
  4544. else
  4545. MovUnaligned := A_MOVSX;
  4546. NewSize := S_NO;
  4547. NewOffset := 0;
  4548. case taicpu(p).opsize of
  4549. S_B:
  4550. { No valid combinations };
  4551. S_W:
  4552. if (taicpu(hp1).oper[0]^.val = 8) then
  4553. begin
  4554. NewSize := S_BW;
  4555. NewOffset := 1;
  4556. end;
  4557. S_L:
  4558. case taicpu(hp1).oper[0]^.val of
  4559. 16:
  4560. begin
  4561. NewSize := S_WL;
  4562. NewOffset := 2;
  4563. end;
  4564. 24:
  4565. begin
  4566. NewSize := S_BL;
  4567. NewOffset := 3;
  4568. end;
  4569. else
  4570. ;
  4571. end;
  4572. {$ifdef x86_64}
  4573. S_Q:
  4574. case taicpu(hp1).oper[0]^.val of
  4575. 32:
  4576. begin
  4577. if taicpu(hp1).opcode = A_SAR then
  4578. begin
  4579. { 32-bit to 64-bit is a distinct instruction }
  4580. MovUnaligned := A_MOVSXD;
  4581. NewSize := S_LQ;
  4582. NewOffset := 4;
  4583. end
  4584. else
  4585. { Should have been handled by MovShr2Mov above }
  4586. InternalError(2022081811);
  4587. end;
  4588. 48:
  4589. begin
  4590. NewSize := S_WQ;
  4591. NewOffset := 6;
  4592. end;
  4593. 56:
  4594. begin
  4595. NewSize := S_BQ;
  4596. NewOffset := 7;
  4597. end;
  4598. else
  4599. ;
  4600. end;
  4601. {$endif x86_64}
  4602. else
  4603. InternalError(2022081810);
  4604. end;
  4605. if (NewSize <> S_NO) and
  4606. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4607. begin
  4608. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4609. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4610. debug_op2str(MovUnaligned);
  4611. {$ifdef x86_64}
  4612. if MovUnaligned <> A_MOVSXD then
  4613. { Don't add size suffix for MOVSXD }
  4614. {$endif x86_64}
  4615. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4616. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4617. taicpu(p).opcode := MovUnaligned;
  4618. taicpu(p).opsize := NewSize;
  4619. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4620. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4621. RemoveInstruction(hp1);
  4622. Result := True;
  4623. Exit;
  4624. end;
  4625. end;
  4626. { Backward optimisation shared with OptPass2MOV }
  4627. if FuncMov2Func(p, hp1) then
  4628. begin
  4629. Result := True;
  4630. Exit;
  4631. end;
  4632. end;
  4633. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4634. var
  4635. hp1 : tai;
  4636. begin
  4637. Result:=false;
  4638. if taicpu(p).ops <> 2 then
  4639. exit;
  4640. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4641. GetNextInstruction(p,hp1) then
  4642. begin
  4643. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4644. (taicpu(hp1).ops = 2) then
  4645. begin
  4646. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4647. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4648. { movXX reg1, mem1 or movXX mem1, reg1
  4649. movXX mem2, reg2 movXX reg2, mem2}
  4650. begin
  4651. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4652. { movXX reg1, mem1 or movXX mem1, reg1
  4653. movXX mem2, reg1 movXX reg2, mem1}
  4654. begin
  4655. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4656. begin
  4657. { Removes the second statement from
  4658. movXX reg1, mem1/reg2
  4659. movXX mem1/reg2, reg1
  4660. }
  4661. if taicpu(p).oper[0]^.typ=top_reg then
  4662. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4663. { Removes the second statement from
  4664. movXX mem1/reg1, reg2
  4665. movXX reg2, mem1/reg1
  4666. }
  4667. if (taicpu(p).oper[1]^.typ=top_reg) and
  4668. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4669. begin
  4670. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4671. RemoveInstruction(hp1);
  4672. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4673. Result:=true;
  4674. exit;
  4675. end
  4676. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4677. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4678. begin
  4679. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4680. RemoveInstruction(hp1);
  4681. Result:=true;
  4682. exit;
  4683. end;
  4684. end
  4685. end;
  4686. end;
  4687. end;
  4688. end;
  4689. end;
  4690. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4691. var
  4692. hp1 : tai;
  4693. begin
  4694. result:=false;
  4695. { replace
  4696. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4697. MovX %mreg2,%mreg1
  4698. dealloc %mreg2
  4699. by
  4700. <Op>X %mreg2,%mreg1
  4701. ?
  4702. }
  4703. if GetNextInstruction(p,hp1) and
  4704. { we mix single and double opperations here because we assume that the compiler
  4705. generates vmovapd only after double operations and vmovaps only after single operations }
  4706. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4707. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4708. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4709. (taicpu(p).oper[0]^.typ=top_reg) then
  4710. begin
  4711. TransferUsedRegs(TmpUsedRegs);
  4712. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4713. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4714. begin
  4715. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4716. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4717. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4718. RemoveInstruction(hp1);
  4719. result:=true;
  4720. end;
  4721. end;
  4722. end;
  4723. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4724. var
  4725. hp1, p_label, p_dist, hp1_dist: tai;
  4726. JumpLabel, JumpLabel_dist: TAsmLabel;
  4727. FirstValue, SecondValue: TCGInt;
  4728. TempBool: Boolean;
  4729. begin
  4730. Result := False;
  4731. if (taicpu(p).oper[0]^.typ = top_const) and
  4732. (taicpu(p).oper[0]^.val <> -1) then
  4733. begin
  4734. { Convert unsigned maximum constants to -1 to aid optimisation }
  4735. case taicpu(p).opsize of
  4736. S_B:
  4737. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4738. begin
  4739. taicpu(p).oper[0]^.val := -1;
  4740. Result := True;
  4741. Exit;
  4742. end;
  4743. S_W:
  4744. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4745. begin
  4746. taicpu(p).oper[0]^.val := -1;
  4747. Result := True;
  4748. Exit;
  4749. end;
  4750. S_L:
  4751. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4752. begin
  4753. taicpu(p).oper[0]^.val := -1;
  4754. Result := True;
  4755. Exit;
  4756. end;
  4757. {$ifdef x86_64}
  4758. S_Q:
  4759. { Storing anything greater than $7FFFFFFF is not possible so do
  4760. nothing };
  4761. {$endif x86_64}
  4762. else
  4763. InternalError(2021121001);
  4764. end;
  4765. end;
  4766. if GetNextInstruction(p, hp1) and
  4767. TrySwapMovCmp(p, hp1) then
  4768. begin
  4769. Result := True;
  4770. Exit;
  4771. end;
  4772. if MatchInstruction(hp1, A_Jcc, []) then
  4773. begin
  4774. TempBool := True;
  4775. if DoJumpOptimizations(hp1, TempBool) or
  4776. not TempBool then
  4777. begin
  4778. Result := True;
  4779. if Assigned(hp1) then
  4780. begin
  4781. if (hp1.typ in [ait_align]) then
  4782. SkipAligns(hp1, hp1);
  4783. { CollapseZeroDistJump will be set to the label after the
  4784. jump if it optimises, whether or not it's live or dead }
  4785. if (hp1.typ in [ait_label]) and
  4786. not (tai_label(hp1).labsym.is_used) then
  4787. GetNextInstruction(hp1, hp1);
  4788. end;
  4789. TransferUsedRegs(TmpUsedRegs);
  4790. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4791. if not Assigned(hp1) or
  4792. (
  4793. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4794. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4795. ) then
  4796. begin
  4797. { No more conditional jumps; conditional statement is no longer required }
  4798. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4799. RemoveCurrentP(p);
  4800. end;
  4801. Exit;
  4802. end;
  4803. end;
  4804. { Search for:
  4805. test $x,(reg/ref)
  4806. jne @lbl1
  4807. test $y,(reg/ref) (same register or reference)
  4808. jne @lbl1
  4809. Change to:
  4810. test $(x or y),(reg/ref)
  4811. jne @lbl1
  4812. (Note, this doesn't work with je instead of jne)
  4813. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4814. Also search for:
  4815. test $x,(reg/ref)
  4816. je @lbl1
  4817. test $y,(reg/ref)
  4818. je/jne @lbl2
  4819. If (x or y) = x, then the second jump is deterministic
  4820. }
  4821. if (
  4822. (
  4823. (taicpu(p).oper[0]^.typ = top_const) or
  4824. (
  4825. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4826. (taicpu(p).oper[0]^.typ = top_reg) and
  4827. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4828. )
  4829. ) and
  4830. MatchInstruction(hp1, A_JCC, [])
  4831. ) then
  4832. begin
  4833. if (taicpu(p).oper[0]^.typ = top_reg) and
  4834. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4835. FirstValue := -1
  4836. else
  4837. FirstValue := taicpu(p).oper[0]^.val;
  4838. { If we have several test/jne's in a row, it might be the case that
  4839. the second label doesn't go to the same location, but the one
  4840. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4841. so accommodate for this with a while loop.
  4842. }
  4843. hp1_dist := hp1;
  4844. if GetNextInstruction(hp1, p_dist) and
  4845. (p_dist.typ = ait_instruction) and
  4846. (
  4847. (
  4848. (taicpu(p_dist).opcode = A_TEST) and
  4849. (
  4850. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4851. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4852. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4853. )
  4854. ) or
  4855. (
  4856. { cmp 0,%reg = test %reg,%reg }
  4857. (taicpu(p_dist).opcode = A_CMP) and
  4858. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4859. )
  4860. ) and
  4861. { Make sure the destination operands are actually the same }
  4862. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4863. GetNextInstruction(p_dist, hp1_dist) and
  4864. MatchInstruction(hp1_dist, A_JCC, []) then
  4865. begin
  4866. if
  4867. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4868. (
  4869. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4870. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4871. ) then
  4872. SecondValue := -1
  4873. else
  4874. SecondValue := taicpu(p_dist).oper[0]^.val;
  4875. { If both of the TEST constants are identical, delete the second
  4876. TEST that is unnecessary. }
  4877. if (FirstValue = SecondValue) then
  4878. begin
  4879. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4880. RemoveInstruction(p_dist);
  4881. { Don't let the flags register become deallocated and reallocated between the jumps }
  4882. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4883. Result := True;
  4884. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4885. begin
  4886. { Since the second jump's condition is a subset of the first, we
  4887. know it will never branch because the first jump dominates it.
  4888. Get it out of the way now rather than wait for the jump
  4889. optimisations for a speed boost. }
  4890. if IsJumpToLabel(taicpu(hp1_dist)) then
  4891. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4892. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4893. RemoveInstruction(hp1_dist);
  4894. end
  4895. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4896. begin
  4897. { If the inverse of the first condition is a subset of the second,
  4898. the second one will definitely branch if the first one doesn't }
  4899. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4900. MakeUnconditional(taicpu(hp1_dist));
  4901. RemoveDeadCodeAfterJump(hp1_dist);
  4902. end;
  4903. Exit;
  4904. end;
  4905. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4906. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4907. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4908. then the second jump will never branch, so it can also be
  4909. removed regardless of where it goes }
  4910. (
  4911. (FirstValue = -1) or
  4912. (SecondValue = -1) or
  4913. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4914. ) then
  4915. begin
  4916. { Same jump location... can be a register since nothing's changed }
  4917. { If any of the entries are equivalent to test %reg,%reg, then the
  4918. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4919. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4920. if IsJumpToLabel(taicpu(hp1_dist)) then
  4921. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4922. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4923. RemoveInstruction(hp1_dist);
  4924. { Only remove the second test if no jumps or other conditional instructions follow }
  4925. TransferUsedRegs(TmpUsedRegs);
  4926. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4927. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4928. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4929. RemoveInstruction(p_dist);
  4930. Result := True;
  4931. Exit;
  4932. end;
  4933. end;
  4934. end;
  4935. { Search for:
  4936. test %reg,%reg
  4937. j(c1) @lbl1
  4938. ...
  4939. @lbl:
  4940. test %reg,%reg (same register)
  4941. j(c2) @lbl2
  4942. If c2 is a subset of c1, change to:
  4943. test %reg,%reg
  4944. j(c1) @lbl2
  4945. (@lbl1 may become a dead label as a result)
  4946. }
  4947. if (taicpu(p).oper[1]^.typ = top_reg) and
  4948. (taicpu(p).oper[0]^.typ = top_reg) and
  4949. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4950. MatchInstruction(hp1, A_JCC, []) and
  4951. IsJumpToLabel(taicpu(hp1)) then
  4952. begin
  4953. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4954. p_label := nil;
  4955. if Assigned(JumpLabel) then
  4956. p_label := getlabelwithsym(JumpLabel);
  4957. if Assigned(p_label) and
  4958. GetNextInstruction(p_label, p_dist) and
  4959. MatchInstruction(p_dist, A_TEST, []) and
  4960. { It's fine if the second test uses smaller sub-registers }
  4961. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4962. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4963. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4964. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4965. GetNextInstruction(p_dist, hp1_dist) and
  4966. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4967. begin
  4968. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4969. if JumpLabel = JumpLabel_dist then
  4970. { This is an infinite loop }
  4971. Exit;
  4972. { Best optimisation when the first condition is a subset (or equal) of the second }
  4973. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4974. begin
  4975. { Any registers used here will already be allocated }
  4976. if Assigned(JumpLabel) then
  4977. JumpLabel.DecRefs;
  4978. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4979. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4980. Result := True;
  4981. Exit;
  4982. end;
  4983. end;
  4984. end;
  4985. end;
  4986. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4987. var
  4988. hp1, hp2: tai;
  4989. ActiveReg: TRegister;
  4990. OldOffset: asizeint;
  4991. ThisConst: TCGInt;
  4992. function RegDeallocated: Boolean;
  4993. begin
  4994. TransferUsedRegs(TmpUsedRegs);
  4995. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4996. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4997. end;
  4998. begin
  4999. result:=false;
  5000. hp1 := nil;
  5001. { replace
  5002. addX const,%reg1
  5003. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5004. dealloc %reg1
  5005. by
  5006. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5007. }
  5008. if MatchOpType(taicpu(p),top_const,top_reg) then
  5009. begin
  5010. ActiveReg := taicpu(p).oper[1]^.reg;
  5011. { Ensures the entire register was updated }
  5012. if (taicpu(p).opsize >= S_L) and
  5013. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5014. MatchInstruction(hp1,A_LEA,[]) and
  5015. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5016. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5017. (
  5018. { Cover the case where the register in the reference is also the destination register }
  5019. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5020. (
  5021. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5022. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5023. RegDeallocated
  5024. )
  5025. ) then
  5026. begin
  5027. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5028. {$push}
  5029. {$R-}{$Q-}
  5030. { Explicitly disable overflow checking for these offset calculation
  5031. as those do not matter for the final result }
  5032. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5033. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5034. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5035. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5036. {$pop}
  5037. {$ifdef x86_64}
  5038. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5039. begin
  5040. { Overflow; abort }
  5041. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5042. end
  5043. else
  5044. {$endif x86_64}
  5045. begin
  5046. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5047. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5048. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5049. RemoveCurrentP(p, hp1)
  5050. else
  5051. RemoveCurrentP(p);
  5052. result:=true;
  5053. Exit;
  5054. end;
  5055. end;
  5056. if (
  5057. { Save calling GetNextInstructionUsingReg again }
  5058. Assigned(hp1) or
  5059. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5060. ) and
  5061. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5062. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5063. begin
  5064. if taicpu(hp1).oper[0]^.typ = top_const then
  5065. begin
  5066. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5067. if taicpu(hp1).opcode = A_ADD then
  5068. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5069. else
  5070. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5071. Result := True;
  5072. { Handle any overflows }
  5073. case taicpu(p).opsize of
  5074. S_B:
  5075. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5076. S_W:
  5077. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5078. S_L:
  5079. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5080. {$ifdef x86_64}
  5081. S_Q:
  5082. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5083. { Overflow; abort }
  5084. Result := False
  5085. else
  5086. taicpu(p).oper[0]^.val := ThisConst;
  5087. {$endif x86_64}
  5088. else
  5089. InternalError(2021102610);
  5090. end;
  5091. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5092. if Result then
  5093. begin
  5094. if (taicpu(p).oper[0]^.val < 0) and
  5095. (
  5096. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5097. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5098. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5099. ) then
  5100. begin
  5101. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5102. taicpu(p).opcode := A_SUB;
  5103. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5104. end
  5105. else
  5106. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5107. RemoveInstruction(hp1);
  5108. end;
  5109. end
  5110. else
  5111. begin
  5112. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5113. TransferUsedRegs(TmpUsedRegs);
  5114. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5115. hp2 := p;
  5116. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5117. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5118. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5119. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5120. begin
  5121. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5122. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5123. Asml.Remove(p);
  5124. Asml.InsertAfter(p, hp1);
  5125. p := hp1;
  5126. Result := True;
  5127. Exit;
  5128. end;
  5129. end;
  5130. end;
  5131. if DoArithCombineOpt(p) then
  5132. Result:=true;
  5133. end;
  5134. end;
  5135. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5136. var
  5137. hp1, hp2: tai;
  5138. ref: Integer;
  5139. saveref: treference;
  5140. offsetcalc: Int64;
  5141. TempReg: TRegister;
  5142. Multiple: TCGInt;
  5143. Adjacent, IntermediateRegDiscarded: Boolean;
  5144. begin
  5145. Result:=false;
  5146. { play save and throw an error if LEA uses a seg register prefix,
  5147. this is most likely an error somewhere else }
  5148. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5149. internalerror(2022022001);
  5150. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5151. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5152. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5153. (
  5154. { do not mess with leas accessing the stack pointer
  5155. unless it's a null operation }
  5156. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5157. (
  5158. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5159. (taicpu(p).oper[0]^.ref^.offset = 0)
  5160. )
  5161. ) and
  5162. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5163. begin
  5164. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5165. begin
  5166. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5167. begin
  5168. taicpu(p).opcode := A_MOV;
  5169. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5170. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5171. end
  5172. else
  5173. begin
  5174. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5175. RemoveCurrentP(p);
  5176. end;
  5177. Result:=true;
  5178. exit;
  5179. end
  5180. else if (
  5181. { continue to use lea to adjust the stack pointer,
  5182. it is the recommended way, but only if not optimizing for size }
  5183. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5184. (cs_opt_size in current_settings.optimizerswitches)
  5185. ) and
  5186. { If the flags register is in use, don't change the instruction
  5187. to an ADD otherwise this will scramble the flags. [Kit] }
  5188. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5189. ConvertLEA(taicpu(p)) then
  5190. begin
  5191. Result:=true;
  5192. exit;
  5193. end;
  5194. end;
  5195. { Don't optimise if the stack or frame pointer is the destination register }
  5196. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5197. Exit;
  5198. if GetNextInstruction(p,hp1) and
  5199. (hp1.typ=ait_instruction) then
  5200. begin
  5201. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5202. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5203. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5204. begin
  5205. TransferUsedRegs(TmpUsedRegs);
  5206. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5207. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5208. begin
  5209. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5210. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5211. RemoveInstruction(hp1);
  5212. result:=true;
  5213. exit;
  5214. end;
  5215. end;
  5216. { changes
  5217. lea <ref1>, reg1
  5218. <op> ...,<ref. with reg1>,...
  5219. to
  5220. <op> ...,<ref1>,... }
  5221. { find a reference which uses reg1 }
  5222. if (taicpu(hp1).ops>=1) and (taicpu(hp1).oper[0]^.typ=top_ref) and RegInOp(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^) then
  5223. ref:=0
  5224. else if (taicpu(hp1).ops>=2) and (taicpu(hp1).oper[1]^.typ=top_ref) and RegInOp(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^) then
  5225. ref:=1
  5226. else
  5227. ref:=-1;
  5228. if (ref<>-1) and
  5229. { reg1 must be either the base or the index }
  5230. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5231. begin
  5232. { reg1 can be removed from the reference }
  5233. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5234. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5235. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5236. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5237. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5238. else
  5239. Internalerror(2019111201);
  5240. { check if the can insert all data of the lea into the second instruction }
  5241. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5242. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5243. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5244. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5245. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5246. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5247. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5248. {$ifdef x86_64}
  5249. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5250. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5251. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5252. )
  5253. {$endif x86_64}
  5254. then
  5255. begin
  5256. { reg1 might not used by the second instruction after it is remove from the reference }
  5257. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5258. begin
  5259. TransferUsedRegs(TmpUsedRegs);
  5260. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5261. { reg1 is not updated so it might not be used afterwards }
  5262. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5263. begin
  5264. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5265. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5266. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5267. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5268. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5269. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5270. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5271. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5272. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5273. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5274. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5275. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5276. RemoveCurrentP(p, hp1);
  5277. result:=true;
  5278. exit;
  5279. end
  5280. end;
  5281. end;
  5282. { recover }
  5283. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5284. end;
  5285. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5286. if Adjacent or
  5287. { Check further ahead (up to 2 instructions ahead for -O2) }
  5288. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5289. begin
  5290. { Check common LEA/LEA conditions }
  5291. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5292. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5293. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5294. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5295. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5296. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5297. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5298. (
  5299. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5300. calling it (since it calls GetNextInstruction) }
  5301. Adjacent or
  5302. (
  5303. (
  5304. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5305. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5306. ) and (
  5307. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5308. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5309. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5310. )
  5311. )
  5312. ) then
  5313. begin
  5314. TransferUsedRegs(TmpUsedRegs);
  5315. hp2 := p;
  5316. repeat
  5317. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5318. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5319. IntermediateRegDiscarded :=
  5320. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5321. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5322. { changes
  5323. lea offset1(regX,scale), reg1
  5324. lea offset2(reg1,reg1), reg2
  5325. to
  5326. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5327. and
  5328. lea offset1(regX,scale1), reg1
  5329. lea offset2(reg1,scale2), reg2
  5330. to
  5331. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5332. and
  5333. lea offset1(regX,scale1), reg1
  5334. lea offset2(reg3,reg1,scale2), reg2
  5335. to
  5336. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5337. ... so long as the final scale does not exceed 8
  5338. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5339. }
  5340. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5341. (
  5342. { Don't optimise if size is a concern and the intermediate register remains in use }
  5343. IntermediateRegDiscarded or
  5344. not (cs_opt_size in current_settings.optimizerswitches)
  5345. ) and
  5346. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5347. (
  5348. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5349. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5350. ) and (
  5351. (
  5352. { lea (reg1,scale2), reg2 variant }
  5353. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5354. (
  5355. Adjacent or
  5356. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5357. ) and
  5358. (
  5359. (
  5360. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5361. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5362. ) or (
  5363. { lea (regX,regX), reg1 variant }
  5364. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5365. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5366. )
  5367. )
  5368. ) or (
  5369. { lea (reg1,reg1), reg1 variant }
  5370. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5371. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5372. )
  5373. ) then
  5374. begin
  5375. { Make everything homogeneous to make calculations easier }
  5376. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5377. begin
  5378. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5379. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5380. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5381. else
  5382. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5383. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5384. end;
  5385. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5386. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5387. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5388. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5389. begin
  5390. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5391. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5392. begin
  5393. { Put the register to change in the index register }
  5394. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5395. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5396. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5397. end;
  5398. if (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5399. begin
  5400. { Just to prevent miscalculations }
  5401. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5402. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5403. else
  5404. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5405. end
  5406. else
  5407. begin
  5408. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5409. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5410. end;
  5411. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5412. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(p).oper[0]^.ref^.scalefactor, 1));
  5413. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5414. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5415. if IntermediateRegDiscarded then
  5416. begin
  5417. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5418. RemoveCurrentP(p);
  5419. end
  5420. else
  5421. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5422. result:=true;
  5423. exit;
  5424. end;
  5425. end;
  5426. { changes
  5427. lea offset1(regX), reg1
  5428. lea offset2(reg1), reg2
  5429. to
  5430. lea offset1+offset2(regX), reg2 }
  5431. if (
  5432. { Don't optimise if size is a concern and the intermediate register remains in use }
  5433. IntermediateRegDiscarded or
  5434. not (cs_opt_size in current_settings.optimizerswitches)
  5435. ) and
  5436. (
  5437. (
  5438. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5439. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5440. ) or (
  5441. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5442. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5443. (
  5444. (
  5445. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5446. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5447. ) or (
  5448. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5449. (
  5450. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5451. (
  5452. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5453. (
  5454. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5455. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5456. )
  5457. )
  5458. )
  5459. )
  5460. )
  5461. )
  5462. ) then
  5463. begin
  5464. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5465. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5466. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5467. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5468. begin
  5469. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5470. begin
  5471. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5472. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5473. { if the register is used as index and base, we have to increase for base as well
  5474. and adapt base }
  5475. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5476. begin
  5477. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5478. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5479. end;
  5480. end
  5481. else
  5482. begin
  5483. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5484. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5485. end;
  5486. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5487. begin
  5488. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5489. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5490. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5491. end;
  5492. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5493. if IntermediateRegDiscarded then
  5494. begin
  5495. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5496. RemoveCurrentP(p);
  5497. end
  5498. else
  5499. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5500. result:=true;
  5501. exit;
  5502. end;
  5503. end;
  5504. end;
  5505. { Change:
  5506. leal/q $x(%reg1),%reg2
  5507. ...
  5508. shll/q $y,%reg2
  5509. To:
  5510. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5511. }
  5512. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5513. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5514. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5515. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5516. (taicpu(hp1).oper[0]^.val <= 3) then
  5517. begin
  5518. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5519. TransferUsedRegs(TmpUsedRegs);
  5520. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5521. if
  5522. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5523. (this works even if scalefactor is zero) }
  5524. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5525. { Ensure offset doesn't go out of bounds }
  5526. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5527. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5528. (
  5529. (
  5530. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5531. (
  5532. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5533. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5534. (
  5535. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5536. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5537. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5538. )
  5539. )
  5540. ) or (
  5541. (
  5542. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5543. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5544. ) and
  5545. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5546. )
  5547. ) then
  5548. begin
  5549. repeat
  5550. with taicpu(p).oper[0]^.ref^ do
  5551. begin
  5552. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5553. if index = base then
  5554. begin
  5555. if Multiple > 4 then
  5556. { Optimisation will no longer work because resultant
  5557. scale factor will exceed 8 }
  5558. Break;
  5559. base := NR_NO;
  5560. scalefactor := 2;
  5561. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5562. end
  5563. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5564. begin
  5565. { Scale factor only works on the index register }
  5566. index := base;
  5567. base := NR_NO;
  5568. end;
  5569. { For safety }
  5570. if scalefactor <= 1 then
  5571. begin
  5572. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5573. scalefactor := Multiple;
  5574. end
  5575. else
  5576. begin
  5577. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5578. scalefactor := scalefactor * Multiple;
  5579. end;
  5580. offset := offset * Multiple;
  5581. end;
  5582. RemoveInstruction(hp1);
  5583. Result := True;
  5584. Exit;
  5585. { This repeat..until loop exists for the benefit of Break }
  5586. until True;
  5587. end;
  5588. end;
  5589. end;
  5590. end;
  5591. end;
  5592. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5593. var
  5594. hp1 : tai;
  5595. SubInstr: Boolean;
  5596. ThisConst: TCGInt;
  5597. const
  5598. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5599. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5600. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5601. begin
  5602. Result := False;
  5603. if taicpu(p).oper[0]^.typ <> top_const then
  5604. { Should have been confirmed before calling }
  5605. InternalError(2021102601);
  5606. SubInstr := (taicpu(p).opcode = A_SUB);
  5607. if GetLastInstruction(p, hp1) and
  5608. (hp1.typ = ait_instruction) and
  5609. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5610. begin
  5611. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5612. { Bad size }
  5613. InternalError(2022042001);
  5614. case taicpu(hp1).opcode Of
  5615. A_INC:
  5616. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5617. begin
  5618. if SubInstr then
  5619. ThisConst := taicpu(p).oper[0]^.val - 1
  5620. else
  5621. ThisConst := taicpu(p).oper[0]^.val + 1;
  5622. end
  5623. else
  5624. Exit;
  5625. A_DEC:
  5626. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5627. begin
  5628. if SubInstr then
  5629. ThisConst := taicpu(p).oper[0]^.val + 1
  5630. else
  5631. ThisConst := taicpu(p).oper[0]^.val - 1;
  5632. end
  5633. else
  5634. Exit;
  5635. A_SUB:
  5636. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5637. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5638. begin
  5639. if SubInstr then
  5640. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5641. else
  5642. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5643. end
  5644. else
  5645. Exit;
  5646. A_ADD:
  5647. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5648. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5649. begin
  5650. if SubInstr then
  5651. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5652. else
  5653. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5654. end
  5655. else
  5656. Exit;
  5657. else
  5658. Exit;
  5659. end;
  5660. { Check that the values are in range }
  5661. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5662. { Overflow; abort }
  5663. Exit;
  5664. if (ThisConst = 0) then
  5665. begin
  5666. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5667. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5668. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5669. RemoveInstruction(hp1);
  5670. hp1 := tai(p.next);
  5671. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5672. if not GetLastInstruction(hp1, p) then
  5673. p := hp1;
  5674. end
  5675. else
  5676. begin
  5677. if taicpu(hp1).opercnt=1 then
  5678. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5679. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5680. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5681. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5682. else
  5683. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5684. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5685. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5686. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5687. RemoveInstruction(hp1);
  5688. taicpu(p).loadconst(0, ThisConst);
  5689. end;
  5690. Result := True;
  5691. end;
  5692. end;
  5693. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5694. begin
  5695. Result := False;
  5696. if UpdateTmpUsedRegs then
  5697. TransferUsedRegs(TmpUsedRegs);
  5698. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5699. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5700. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5701. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5702. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5703. (
  5704. (
  5705. (taicpu(hp1).opcode = A_TEST)
  5706. ) or (
  5707. (taicpu(hp1).opcode = A_CMP) and
  5708. { A sanity check more than anything }
  5709. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5710. )
  5711. ) then
  5712. begin
  5713. { change
  5714. mov mem, %reg
  5715. cmp/test x, %reg / test %reg,%reg
  5716. (reg deallocated)
  5717. to
  5718. cmp/test x, mem / cmp 0, mem
  5719. }
  5720. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5721. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5722. begin
  5723. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5724. if (taicpu(hp1).opcode = A_TEST) and
  5725. (
  5726. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5727. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5728. ) then
  5729. begin
  5730. taicpu(hp1).opcode := A_CMP;
  5731. taicpu(hp1).loadconst(0, 0);
  5732. end;
  5733. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5734. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5735. RemoveCurrentP(p, hp1);
  5736. Result := True;
  5737. Exit;
  5738. end;
  5739. end;
  5740. end;
  5741. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5742. var
  5743. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5744. ThisReg, SecondReg: TRegister;
  5745. JumpLoc: TAsmLabel;
  5746. NewSize: TOpSize;
  5747. begin
  5748. Result := False;
  5749. {
  5750. Convert:
  5751. j<c> .L1
  5752. .L2:
  5753. mov 1,reg
  5754. jmp .L3 (or ret, although it might not be a RET yet)
  5755. .L1:
  5756. mov 0,reg
  5757. jmp .L3 (or ret)
  5758. ( As long as .L3 <> .L1 or .L2)
  5759. To:
  5760. mov 0,reg
  5761. set<not(c)> reg
  5762. jmp .L3 (or ret)
  5763. .L2:
  5764. mov 1,reg
  5765. jmp .L3 (or ret)
  5766. .L1:
  5767. mov 0,reg
  5768. jmp .L3 (or ret)
  5769. }
  5770. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5771. Exit;
  5772. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5773. if GetNextInstruction(hp_label, hp2) and
  5774. MatchInstruction(hp2,A_MOV,[]) and
  5775. (taicpu(hp2).oper[0]^.typ = top_const) and
  5776. (
  5777. (
  5778. (taicpu(hp2).oper[1]^.typ = top_reg)
  5779. {$ifdef i386}
  5780. { Under i386, ESI, EDI, EBP and ESP
  5781. don't have an 8-bit representation }
  5782. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5783. {$endif i386}
  5784. ) or (
  5785. {$ifdef i386}
  5786. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5787. {$endif i386}
  5788. (taicpu(hp2).opsize = S_B)
  5789. )
  5790. ) and
  5791. GetNextInstruction(hp2, hp3) and
  5792. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5793. (
  5794. (taicpu(hp3).opcode=A_RET) or
  5795. (
  5796. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5797. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5798. )
  5799. ) and
  5800. GetNextInstruction(hp3, hp4) and
  5801. SkipAligns(hp4, hp4) and
  5802. (hp4.typ=ait_label) and
  5803. (tai_label(hp4).labsym=JumpLoc) and
  5804. (
  5805. not (cs_opt_size in current_settings.optimizerswitches) or
  5806. { If the initial jump is the label's only reference, then it will
  5807. become a dead label if the other conditions are met and hence
  5808. remove at least 2 instructions, including a jump }
  5809. (JumpLoc.getrefs = 1)
  5810. ) and
  5811. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5812. that will be optimised out }
  5813. GetNextInstruction(hp4, hp5) and
  5814. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5815. (taicpu(hp5).oper[0]^.typ = top_const) and
  5816. (
  5817. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5818. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5819. ) and
  5820. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5821. GetNextInstruction(hp5,hp6) and
  5822. (
  5823. (hp6.typ<>ait_label) or
  5824. SkipLabels(hp6, hp6)
  5825. ) and
  5826. (hp6.typ=ait_instruction) then
  5827. begin
  5828. { First, let's look at the two jumps that are hp3 and hp6 }
  5829. if not
  5830. (
  5831. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5832. (
  5833. (taicpu(hp6).opcode=A_RET) or
  5834. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5835. )
  5836. ) then
  5837. { If condition is False, then the JMP/RET instructions matched conventionally }
  5838. begin
  5839. { See if one of the jumps can be instantly converted into a RET }
  5840. if (taicpu(hp3).opcode=A_JMP) then
  5841. begin
  5842. { Reuse hp5 }
  5843. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5844. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5845. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5846. Exit;
  5847. if MatchInstruction(hp5, A_RET, []) then
  5848. begin
  5849. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5850. ConvertJumpToRET(hp3, hp5);
  5851. Result := True;
  5852. end
  5853. else
  5854. Exit;
  5855. end;
  5856. if (taicpu(hp6).opcode=A_JMP) then
  5857. begin
  5858. { Reuse hp5 }
  5859. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5860. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5861. Exit;
  5862. if MatchInstruction(hp5, A_RET, []) then
  5863. begin
  5864. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5865. ConvertJumpToRET(hp6, hp5);
  5866. Result := True;
  5867. end
  5868. else
  5869. Exit;
  5870. end;
  5871. if not
  5872. (
  5873. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5874. (
  5875. (taicpu(hp6).opcode=A_RET) or
  5876. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5877. )
  5878. ) then
  5879. { Still doesn't match }
  5880. Exit;
  5881. end;
  5882. if (taicpu(hp2).oper[0]^.val = 1) then
  5883. begin
  5884. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5885. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5886. end
  5887. else
  5888. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5889. if taicpu(hp2).opsize=S_B then
  5890. begin
  5891. if taicpu(hp2).oper[1]^.typ = top_reg then
  5892. begin
  5893. SecondReg := taicpu(hp2).oper[1]^.reg;
  5894. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  5895. end
  5896. else
  5897. begin
  5898. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5899. SecondReg := NR_NO;
  5900. end;
  5901. hp_pos := p;
  5902. hp_allocstart := hp4;
  5903. end
  5904. else
  5905. begin
  5906. { Will be a register because the size can't be S_B otherwise }
  5907. SecondReg:=taicpu(hp2).oper[1]^.reg;
  5908. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  5909. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5910. if (cs_opt_size in current_settings.optimizerswitches) then
  5911. begin
  5912. { Favour using MOVZX when optimising for size }
  5913. case taicpu(hp2).opsize of
  5914. S_W:
  5915. NewSize := S_BW;
  5916. S_L:
  5917. NewSize := S_BL;
  5918. {$ifdef x86_64}
  5919. S_Q:
  5920. begin
  5921. NewSize := S_BL;
  5922. { Will implicitly zero-extend to 64-bit }
  5923. setsubreg(SecondReg, R_SUBD);
  5924. end;
  5925. {$endif x86_64}
  5926. else
  5927. InternalError(2022101301);
  5928. end;
  5929. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  5930. { Inserting it right before p will guarantee that the flags are also tracked }
  5931. Asml.InsertBefore(hp5, p);
  5932. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  5933. hp_pos := hp5;
  5934. hp_allocstart := hp4;
  5935. end
  5936. else
  5937. begin
  5938. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  5939. { Inserting it right before p will guarantee that the flags are also tracked }
  5940. Asml.InsertBefore(hp5, p);
  5941. hp_pos := p;
  5942. hp_allocstart := hp5;
  5943. end;
  5944. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  5945. end;
  5946. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  5947. taicpu(hp4).condition := taicpu(p).condition;
  5948. asml.InsertBefore(hp4, hp_pos);
  5949. if taicpu(hp3).is_jmp then
  5950. begin
  5951. JumpLoc.decrefs;
  5952. MakeUnconditional(taicpu(p));
  5953. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5954. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5955. end
  5956. else
  5957. ConvertJumpToRET(p, hp3);
  5958. if SecondReg <> NR_NO then
  5959. { Ensure the destination register is allocated over this region }
  5960. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  5961. if (JumpLoc.getrefs = 0) then
  5962. RemoveDeadCodeAfterJump(hp3);
  5963. Result:=true;
  5964. exit;
  5965. end;
  5966. end;
  5967. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5968. var
  5969. hp1, hp2: tai;
  5970. ActiveReg: TRegister;
  5971. OldOffset: asizeint;
  5972. ThisConst: TCGInt;
  5973. function RegDeallocated: Boolean;
  5974. begin
  5975. TransferUsedRegs(TmpUsedRegs);
  5976. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5977. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5978. end;
  5979. begin
  5980. Result:=false;
  5981. hp1 := nil;
  5982. { replace
  5983. subX const,%reg1
  5984. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5985. dealloc %reg1
  5986. by
  5987. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5988. }
  5989. if MatchOpType(taicpu(p),top_const,top_reg) then
  5990. begin
  5991. ActiveReg := taicpu(p).oper[1]^.reg;
  5992. { Ensures the entire register was updated }
  5993. if (taicpu(p).opsize >= S_L) and
  5994. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5995. MatchInstruction(hp1,A_LEA,[]) and
  5996. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5997. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5998. (
  5999. { Cover the case where the register in the reference is also the destination register }
  6000. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6001. (
  6002. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6003. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6004. RegDeallocated
  6005. )
  6006. ) then
  6007. begin
  6008. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6009. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6010. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6011. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6012. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6013. {$ifdef x86_64}
  6014. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6015. begin
  6016. { Overflow; abort }
  6017. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6018. end
  6019. else
  6020. {$endif x86_64}
  6021. begin
  6022. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6023. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6024. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6025. RemoveCurrentP(p, hp1)
  6026. else
  6027. RemoveCurrentP(p);
  6028. result:=true;
  6029. Exit;
  6030. end;
  6031. end;
  6032. if (
  6033. { Save calling GetNextInstructionUsingReg again }
  6034. Assigned(hp1) or
  6035. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6036. ) and
  6037. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6038. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6039. begin
  6040. if taicpu(hp1).oper[0]^.typ = top_const then
  6041. begin
  6042. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6043. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6044. Result := True;
  6045. { Handle any overflows }
  6046. case taicpu(p).opsize of
  6047. S_B:
  6048. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6049. S_W:
  6050. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6051. S_L:
  6052. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6053. {$ifdef x86_64}
  6054. S_Q:
  6055. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6056. { Overflow; abort }
  6057. Result := False
  6058. else
  6059. taicpu(p).oper[0]^.val := ThisConst;
  6060. {$endif x86_64}
  6061. else
  6062. InternalError(2021102611);
  6063. end;
  6064. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6065. if Result then
  6066. begin
  6067. if (taicpu(p).oper[0]^.val < 0) and
  6068. (
  6069. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6070. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6071. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6072. ) then
  6073. begin
  6074. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6075. taicpu(p).opcode := A_SUB;
  6076. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6077. end
  6078. else
  6079. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6080. RemoveInstruction(hp1);
  6081. end;
  6082. end
  6083. else
  6084. begin
  6085. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6086. TransferUsedRegs(TmpUsedRegs);
  6087. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6088. hp2 := p;
  6089. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6090. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6091. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6092. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6093. begin
  6094. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6095. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6096. Asml.Remove(p);
  6097. Asml.InsertAfter(p, hp1);
  6098. p := hp1;
  6099. Result := True;
  6100. Exit;
  6101. end;
  6102. end;
  6103. end;
  6104. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6105. { * change "sub/add const1, reg" or "dec reg" followed by
  6106. "sub const2, reg" to one "sub ..., reg" }
  6107. {$ifdef i386}
  6108. if (taicpu(p).oper[0]^.val = 2) and
  6109. (ActiveReg = NR_ESP) and
  6110. { Don't do the sub/push optimization if the sub }
  6111. { comes from setting up the stack frame (JM) }
  6112. (not(GetLastInstruction(p,hp1)) or
  6113. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6114. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6115. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6116. begin
  6117. hp1 := tai(p.next);
  6118. while Assigned(hp1) and
  6119. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6120. not RegReadByInstruction(NR_ESP,hp1) and
  6121. not RegModifiedByInstruction(NR_ESP,hp1) do
  6122. hp1 := tai(hp1.next);
  6123. if Assigned(hp1) and
  6124. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6125. begin
  6126. taicpu(hp1).changeopsize(S_L);
  6127. if taicpu(hp1).oper[0]^.typ=top_reg then
  6128. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6129. hp1 := tai(p.next);
  6130. RemoveCurrentp(p, hp1);
  6131. Result:=true;
  6132. exit;
  6133. end;
  6134. end;
  6135. {$endif i386}
  6136. if DoArithCombineOpt(p) then
  6137. Result:=true;
  6138. end;
  6139. end;
  6140. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6141. var
  6142. TmpBool1,TmpBool2 : Boolean;
  6143. tmpref : treference;
  6144. hp1,hp2: tai;
  6145. mask, shiftval: tcgint;
  6146. begin
  6147. Result:=false;
  6148. { All these optimisations work on "shl/sal const,%reg" }
  6149. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6150. Exit;
  6151. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6152. (taicpu(p).oper[0]^.val <= 3) then
  6153. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6154. begin
  6155. { should we check the next instruction? }
  6156. TmpBool1 := True;
  6157. { have we found an add/sub which could be
  6158. integrated in the lea? }
  6159. TmpBool2 := False;
  6160. reference_reset(tmpref,2,[]);
  6161. TmpRef.index := taicpu(p).oper[1]^.reg;
  6162. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6163. while TmpBool1 and
  6164. GetNextInstruction(p, hp1) and
  6165. (tai(hp1).typ = ait_instruction) and
  6166. ((((taicpu(hp1).opcode = A_ADD) or
  6167. (taicpu(hp1).opcode = A_SUB)) and
  6168. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6169. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6170. (((taicpu(hp1).opcode = A_INC) or
  6171. (taicpu(hp1).opcode = A_DEC)) and
  6172. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6173. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6174. ((taicpu(hp1).opcode = A_LEA) and
  6175. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6176. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6177. (not GetNextInstruction(hp1,hp2) or
  6178. not instrReadsFlags(hp2)) Do
  6179. begin
  6180. TmpBool1 := False;
  6181. if taicpu(hp1).opcode=A_LEA then
  6182. begin
  6183. if (TmpRef.base = NR_NO) and
  6184. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6185. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6186. { Segment register isn't a concern here }
  6187. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6188. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6189. begin
  6190. TmpBool1 := True;
  6191. TmpBool2 := True;
  6192. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6193. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6194. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6195. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6196. RemoveInstruction(hp1);
  6197. end
  6198. end
  6199. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6200. begin
  6201. TmpBool1 := True;
  6202. TmpBool2 := True;
  6203. case taicpu(hp1).opcode of
  6204. A_ADD:
  6205. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6206. A_SUB:
  6207. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6208. else
  6209. internalerror(2019050536);
  6210. end;
  6211. RemoveInstruction(hp1);
  6212. end
  6213. else
  6214. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6215. (((taicpu(hp1).opcode = A_ADD) and
  6216. (TmpRef.base = NR_NO)) or
  6217. (taicpu(hp1).opcode = A_INC) or
  6218. (taicpu(hp1).opcode = A_DEC)) then
  6219. begin
  6220. TmpBool1 := True;
  6221. TmpBool2 := True;
  6222. case taicpu(hp1).opcode of
  6223. A_ADD:
  6224. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6225. A_INC:
  6226. inc(TmpRef.offset);
  6227. A_DEC:
  6228. dec(TmpRef.offset);
  6229. else
  6230. internalerror(2019050535);
  6231. end;
  6232. RemoveInstruction(hp1);
  6233. end;
  6234. end;
  6235. if TmpBool2
  6236. {$ifndef x86_64}
  6237. or
  6238. ((current_settings.optimizecputype < cpu_Pentium2) and
  6239. (taicpu(p).oper[0]^.val <= 3) and
  6240. not(cs_opt_size in current_settings.optimizerswitches))
  6241. {$endif x86_64}
  6242. then
  6243. begin
  6244. if not(TmpBool2) and
  6245. (taicpu(p).oper[0]^.val=1) then
  6246. begin
  6247. taicpu(p).opcode := A_ADD;
  6248. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6249. end
  6250. else
  6251. begin
  6252. taicpu(p).opcode := A_LEA;
  6253. taicpu(p).loadref(0, TmpRef);
  6254. end;
  6255. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6256. Result := True;
  6257. end;
  6258. end
  6259. {$ifndef x86_64}
  6260. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6261. begin
  6262. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6263. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6264. (unlike shl, which is only Tairable in the U pipe) }
  6265. if taicpu(p).oper[0]^.val=1 then
  6266. begin
  6267. taicpu(p).opcode := A_ADD;
  6268. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6269. Result := True;
  6270. end
  6271. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6272. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6273. else if (taicpu(p).opsize = S_L) and
  6274. (taicpu(p).oper[0]^.val<= 3) then
  6275. begin
  6276. reference_reset(tmpref,2,[]);
  6277. TmpRef.index := taicpu(p).oper[1]^.reg;
  6278. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6279. taicpu(p).opcode := A_LEA;
  6280. taicpu(p).loadref(0, TmpRef);
  6281. Result := True;
  6282. end;
  6283. end
  6284. {$endif x86_64}
  6285. else if
  6286. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6287. (
  6288. (
  6289. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6290. SetAndTest(hp1, hp2)
  6291. {$ifdef x86_64}
  6292. ) or
  6293. (
  6294. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6295. GetNextInstruction(hp1, hp2) and
  6296. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6297. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6298. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6299. {$endif x86_64}
  6300. )
  6301. ) and
  6302. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6303. begin
  6304. { Change:
  6305. shl x, %reg1
  6306. mov -(1<<x), %reg2
  6307. and %reg2, %reg1
  6308. Or:
  6309. shl x, %reg1
  6310. and -(1<<x), %reg1
  6311. To just:
  6312. shl x, %reg1
  6313. Since the and operation only zeroes bits that are already zero from the shl operation
  6314. }
  6315. case taicpu(p).oper[0]^.val of
  6316. 8:
  6317. mask:=$FFFFFFFFFFFFFF00;
  6318. 16:
  6319. mask:=$FFFFFFFFFFFF0000;
  6320. 32:
  6321. mask:=$FFFFFFFF00000000;
  6322. 63:
  6323. { Constant pre-calculated to prevent overflow errors with Int64 }
  6324. mask:=$8000000000000000;
  6325. else
  6326. begin
  6327. if taicpu(p).oper[0]^.val >= 64 then
  6328. { Shouldn't happen realistically, since the register
  6329. is guaranteed to be set to zero at this point }
  6330. mask := 0
  6331. else
  6332. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6333. end;
  6334. end;
  6335. if taicpu(hp1).oper[0]^.val = mask then
  6336. begin
  6337. { Everything checks out, perform the optimisation, as long as
  6338. the FLAGS register isn't being used}
  6339. TransferUsedRegs(TmpUsedRegs);
  6340. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6341. {$ifdef x86_64}
  6342. if (hp1 <> hp2) then
  6343. begin
  6344. { "shl/mov/and" version }
  6345. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6346. { Don't do the optimisation if the FLAGS register is in use }
  6347. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6348. begin
  6349. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6350. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6351. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6352. begin
  6353. RemoveInstruction(hp1);
  6354. Result := True;
  6355. end;
  6356. { Only set Result to True if the 'mov' instruction was removed }
  6357. RemoveInstruction(hp2);
  6358. end;
  6359. end
  6360. else
  6361. {$endif x86_64}
  6362. begin
  6363. { "shl/and" version }
  6364. { Don't do the optimisation if the FLAGS register is in use }
  6365. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6366. begin
  6367. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6368. RemoveInstruction(hp1);
  6369. Result := True;
  6370. end;
  6371. end;
  6372. Exit;
  6373. end
  6374. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6375. begin
  6376. { Even if the mask doesn't allow for its removal, we might be
  6377. able to optimise the mask for the "shl/and" version, which
  6378. may permit other peephole optimisations }
  6379. {$ifdef DEBUG_AOPTCPU}
  6380. mask := taicpu(hp1).oper[0]^.val and mask;
  6381. if taicpu(hp1).oper[0]^.val <> mask then
  6382. begin
  6383. DebugMsg(
  6384. SPeepholeOptimization +
  6385. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6386. ' to $' + debug_tostr(mask) +
  6387. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6388. taicpu(hp1).oper[0]^.val := mask;
  6389. end;
  6390. {$else DEBUG_AOPTCPU}
  6391. { If debugging is off, just set the operand even if it's the same }
  6392. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6393. {$endif DEBUG_AOPTCPU}
  6394. end;
  6395. end;
  6396. {
  6397. change
  6398. shl/sal const,reg
  6399. <op> ...(...,reg,1),...
  6400. into
  6401. <op> ...(...,reg,1 shl const),...
  6402. if const in 1..3
  6403. }
  6404. if MatchOpType(taicpu(p), top_const, top_reg) and
  6405. (taicpu(p).oper[0]^.val in [1..3]) and
  6406. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6407. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6408. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6409. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6410. MatchOpType(taicpu(hp1),top_ref))
  6411. ) and
  6412. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6413. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6414. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6415. begin
  6416. TransferUsedRegs(TmpUsedRegs);
  6417. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6418. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6419. begin
  6420. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6421. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6422. RemoveCurrentP(p);
  6423. Result:=true;
  6424. exit;
  6425. end;
  6426. end;
  6427. if MatchOpType(taicpu(p), top_const, top_reg) and
  6428. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6429. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6430. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6431. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6432. begin
  6433. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6434. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6435. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6436. {$ifdef x86_64}
  6437. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6438. {$endif x86_64}
  6439. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6440. begin
  6441. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6442. taicpu(hp1).opcode:=A_MOV;
  6443. taicpu(hp1).oper[0]^.val:=0;
  6444. end
  6445. else
  6446. begin
  6447. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6448. taicpu(hp1).oper[0]^.val:=shiftval;
  6449. end;
  6450. RemoveCurrentP(p);
  6451. Result:=true;
  6452. exit;
  6453. end;
  6454. end;
  6455. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6456. begin
  6457. case shr_size of
  6458. S_B:
  6459. { No valid combinations }
  6460. Result := False;
  6461. S_W:
  6462. Result := (Shift >= 8) and (movz_size = S_BW);
  6463. S_L:
  6464. Result :=
  6465. (Shift >= 24) { Any opsize is valid for this shift } or
  6466. ((Shift >= 16) and (movz_size = S_WL));
  6467. {$ifdef x86_64}
  6468. S_Q:
  6469. Result :=
  6470. (Shift >= 56) { Any opsize is valid for this shift } or
  6471. ((Shift >= 48) and (movz_size = S_WL));
  6472. {$endif x86_64}
  6473. else
  6474. InternalError(2022081510);
  6475. end;
  6476. end;
  6477. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6478. var
  6479. hp1, hp2: tai;
  6480. Shift: TCGInt;
  6481. LimitSize: Topsize;
  6482. DoNotMerge: Boolean;
  6483. begin
  6484. Result := False;
  6485. { All these optimisations work on "shr const,%reg" }
  6486. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6487. Exit;
  6488. DoNotMerge := False;
  6489. Shift := taicpu(p).oper[0]^.val;
  6490. LimitSize := taicpu(p).opsize;
  6491. hp1 := p;
  6492. repeat
  6493. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6494. Exit;
  6495. case taicpu(hp1).opcode of
  6496. A_TEST, A_CMP, A_Jcc:
  6497. { Skip over conditional jumps and relevant comparisons }
  6498. Continue;
  6499. A_MOVZX:
  6500. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6501. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6502. begin
  6503. { Since the original register is being read as is, subsequent
  6504. SHRs must not be merged at this point }
  6505. DoNotMerge := True;
  6506. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6507. begin
  6508. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6509. begin
  6510. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6511. taicpu(hp1).opcode := A_MOV;
  6512. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6513. case taicpu(hp1).opsize of
  6514. S_BW:
  6515. taicpu(hp1).opsize := S_W;
  6516. S_BL, S_WL:
  6517. taicpu(hp1).opsize := S_L;
  6518. else
  6519. InternalError(2022081503);
  6520. end;
  6521. { p itself hasn't changed, so no need to set Result to True }
  6522. Include(OptsToCheck, aoc_ForceNewIteration);
  6523. { See if there's anything afterwards that can be
  6524. optimised, since the input register hasn't changed }
  6525. Continue;
  6526. end;
  6527. { NOTE: If the MOVZX instruction reads and writes the same
  6528. register, defer this to the post-peephole optimisation stage }
  6529. Exit;
  6530. end;
  6531. end;
  6532. A_SHL, A_SAL, A_SHR:
  6533. if (taicpu(hp1).opsize <= LimitSize) and
  6534. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6535. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6536. begin
  6537. { Make sure the sizes don't exceed the register size limit
  6538. (measured by the shift value falling below the limit) }
  6539. if taicpu(hp1).opsize < LimitSize then
  6540. LimitSize := taicpu(hp1).opsize;
  6541. if taicpu(hp1).opcode = A_SHR then
  6542. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6543. else
  6544. begin
  6545. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6546. DoNotMerge := True;
  6547. end;
  6548. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6549. Exit;
  6550. { Since we've established that the combined shift is within
  6551. limits, we can actually combine the adjacent SHR
  6552. instructions even if they're different sizes }
  6553. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6554. begin
  6555. hp2 := tai(hp1.Previous);
  6556. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6557. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6558. RemoveInstruction(hp1);
  6559. hp1 := hp2;
  6560. { Though p has changed, only the constant has, and its
  6561. effects can still be detected on the next iteration of
  6562. the repeat..until loop }
  6563. Include(OptsToCheck, aoc_ForceNewIteration);
  6564. end;
  6565. { Move onto the next instruction }
  6566. Continue;
  6567. end;
  6568. else
  6569. ;
  6570. end;
  6571. Break;
  6572. until False;
  6573. end;
  6574. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6575. var
  6576. CurrentRef: TReference;
  6577. FullReg: TRegister;
  6578. hp1, hp2: tai;
  6579. begin
  6580. Result := False;
  6581. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6582. Exit;
  6583. { We assume you've checked if the operand is actually a reference by
  6584. this point. If it isn't, you'll most likely get an access violation }
  6585. CurrentRef := first_mov.oper[1]^.ref^;
  6586. { Memory must be aligned }
  6587. if (CurrentRef.offset mod 4) <> 0 then
  6588. Exit;
  6589. Inc(CurrentRef.offset);
  6590. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6591. if MatchOperand(second_mov.oper[0]^, 0) and
  6592. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6593. GetNextInstruction(second_mov, hp1) and
  6594. (hp1.typ = ait_instruction) and
  6595. (taicpu(hp1).opcode = A_MOV) and
  6596. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6597. (taicpu(hp1).oper[0]^.val = 0) then
  6598. begin
  6599. Inc(CurrentRef.offset);
  6600. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6601. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6602. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6603. begin
  6604. case taicpu(hp1).opsize of
  6605. S_B:
  6606. if GetNextInstruction(hp1, hp2) and
  6607. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6608. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6609. (taicpu(hp2).oper[0]^.val = 0) then
  6610. begin
  6611. Inc(CurrentRef.offset);
  6612. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6613. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6614. (taicpu(hp2).opsize = S_B) then
  6615. begin
  6616. RemoveInstruction(hp1);
  6617. RemoveInstruction(hp2);
  6618. first_mov.opsize := S_L;
  6619. if first_mov.oper[0]^.typ = top_reg then
  6620. begin
  6621. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6622. { Reuse second_mov as a MOVZX instruction }
  6623. second_mov.opcode := A_MOVZX;
  6624. second_mov.opsize := S_BL;
  6625. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6626. second_mov.loadreg(1, FullReg);
  6627. first_mov.oper[0]^.reg := FullReg;
  6628. asml.Remove(second_mov);
  6629. asml.InsertBefore(second_mov, first_mov);
  6630. end
  6631. else
  6632. { It's a value }
  6633. begin
  6634. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6635. RemoveInstruction(second_mov);
  6636. end;
  6637. Result := True;
  6638. Exit;
  6639. end;
  6640. end;
  6641. S_W:
  6642. begin
  6643. RemoveInstruction(hp1);
  6644. first_mov.opsize := S_L;
  6645. if first_mov.oper[0]^.typ = top_reg then
  6646. begin
  6647. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6648. { Reuse second_mov as a MOVZX instruction }
  6649. second_mov.opcode := A_MOVZX;
  6650. second_mov.opsize := S_BL;
  6651. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6652. second_mov.loadreg(1, FullReg);
  6653. first_mov.oper[0]^.reg := FullReg;
  6654. asml.Remove(second_mov);
  6655. asml.InsertBefore(second_mov, first_mov);
  6656. end
  6657. else
  6658. { It's a value }
  6659. begin
  6660. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6661. RemoveInstruction(second_mov);
  6662. end;
  6663. Result := True;
  6664. Exit;
  6665. end;
  6666. else
  6667. ;
  6668. end;
  6669. end;
  6670. end;
  6671. end;
  6672. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6673. { returns true if a "continue" should be done after this optimization }
  6674. var
  6675. hp1, hp2, hp3: tai;
  6676. begin
  6677. Result := false;
  6678. hp3 := nil;
  6679. if MatchOpType(taicpu(p),top_ref) and
  6680. GetNextInstruction(p, hp1) and
  6681. (hp1.typ = ait_instruction) and
  6682. (((taicpu(hp1).opcode = A_FLD) and
  6683. (taicpu(p).opcode = A_FSTP)) or
  6684. ((taicpu(p).opcode = A_FISTP) and
  6685. (taicpu(hp1).opcode = A_FILD))) and
  6686. MatchOpType(taicpu(hp1),top_ref) and
  6687. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6688. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6689. begin
  6690. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6691. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6692. GetNextInstruction(hp1, hp2) and
  6693. (((hp2.typ = ait_instruction) and
  6694. IsExitCode(hp2) and
  6695. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6696. not(assigned(current_procinfo.procdef.funcretsym) and
  6697. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6698. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6699. { fstp <temp>
  6700. fld <temp>
  6701. <dealloc> <temp>
  6702. }
  6703. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6704. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6705. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6706. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6707. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6708. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6709. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6710. )
  6711. )
  6712. ) then
  6713. begin
  6714. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6715. RemoveInstruction(hp1);
  6716. RemoveCurrentP(p, hp2);
  6717. { first case: exit code }
  6718. if hp2.typ = ait_instruction then
  6719. RemoveLastDeallocForFuncRes(p);
  6720. Result := true;
  6721. end
  6722. else
  6723. { we can do this only in fast math mode as fstp is rounding ...
  6724. ... still disabled as it breaks the compiler and/or rtl }
  6725. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6726. { ... or if another fstp equal to the first one follows }
  6727. GetNextInstruction(hp1,hp2) and
  6728. (hp2.typ = ait_instruction) and
  6729. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6730. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6731. begin
  6732. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6733. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6734. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6735. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6736. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6737. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6738. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6739. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6740. ) then
  6741. begin
  6742. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6743. RemoveCurrentP(p,hp2);
  6744. RemoveInstruction(hp1);
  6745. Result := true;
  6746. end
  6747. else if { fst can't store an extended/comp value }
  6748. (taicpu(p).opsize <> S_FX) and
  6749. (taicpu(p).opsize <> S_IQ) then
  6750. begin
  6751. if (taicpu(p).opcode = A_FSTP) then
  6752. taicpu(p).opcode := A_FST
  6753. else
  6754. taicpu(p).opcode := A_FIST;
  6755. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6756. RemoveInstruction(hp1);
  6757. Result := true;
  6758. end;
  6759. end;
  6760. end;
  6761. end;
  6762. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6763. var
  6764. hp1, hp2, hp3: tai;
  6765. begin
  6766. result:=false;
  6767. if MatchOpType(taicpu(p),top_reg) and
  6768. GetNextInstruction(p, hp1) and
  6769. (hp1.typ = Ait_Instruction) and
  6770. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6771. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6772. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6773. { change to
  6774. fld reg fxxx reg,st
  6775. fxxxp st, st1 (hp1)
  6776. Remark: non commutative operations must be reversed!
  6777. }
  6778. begin
  6779. case taicpu(hp1).opcode Of
  6780. A_FMULP,A_FADDP,
  6781. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6782. begin
  6783. case taicpu(hp1).opcode Of
  6784. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6785. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6786. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6787. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6788. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6789. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6790. else
  6791. internalerror(2019050534);
  6792. end;
  6793. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6794. taicpu(hp1).oper[1]^.reg := NR_ST;
  6795. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6796. RemoveCurrentP(p, hp1);
  6797. Result:=true;
  6798. exit;
  6799. end;
  6800. else
  6801. ;
  6802. end;
  6803. end
  6804. else
  6805. if MatchOpType(taicpu(p),top_ref) and
  6806. GetNextInstruction(p, hp2) and
  6807. (hp2.typ = Ait_Instruction) and
  6808. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6809. (taicpu(p).opsize in [S_FS, S_FL]) and
  6810. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6811. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6812. if GetLastInstruction(p, hp1) and
  6813. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6814. MatchOpType(taicpu(hp1),top_ref) and
  6815. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6816. if ((taicpu(hp2).opcode = A_FMULP) or
  6817. (taicpu(hp2).opcode = A_FADDP)) then
  6818. { change to
  6819. fld/fst mem1 (hp1) fld/fst mem1
  6820. fld mem1 (p) fadd/
  6821. faddp/ fmul st, st
  6822. fmulp st, st1 (hp2) }
  6823. begin
  6824. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6825. RemoveCurrentP(p, hp1);
  6826. if (taicpu(hp2).opcode = A_FADDP) then
  6827. taicpu(hp2).opcode := A_FADD
  6828. else
  6829. taicpu(hp2).opcode := A_FMUL;
  6830. taicpu(hp2).oper[1]^.reg := NR_ST;
  6831. end
  6832. else
  6833. { change to
  6834. fld/fst mem1 (hp1) fld/fst mem1
  6835. fld mem1 (p) fld st
  6836. }
  6837. begin
  6838. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6839. taicpu(p).changeopsize(S_FL);
  6840. taicpu(p).loadreg(0,NR_ST);
  6841. end
  6842. else
  6843. begin
  6844. case taicpu(hp2).opcode Of
  6845. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6846. { change to
  6847. fld/fst mem1 (hp1) fld/fst mem1
  6848. fld mem2 (p) fxxx mem2
  6849. fxxxp st, st1 (hp2) }
  6850. begin
  6851. case taicpu(hp2).opcode Of
  6852. A_FADDP: taicpu(p).opcode := A_FADD;
  6853. A_FMULP: taicpu(p).opcode := A_FMUL;
  6854. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6855. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6856. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6857. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6858. else
  6859. internalerror(2019050533);
  6860. end;
  6861. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6862. RemoveInstruction(hp2);
  6863. end
  6864. else
  6865. ;
  6866. end
  6867. end
  6868. end;
  6869. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6870. begin
  6871. Result := condition_in(cond1, cond2) or
  6872. { Not strictly subsets due to the actual flags checked, but because we're
  6873. comparing integers, E is a subset of AE and GE and their aliases }
  6874. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6875. end;
  6876. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6877. var
  6878. v: TCGInt;
  6879. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6880. FirstMatch, TempBool: Boolean;
  6881. NewReg: TRegister;
  6882. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6883. begin
  6884. Result:=false;
  6885. { All these optimisations need a next instruction }
  6886. if not GetNextInstruction(p, hp1) then
  6887. Exit;
  6888. { Search for:
  6889. cmp ###,###
  6890. j(c1) @lbl1
  6891. ...
  6892. @lbl:
  6893. cmp ###,### (same comparison as above)
  6894. j(c2) @lbl2
  6895. If c1 is a subset of c2, change to:
  6896. cmp ###,###
  6897. j(c1) @lbl2
  6898. (@lbl1 may become a dead label as a result)
  6899. }
  6900. { Also handle cases where there are multiple jumps in a row }
  6901. p_jump := hp1;
  6902. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6903. begin
  6904. if IsJumpToLabel(taicpu(p_jump)) then
  6905. begin
  6906. { Do jump optimisations first in case the condition becomes
  6907. unnecessary }
  6908. TempBool := True;
  6909. if DoJumpOptimizations(p_jump, TempBool) or
  6910. not TempBool then
  6911. begin
  6912. if Assigned(p_jump) then
  6913. begin
  6914. hp1 := p_jump;
  6915. if (p_jump.typ in [ait_align]) then
  6916. SkipAligns(p_jump, p_jump);
  6917. { CollapseZeroDistJump will be set to the label after the
  6918. jump if it optimises, whether or not it's live or dead }
  6919. if (p_jump.typ in [ait_label]) and
  6920. not (tai_label(p_jump).labsym.is_used) then
  6921. GetNextInstruction(p_jump, p_jump);
  6922. end;
  6923. TransferUsedRegs(TmpUsedRegs);
  6924. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6925. if not Assigned(p_jump) or
  6926. (
  6927. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  6928. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  6929. ) then
  6930. begin
  6931. { No more conditional jumps; conditional statement is no longer required }
  6932. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  6933. RemoveCurrentP(p);
  6934. Result := True;
  6935. Exit;
  6936. end;
  6937. hp1 := p_jump;
  6938. Include(OptsToCheck, aoc_ForceNewIteration);
  6939. Continue;
  6940. end;
  6941. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6942. if GetNextInstruction(p_jump, hp2) and
  6943. (
  6944. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  6945. not TempBool
  6946. ) then
  6947. begin
  6948. hp1 := p_jump;
  6949. Include(OptsToCheck, aoc_ForceNewIteration);
  6950. Continue;
  6951. end;
  6952. p_label := nil;
  6953. if Assigned(JumpLabel) then
  6954. p_label := getlabelwithsym(JumpLabel);
  6955. if Assigned(p_label) and
  6956. GetNextInstruction(p_label, p_dist) and
  6957. MatchInstruction(p_dist, A_CMP, []) and
  6958. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6959. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6960. GetNextInstruction(p_dist, hp1_dist) and
  6961. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6962. begin
  6963. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6964. if JumpLabel = JumpLabel_dist then
  6965. { This is an infinite loop }
  6966. Exit;
  6967. { Best optimisation when the first condition is a subset (or equal) of the second }
  6968. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6969. begin
  6970. { Any registers used here will already be allocated }
  6971. if Assigned(JumpLabel) then
  6972. JumpLabel.DecRefs;
  6973. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6974. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6975. Result := True;
  6976. { Don't exit yet. Since p and p_jump haven't actually been
  6977. removed, we can check for more on this iteration }
  6978. end
  6979. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6980. GetNextInstruction(hp1_dist, hp1_label) and
  6981. SkipAligns(hp1_label, hp1_label) and
  6982. (hp1_label.typ = ait_label) then
  6983. begin
  6984. JumpLabel_far := tai_label(hp1_label).labsym;
  6985. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6986. { This is an infinite loop }
  6987. Exit;
  6988. if Assigned(JumpLabel_far) then
  6989. begin
  6990. { In this situation, if the first jump branches, the second one will never,
  6991. branch so change the destination label to after the second jump }
  6992. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6993. if Assigned(JumpLabel) then
  6994. JumpLabel.DecRefs;
  6995. JumpLabel_far.IncRefs;
  6996. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6997. Result := True;
  6998. { Don't exit yet. Since p and p_jump haven't actually been
  6999. removed, we can check for more on this iteration }
  7000. Continue;
  7001. end;
  7002. end;
  7003. end;
  7004. end;
  7005. { Search for:
  7006. cmp ###,###
  7007. j(c1) @lbl1
  7008. cmp ###,### (same as first)
  7009. Remove second cmp
  7010. }
  7011. if GetNextInstruction(p_jump, hp2) and
  7012. (
  7013. (
  7014. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7015. (
  7016. (
  7017. MatchOpType(taicpu(p), top_const, top_reg) and
  7018. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7019. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7020. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7021. ) or (
  7022. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7023. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7024. )
  7025. )
  7026. ) or (
  7027. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7028. MatchOperand(taicpu(p).oper[0]^, 0) and
  7029. (taicpu(p).oper[1]^.typ = top_reg) and
  7030. MatchInstruction(hp2, A_TEST, []) and
  7031. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7032. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7033. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7034. )
  7035. ) then
  7036. begin
  7037. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7038. RemoveInstruction(hp2);
  7039. Result := True;
  7040. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7041. end;
  7042. GetNextInstruction(p_jump, p_jump);
  7043. end;
  7044. if (
  7045. { Don't call GetNextInstruction again if we already have it }
  7046. (hp1 = p_jump) or
  7047. GetNextInstruction(p, hp1)
  7048. ) and
  7049. MatchInstruction(hp1, A_Jcc, []) and
  7050. IsJumpToLabel(taicpu(hp1)) and
  7051. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7052. GetNextInstruction(hp1, hp2) then
  7053. begin
  7054. {
  7055. cmp x, y (or "cmp y, x")
  7056. je @lbl
  7057. mov x, y
  7058. @lbl:
  7059. (x and y can be constants, registers or references)
  7060. Change to:
  7061. mov x, y (x and y will always be equal in the end)
  7062. @lbl: (may beceome a dead label)
  7063. Also:
  7064. cmp x, y (or "cmp y, x")
  7065. jne @lbl
  7066. mov x, y
  7067. @lbl:
  7068. (x and y can be constants, registers or references)
  7069. Change to:
  7070. Absolutely nothing! (Except @lbl if it's still live)
  7071. }
  7072. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7073. (
  7074. (
  7075. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7076. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7077. ) or (
  7078. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7079. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7080. )
  7081. ) and
  7082. GetNextInstruction(hp2, hp1_label) and
  7083. SkipAligns(hp1_label, hp1_label) and
  7084. (hp1_label.typ = ait_label) and
  7085. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7086. begin
  7087. tai_label(hp1_label).labsym.DecRefs;
  7088. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7089. begin
  7090. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7091. RemoveInstruction(hp2);
  7092. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7093. end
  7094. else
  7095. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7096. RemoveInstruction(hp1);
  7097. RemoveCurrentp(p, hp2);
  7098. Result := True;
  7099. Exit;
  7100. end;
  7101. {
  7102. Try to optimise the following:
  7103. cmp $x,### ($x and $y can be registers or constants)
  7104. je @lbl1 (only reference)
  7105. cmp $y,### (### are identical)
  7106. @Lbl:
  7107. sete %reg1
  7108. Change to:
  7109. cmp $x,###
  7110. sete %reg2 (allocate new %reg2)
  7111. cmp $y,###
  7112. sete %reg1
  7113. orb %reg2,%reg1
  7114. (dealloc %reg2)
  7115. This adds an instruction (so don't perform under -Os), but it removes
  7116. a conditional branch.
  7117. }
  7118. if not (cs_opt_size in current_settings.optimizerswitches) and
  7119. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7120. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7121. { The first operand of CMP instructions can only be a register or
  7122. immediate anyway, so no need to check }
  7123. GetNextInstruction(hp2, p_label) and
  7124. (p_label.typ = ait_label) and
  7125. (tai_label(p_label).labsym.getrefs = 1) and
  7126. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7127. GetNextInstruction(p_label, p_dist) and
  7128. MatchInstruction(p_dist, A_SETcc, []) and
  7129. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7130. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7131. begin
  7132. TransferUsedRegs(TmpUsedRegs);
  7133. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7134. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7135. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7136. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7137. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7138. { Get the instruction after the SETcc instruction so we can
  7139. allocate a new register over the entire range }
  7140. GetNextInstruction(p_dist, hp1_dist) then
  7141. begin
  7142. { Register can appear in p if it's not used afterwards, so only
  7143. allocate between hp1 and hp1_dist }
  7144. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7145. if NewReg <> NR_NO then
  7146. begin
  7147. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7148. { Change the jump instruction into a SETcc instruction }
  7149. taicpu(hp1).opcode := A_SETcc;
  7150. taicpu(hp1).opsize := S_B;
  7151. taicpu(hp1).loadreg(0, NewReg);
  7152. { This is now a dead label }
  7153. tai_label(p_label).labsym.decrefs;
  7154. { Prefer adding before the next instruction so the FLAGS
  7155. register is deallicated first }
  7156. AsmL.InsertBefore(
  7157. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7158. hp1_dist
  7159. );
  7160. Result := True;
  7161. { Don't exit yet, as p wasn't changed and hp1, while
  7162. modified, is still intact and might be optimised by the
  7163. SETcc optimisation below }
  7164. end;
  7165. end;
  7166. end;
  7167. end;
  7168. if taicpu(p).oper[0]^.typ = top_const then
  7169. begin
  7170. if (taicpu(p).oper[0]^.val = 0) and
  7171. (taicpu(p).oper[1]^.typ = top_reg) and
  7172. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7173. begin
  7174. hp2 := p;
  7175. FirstMatch := True;
  7176. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7177. anything meaningful once it's converted to "test %reg,%reg";
  7178. additionally, some jumps will always (or never) branch, so
  7179. evaluate every jump immediately following the
  7180. comparison, optimising the conditions if possible.
  7181. Similarly with SETcc... those that are always set to 0 or 1
  7182. are changed to MOV instructions }
  7183. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7184. (
  7185. GetNextInstruction(hp2, hp1) and
  7186. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7187. ) do
  7188. begin
  7189. FirstMatch := False;
  7190. case taicpu(hp1).condition of
  7191. C_B, C_C, C_NAE, C_O:
  7192. { For B/NAE:
  7193. Will never branch since an unsigned integer can never be below zero
  7194. For C/O:
  7195. Result cannot overflow because 0 is being subtracted
  7196. }
  7197. begin
  7198. if taicpu(hp1).opcode = A_Jcc then
  7199. begin
  7200. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7201. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7202. RemoveInstruction(hp1);
  7203. { Since hp1 was deleted, hp2 must not be updated }
  7204. Continue;
  7205. end
  7206. else
  7207. begin
  7208. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7209. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7210. taicpu(hp1).opcode := A_MOV;
  7211. taicpu(hp1).ops := 2;
  7212. taicpu(hp1).condition := C_None;
  7213. taicpu(hp1).opsize := S_B;
  7214. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7215. taicpu(hp1).loadconst(0, 0);
  7216. end;
  7217. end;
  7218. C_BE, C_NA:
  7219. begin
  7220. { Will only branch if equal to zero }
  7221. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7222. taicpu(hp1).condition := C_E;
  7223. end;
  7224. C_A, C_NBE:
  7225. begin
  7226. { Will only branch if not equal to zero }
  7227. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7228. taicpu(hp1).condition := C_NE;
  7229. end;
  7230. C_AE, C_NB, C_NC, C_NO:
  7231. begin
  7232. { Will always branch }
  7233. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7234. if taicpu(hp1).opcode = A_Jcc then
  7235. begin
  7236. MakeUnconditional(taicpu(hp1));
  7237. { Any jumps/set that follow will now be dead code }
  7238. RemoveDeadCodeAfterJump(taicpu(hp1));
  7239. Break;
  7240. end
  7241. else
  7242. begin
  7243. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7244. taicpu(hp1).opcode := A_MOV;
  7245. taicpu(hp1).ops := 2;
  7246. taicpu(hp1).condition := C_None;
  7247. taicpu(hp1).opsize := S_B;
  7248. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7249. taicpu(hp1).loadconst(0, 1);
  7250. end;
  7251. end;
  7252. C_None:
  7253. InternalError(2020012201);
  7254. C_P, C_PE, C_NP, C_PO:
  7255. { We can't handle parity checks and they should never be generated
  7256. after a general-purpose CMP (it's used in some floating-point
  7257. comparisons that don't use CMP) }
  7258. InternalError(2020012202);
  7259. else
  7260. { Zero/Equality, Sign, their complements and all of the
  7261. signed comparisons do not need to be converted };
  7262. end;
  7263. hp2 := hp1;
  7264. end;
  7265. { Convert the instruction to a TEST }
  7266. taicpu(p).opcode := A_TEST;
  7267. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7268. Result := True;
  7269. Exit;
  7270. end
  7271. else if (taicpu(p).oper[0]^.val = 1) and
  7272. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7273. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7274. begin
  7275. { Convert; To:
  7276. cmp $1,r/m cmp $0,r/m
  7277. jl @lbl jle @lbl
  7278. (Also do inverted conditions)
  7279. }
  7280. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7281. taicpu(p).oper[0]^.val := 0;
  7282. if taicpu(hp1).condition in [C_L, C_NGE] then
  7283. taicpu(hp1).condition := C_LE
  7284. else
  7285. taicpu(hp1).condition := C_NLE;
  7286. { If the instruction is now "cmp $0,%reg", convert it to a
  7287. TEST (and effectively do the work of the "cmp $0,%reg" in
  7288. the block above)
  7289. }
  7290. if (taicpu(p).oper[1]^.typ = top_reg) then
  7291. begin
  7292. taicpu(p).opcode := A_TEST;
  7293. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7294. end;
  7295. Result := True;
  7296. Exit;
  7297. end
  7298. else if (taicpu(p).oper[1]^.typ = top_reg)
  7299. {$ifdef x86_64}
  7300. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7301. {$endif x86_64}
  7302. then
  7303. begin
  7304. { cmp register,$8000 neg register
  7305. je target --> jo target
  7306. .... only if register is deallocated before jump.}
  7307. case Taicpu(p).opsize of
  7308. S_B: v:=$80;
  7309. S_W: v:=$8000;
  7310. S_L: v:=qword($80000000);
  7311. else
  7312. internalerror(2013112905);
  7313. end;
  7314. if (taicpu(p).oper[0]^.val=v) and
  7315. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7316. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7317. begin
  7318. TransferUsedRegs(TmpUsedRegs);
  7319. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7320. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7321. begin
  7322. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7323. Taicpu(p).opcode:=A_NEG;
  7324. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7325. Taicpu(p).clearop(1);
  7326. Taicpu(p).ops:=1;
  7327. if Taicpu(hp1).condition=C_E then
  7328. Taicpu(hp1).condition:=C_O
  7329. else
  7330. Taicpu(hp1).condition:=C_NO;
  7331. Result:=true;
  7332. exit;
  7333. end;
  7334. end;
  7335. end;
  7336. end;
  7337. if TrySwapMovCmp(p, hp1) then
  7338. begin
  7339. Result := True;
  7340. Exit;
  7341. end;
  7342. end;
  7343. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7344. var
  7345. hp1: tai;
  7346. begin
  7347. {
  7348. remove the second (v)pxor from
  7349. pxor reg,reg
  7350. ...
  7351. pxor reg,reg
  7352. }
  7353. Result:=false;
  7354. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7355. MatchOpType(taicpu(p),top_reg,top_reg) and
  7356. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7357. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7358. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7359. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7360. begin
  7361. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7362. RemoveInstruction(hp1);
  7363. Result:=true;
  7364. Exit;
  7365. end
  7366. {
  7367. replace
  7368. pxor reg1,reg1
  7369. movapd/s reg1,reg2
  7370. dealloc reg1
  7371. by
  7372. pxor reg2,reg2
  7373. }
  7374. else if GetNextInstruction(p,hp1) and
  7375. { we mix single and double opperations here because we assume that the compiler
  7376. generates vmovapd only after double operations and vmovaps only after single operations }
  7377. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7378. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7379. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7380. (taicpu(p).oper[0]^.typ=top_reg) then
  7381. begin
  7382. TransferUsedRegs(TmpUsedRegs);
  7383. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7384. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7385. begin
  7386. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7387. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7388. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7389. RemoveInstruction(hp1);
  7390. result:=true;
  7391. end;
  7392. end;
  7393. end;
  7394. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7395. var
  7396. hp1: tai;
  7397. begin
  7398. {
  7399. remove the second (v)pxor from
  7400. (v)pxor reg,reg
  7401. ...
  7402. (v)pxor reg,reg
  7403. }
  7404. Result:=false;
  7405. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7406. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7407. begin
  7408. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7409. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7410. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7411. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7412. begin
  7413. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7414. RemoveInstruction(hp1);
  7415. Result:=true;
  7416. Exit;
  7417. end;
  7418. {$ifdef x86_64}
  7419. {
  7420. replace
  7421. vpxor reg1,reg1,reg1
  7422. vmov reg,mem
  7423. by
  7424. movq $0,mem
  7425. }
  7426. if GetNextInstruction(p,hp1) and
  7427. MatchInstruction(hp1,A_VMOVSD,[]) and
  7428. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7429. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7430. begin
  7431. TransferUsedRegs(TmpUsedRegs);
  7432. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7433. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7434. begin
  7435. taicpu(hp1).loadconst(0,0);
  7436. taicpu(hp1).opcode:=A_MOV;
  7437. taicpu(hp1).opsize:=S_Q;
  7438. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7439. RemoveCurrentP(p);
  7440. result:=true;
  7441. Exit;
  7442. end;
  7443. end;
  7444. {$endif x86_64}
  7445. end
  7446. {
  7447. replace
  7448. vpxor reg1,reg1,reg2
  7449. by
  7450. vpxor reg2,reg2,reg2
  7451. to avoid unncessary data dependencies
  7452. }
  7453. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7454. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7455. begin
  7456. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7457. { avoid unncessary data dependency }
  7458. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7459. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7460. result:=true;
  7461. exit;
  7462. end;
  7463. Result:=OptPass1VOP(p);
  7464. end;
  7465. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7466. var
  7467. hp1 : tai;
  7468. begin
  7469. result:=false;
  7470. { replace
  7471. IMul const,%mreg1,%mreg2
  7472. Mov %reg2,%mreg3
  7473. dealloc %mreg3
  7474. by
  7475. Imul const,%mreg1,%mreg23
  7476. }
  7477. if (taicpu(p).ops=3) and
  7478. GetNextInstruction(p,hp1) and
  7479. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7480. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7481. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7482. begin
  7483. TransferUsedRegs(TmpUsedRegs);
  7484. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7485. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7486. begin
  7487. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7488. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7489. RemoveInstruction(hp1);
  7490. result:=true;
  7491. end;
  7492. end;
  7493. end;
  7494. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7495. var
  7496. hp1 : tai;
  7497. begin
  7498. result:=false;
  7499. { replace
  7500. IMul %reg0,%reg1,%reg2
  7501. Mov %reg2,%reg3
  7502. dealloc %reg2
  7503. by
  7504. Imul %reg0,%reg1,%reg3
  7505. }
  7506. if GetNextInstruction(p,hp1) and
  7507. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7508. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7509. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7510. begin
  7511. TransferUsedRegs(TmpUsedRegs);
  7512. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7513. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7514. begin
  7515. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7516. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7517. RemoveInstruction(hp1);
  7518. result:=true;
  7519. end;
  7520. end;
  7521. end;
  7522. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7523. var
  7524. hp1: tai;
  7525. begin
  7526. Result:=false;
  7527. { get rid of
  7528. (v)cvtss2sd reg0,<reg1,>reg2
  7529. (v)cvtss2sd reg2,<reg2,>reg0
  7530. }
  7531. if GetNextInstruction(p,hp1) and
  7532. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7533. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7534. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7535. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7536. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7537. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7538. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7539. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7540. )
  7541. ) then
  7542. begin
  7543. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7544. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7545. begin
  7546. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7547. RemoveCurrentP(p);
  7548. RemoveInstruction(hp1);
  7549. end
  7550. else
  7551. begin
  7552. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7553. if taicpu(hp1).opcode=A_CVTSD2SS then
  7554. begin
  7555. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7556. taicpu(p).opcode:=A_MOVAPS;
  7557. end
  7558. else
  7559. begin
  7560. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7561. taicpu(p).opcode:=A_VMOVAPS;
  7562. end;
  7563. taicpu(p).ops:=2;
  7564. RemoveInstruction(hp1);
  7565. end;
  7566. Result:=true;
  7567. Exit;
  7568. end;
  7569. end;
  7570. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7571. var
  7572. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7573. ThisReg: TRegister;
  7574. begin
  7575. Result := False;
  7576. if not GetNextInstruction(p,hp1) then
  7577. Exit;
  7578. {
  7579. convert
  7580. j<c> .L1
  7581. mov 1,reg
  7582. jmp .L2
  7583. .L1
  7584. mov 0,reg
  7585. .L2
  7586. into
  7587. mov 0,reg
  7588. set<not(c)> reg
  7589. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7590. would destroy the flag contents
  7591. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7592. executed at the same time as a previous comparison.
  7593. set<not(c)> reg
  7594. movzx reg, reg
  7595. }
  7596. if MatchInstruction(hp1,A_MOV,[]) and
  7597. (taicpu(hp1).oper[0]^.typ = top_const) and
  7598. (
  7599. (
  7600. (taicpu(hp1).oper[1]^.typ = top_reg)
  7601. {$ifdef i386}
  7602. { Under i386, ESI, EDI, EBP and ESP
  7603. don't have an 8-bit representation }
  7604. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7605. {$endif i386}
  7606. ) or (
  7607. {$ifdef i386}
  7608. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7609. {$endif i386}
  7610. (taicpu(hp1).opsize = S_B)
  7611. )
  7612. ) and
  7613. GetNextInstruction(hp1,hp2) and
  7614. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7615. GetNextInstruction(hp2,hp3) and
  7616. SkipAligns(hp3, hp3) and
  7617. (hp3.typ=ait_label) and
  7618. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7619. GetNextInstruction(hp3,hp4) and
  7620. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7621. (taicpu(hp4).oper[0]^.typ = top_const) and
  7622. (
  7623. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7624. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7625. ) and
  7626. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7627. GetNextInstruction(hp4,hp5) and
  7628. SkipAligns(hp5, hp5) and
  7629. (hp5.typ=ait_label) and
  7630. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7631. begin
  7632. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7633. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7634. tai_label(hp3).labsym.DecRefs;
  7635. { If this isn't the only reference to the middle label, we can
  7636. still make a saving - only that the first jump and everything
  7637. that follows will remain. }
  7638. if (tai_label(hp3).labsym.getrefs = 0) then
  7639. begin
  7640. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7641. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7642. else
  7643. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7644. { remove jump, first label and second MOV (also catching any aligns) }
  7645. repeat
  7646. if not GetNextInstruction(hp2, hp3) then
  7647. InternalError(2021040810);
  7648. RemoveInstruction(hp2);
  7649. hp2 := hp3;
  7650. until hp2 = hp5;
  7651. { Don't decrement reference count before the removal loop
  7652. above, otherwise GetNextInstruction won't stop on the
  7653. the label }
  7654. tai_label(hp5).labsym.DecRefs;
  7655. end
  7656. else
  7657. begin
  7658. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7659. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7660. else
  7661. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7662. end;
  7663. taicpu(p).opcode:=A_SETcc;
  7664. taicpu(p).opsize:=S_B;
  7665. taicpu(p).is_jmp:=False;
  7666. if taicpu(hp1).opsize=S_B then
  7667. begin
  7668. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7669. if taicpu(hp1).oper[1]^.typ = top_reg then
  7670. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7671. RemoveInstruction(hp1);
  7672. end
  7673. else
  7674. begin
  7675. { Will be a register because the size can't be S_B otherwise }
  7676. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7677. taicpu(p).loadreg(0, ThisReg);
  7678. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7679. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7680. begin
  7681. case taicpu(hp1).opsize of
  7682. S_W:
  7683. taicpu(hp1).opsize := S_BW;
  7684. S_L:
  7685. taicpu(hp1).opsize := S_BL;
  7686. {$ifdef x86_64}
  7687. S_Q:
  7688. begin
  7689. taicpu(hp1).opsize := S_BL;
  7690. { Change the destination register to 32-bit }
  7691. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7692. end;
  7693. {$endif x86_64}
  7694. else
  7695. InternalError(2021040820);
  7696. end;
  7697. taicpu(hp1).opcode := A_MOVZX;
  7698. taicpu(hp1).loadreg(0, ThisReg);
  7699. end
  7700. else
  7701. begin
  7702. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7703. { hp1 is already a MOV instruction with the correct register }
  7704. taicpu(hp1).loadconst(0, 0);
  7705. { Inserting it right before p will guarantee that the flags are also tracked }
  7706. asml.Remove(hp1);
  7707. asml.InsertBefore(hp1, p);
  7708. end;
  7709. end;
  7710. Result:=true;
  7711. exit;
  7712. end
  7713. else if (hp1.typ = ait_label) then
  7714. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7715. end;
  7716. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7717. var
  7718. hp1, hp2, hp3: tai;
  7719. SourceRef, TargetRef: TReference;
  7720. CurrentReg: TRegister;
  7721. begin
  7722. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7723. if not UseAVX then
  7724. InternalError(2021100501);
  7725. Result := False;
  7726. { Look for the following to simplify:
  7727. vmovdqa/u x(mem1), %xmmreg
  7728. vmovdqa/u %xmmreg, y(mem2)
  7729. vmovdqa/u x+16(mem1), %xmmreg
  7730. vmovdqa/u %xmmreg, y+16(mem2)
  7731. Change to:
  7732. vmovdqa/u x(mem1), %ymmreg
  7733. vmovdqa/u %ymmreg, y(mem2)
  7734. vpxor %ymmreg, %ymmreg, %ymmreg
  7735. ( The VPXOR instruction is to zero the upper half, thus removing the
  7736. need to call the potentially expensive VZEROUPPER instruction. Other
  7737. peephole optimisations can remove VPXOR if it's unnecessary )
  7738. }
  7739. TransferUsedRegs(TmpUsedRegs);
  7740. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7741. { NOTE: In the optimisations below, if the references dictate that an
  7742. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7743. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7744. if (taicpu(p).opsize = S_XMM) and
  7745. MatchOpType(taicpu(p), top_ref, top_reg) and
  7746. GetNextInstruction(p, hp1) and
  7747. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7748. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7749. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7750. begin
  7751. SourceRef := taicpu(p).oper[0]^.ref^;
  7752. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7753. if GetNextInstruction(hp1, hp2) and
  7754. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7755. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7756. begin
  7757. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7758. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7759. Inc(SourceRef.offset, 16);
  7760. { Reuse the register in the first block move }
  7761. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7762. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7763. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7764. begin
  7765. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7766. Inc(TargetRef.offset, 16);
  7767. if GetNextInstruction(hp2, hp3) and
  7768. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7769. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7770. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7771. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7772. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7773. begin
  7774. { Update the register tracking to the new size }
  7775. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7776. { Remember that the offsets are 16 ahead }
  7777. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7778. if not (
  7779. ((SourceRef.offset mod 32) = 16) and
  7780. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7781. ) then
  7782. taicpu(p).opcode := A_VMOVDQU;
  7783. taicpu(p).opsize := S_YMM;
  7784. taicpu(p).oper[1]^.reg := CurrentReg;
  7785. if not (
  7786. ((TargetRef.offset mod 32) = 16) and
  7787. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7788. ) then
  7789. taicpu(hp1).opcode := A_VMOVDQU;
  7790. taicpu(hp1).opsize := S_YMM;
  7791. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7792. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7793. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7794. if (pi_uses_ymm in current_procinfo.flags) then
  7795. RemoveInstruction(hp2)
  7796. else
  7797. begin
  7798. taicpu(hp2).opcode := A_VPXOR;
  7799. taicpu(hp2).opsize := S_YMM;
  7800. taicpu(hp2).loadreg(0, CurrentReg);
  7801. taicpu(hp2).loadreg(1, CurrentReg);
  7802. taicpu(hp2).loadreg(2, CurrentReg);
  7803. taicpu(hp2).ops := 3;
  7804. end;
  7805. RemoveInstruction(hp3);
  7806. Result := True;
  7807. Exit;
  7808. end;
  7809. end
  7810. else
  7811. begin
  7812. { See if the next references are 16 less rather than 16 greater }
  7813. Dec(SourceRef.offset, 32); { -16 the other way }
  7814. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7815. begin
  7816. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7817. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7818. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7819. GetNextInstruction(hp2, hp3) and
  7820. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7821. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7822. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7823. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7824. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7825. begin
  7826. { Update the register tracking to the new size }
  7827. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7828. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7829. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7830. if not(
  7831. ((SourceRef.offset mod 32) = 0) and
  7832. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7833. ) then
  7834. taicpu(hp2).opcode := A_VMOVDQU;
  7835. taicpu(hp2).opsize := S_YMM;
  7836. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7837. if not (
  7838. ((TargetRef.offset mod 32) = 0) and
  7839. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7840. ) then
  7841. taicpu(hp3).opcode := A_VMOVDQU;
  7842. taicpu(hp3).opsize := S_YMM;
  7843. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7844. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7845. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7846. if (pi_uses_ymm in current_procinfo.flags) then
  7847. RemoveInstruction(hp1)
  7848. else
  7849. begin
  7850. taicpu(hp1).opcode := A_VPXOR;
  7851. taicpu(hp1).opsize := S_YMM;
  7852. taicpu(hp1).loadreg(0, CurrentReg);
  7853. taicpu(hp1).loadreg(1, CurrentReg);
  7854. taicpu(hp1).loadreg(2, CurrentReg);
  7855. taicpu(hp1).ops := 3;
  7856. Asml.Remove(hp1);
  7857. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7858. end;
  7859. RemoveCurrentP(p, hp2);
  7860. Result := True;
  7861. Exit;
  7862. end;
  7863. end;
  7864. end;
  7865. end;
  7866. end;
  7867. end;
  7868. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7869. var
  7870. hp2, hp3, first_assignment: tai;
  7871. IncCount, OperIdx: Integer;
  7872. OrigLabel: TAsmLabel;
  7873. begin
  7874. Count := 0;
  7875. Result := False;
  7876. first_assignment := nil;
  7877. if (LoopCount >= 20) then
  7878. begin
  7879. { Guard against infinite loops }
  7880. Exit;
  7881. end;
  7882. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7883. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7884. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7885. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7886. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7887. Exit;
  7888. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7889. {
  7890. change
  7891. jmp .L1
  7892. ...
  7893. .L1:
  7894. mov ##, ## ( multiple movs possible )
  7895. jmp/ret
  7896. into
  7897. mov ##, ##
  7898. jmp/ret
  7899. }
  7900. if not Assigned(hp1) then
  7901. begin
  7902. hp1 := GetLabelWithSym(OrigLabel);
  7903. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7904. Exit;
  7905. end;
  7906. hp2 := hp1;
  7907. while Assigned(hp2) do
  7908. begin
  7909. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7910. SkipLabels(hp2,hp2);
  7911. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7912. Break;
  7913. case taicpu(hp2).opcode of
  7914. A_MOVSD:
  7915. begin
  7916. if taicpu(hp2).ops = 0 then
  7917. { Wrong MOVSD }
  7918. Break;
  7919. Inc(Count);
  7920. if Count >= 5 then
  7921. { Too many to be worthwhile }
  7922. Break;
  7923. GetNextInstruction(hp2, hp2);
  7924. Continue;
  7925. end;
  7926. A_MOV,
  7927. A_MOVD,
  7928. A_MOVQ,
  7929. A_MOVSX,
  7930. {$ifdef x86_64}
  7931. A_MOVSXD,
  7932. {$endif x86_64}
  7933. A_MOVZX,
  7934. A_MOVAPS,
  7935. A_MOVUPS,
  7936. A_MOVSS,
  7937. A_MOVAPD,
  7938. A_MOVUPD,
  7939. A_MOVDQA,
  7940. A_MOVDQU,
  7941. A_VMOVSS,
  7942. A_VMOVAPS,
  7943. A_VMOVUPS,
  7944. A_VMOVSD,
  7945. A_VMOVAPD,
  7946. A_VMOVUPD,
  7947. A_VMOVDQA,
  7948. A_VMOVDQU:
  7949. begin
  7950. Inc(Count);
  7951. if Count >= 5 then
  7952. { Too many to be worthwhile }
  7953. Break;
  7954. GetNextInstruction(hp2, hp2);
  7955. Continue;
  7956. end;
  7957. A_JMP:
  7958. begin
  7959. { Guard against infinite loops }
  7960. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7961. Exit;
  7962. { Analyse this jump first in case it also duplicates assignments }
  7963. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7964. begin
  7965. { Something did change! }
  7966. Result := True;
  7967. Inc(Count, IncCount);
  7968. if Count >= 5 then
  7969. begin
  7970. { Too many to be worthwhile }
  7971. Exit;
  7972. end;
  7973. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7974. Break;
  7975. end;
  7976. Result := True;
  7977. Break;
  7978. end;
  7979. A_RET:
  7980. begin
  7981. Result := True;
  7982. Break;
  7983. end;
  7984. else
  7985. Break;
  7986. end;
  7987. end;
  7988. if Result then
  7989. begin
  7990. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7991. if Count = 0 then
  7992. begin
  7993. Result := False;
  7994. Exit;
  7995. end;
  7996. hp3 := p;
  7997. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7998. while True do
  7999. begin
  8000. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  8001. SkipLabels(hp1,hp1);
  8002. if (hp1.typ <> ait_instruction) then
  8003. InternalError(2021040720);
  8004. case taicpu(hp1).opcode of
  8005. A_JMP:
  8006. begin
  8007. { Change the original jump to the new destination }
  8008. OrigLabel.decrefs;
  8009. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8010. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8011. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8012. if not Assigned(first_assignment) then
  8013. InternalError(2021040810)
  8014. else
  8015. p := first_assignment;
  8016. Exit;
  8017. end;
  8018. A_RET:
  8019. begin
  8020. { Now change the jump into a RET instruction }
  8021. ConvertJumpToRET(p, hp1);
  8022. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8023. if not Assigned(first_assignment) then
  8024. InternalError(2021040811)
  8025. else
  8026. p := first_assignment;
  8027. Exit;
  8028. end;
  8029. else
  8030. begin
  8031. { Duplicate the MOV instruction }
  8032. hp3:=tai(hp1.getcopy);
  8033. if first_assignment = nil then
  8034. first_assignment := hp3;
  8035. asml.InsertBefore(hp3, p);
  8036. { Make sure the compiler knows about any final registers written here }
  8037. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8038. with taicpu(hp3).oper[OperIdx]^ do
  8039. begin
  8040. case typ of
  8041. top_ref:
  8042. begin
  8043. if (ref^.base <> NR_NO) and
  8044. (getsupreg(ref^.base) <> RS_ESP) and
  8045. (getsupreg(ref^.base) <> RS_EBP)
  8046. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8047. then
  8048. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8049. if (ref^.index <> NR_NO) and
  8050. (getsupreg(ref^.index) <> RS_ESP) and
  8051. (getsupreg(ref^.index) <> RS_EBP)
  8052. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8053. (ref^.index <> ref^.base) then
  8054. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8055. end;
  8056. top_reg:
  8057. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8058. else
  8059. ;
  8060. end;
  8061. end;
  8062. end;
  8063. end;
  8064. if not GetNextInstruction(hp1, hp1) then
  8065. { Should have dropped out earlier }
  8066. InternalError(2021040710);
  8067. end;
  8068. end;
  8069. end;
  8070. const
  8071. WriteOp: array[0..3] of set of TInsChange = (
  8072. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8073. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8074. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8075. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8076. RegWriteFlags: array[0..7] of set of TInsChange = (
  8077. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8078. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8079. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8080. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8081. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8082. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8083. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8084. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8085. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8086. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8087. var
  8088. hp2: tai;
  8089. X: Integer;
  8090. begin
  8091. { If we have something like:
  8092. op ###,###
  8093. mov ###,###
  8094. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8095. interfere in regards to what they write to.
  8096. NOTE: p must be a 2-operand instruction
  8097. }
  8098. Result := False;
  8099. if (hp1.typ <> ait_instruction) or
  8100. taicpu(hp1).is_jmp or
  8101. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8102. Exit;
  8103. { NOP is a pipeline fence, likely marking the beginning of the function
  8104. epilogue, so drop out. Similarly, drop out if POP or RET are
  8105. encountered }
  8106. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8107. Exit;
  8108. if (taicpu(hp1).opcode = A_MOVSD) and
  8109. (taicpu(hp1).ops = 0) then
  8110. { Wrong MOVSD }
  8111. Exit;
  8112. { Check for writes to specific registers first }
  8113. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8114. for X := 0 to 7 do
  8115. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8116. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8117. Exit;
  8118. for X := 0 to taicpu(hp1).ops - 1 do
  8119. begin
  8120. { Check to see if this operand writes to something }
  8121. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8122. { And matches something in the CMP/TEST instruction }
  8123. (
  8124. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8125. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8126. (
  8127. { If it's a register, make sure the register written to doesn't
  8128. appear in the cmp instruction as part of a reference }
  8129. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8130. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8131. )
  8132. ) then
  8133. Exit;
  8134. end;
  8135. { Check p to make sure it doesn't write to something that affects hp1 }
  8136. { Check for writes to specific registers first }
  8137. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8138. for X := 0 to 7 do
  8139. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8140. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8141. Exit;
  8142. for X := 0 to taicpu(p).ops - 1 do
  8143. begin
  8144. { Check to see if this operand writes to something }
  8145. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8146. { And matches something in hp1 }
  8147. (taicpu(p).oper[X]^.typ = top_reg) and
  8148. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8149. Exit;
  8150. end;
  8151. { The instruction can be safely moved }
  8152. asml.Remove(hp1);
  8153. { Try to insert after the last instructions where the FLAGS register is not
  8154. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8155. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8156. asml.InsertBefore(hp1, hp2)
  8157. { Failing that, try to insert after the last instructions where the
  8158. FLAGS register is not yet in use }
  8159. else if GetLastInstruction(p, hp2) and
  8160. (
  8161. (hp2.typ <> ait_instruction) or
  8162. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8163. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8164. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8165. ) then
  8166. asml.InsertAfter(hp1, hp2)
  8167. else
  8168. { Note, if p.Previous is nil (even if it should logically never be the
  8169. case), FindRegAllocBackward immediately exits with False and so we
  8170. safely land here (we can't just pass p because FindRegAllocBackward
  8171. immediately exits on an instruction). [Kit] }
  8172. asml.InsertBefore(hp1, p);
  8173. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8174. { We can't trust UsedRegs because we're looking backwards, although we
  8175. know the registers are allocated after p at the very least, so manually
  8176. create tai_regalloc objects if needed }
  8177. for X := 0 to taicpu(hp1).ops - 1 do
  8178. case taicpu(hp1).oper[X]^.typ of
  8179. top_reg:
  8180. begin
  8181. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8182. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8183. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8184. end;
  8185. top_ref:
  8186. begin
  8187. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8188. begin
  8189. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8190. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8191. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8192. end;
  8193. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8194. begin
  8195. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8196. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8197. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8198. end;
  8199. end;
  8200. else
  8201. ;
  8202. end;
  8203. Result := True;
  8204. end;
  8205. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8206. var
  8207. hp2: tai;
  8208. X: Integer;
  8209. begin
  8210. { If we have something like:
  8211. cmp ###,%reg1
  8212. mov 0,%reg2
  8213. And no modified registers are shared, move the instruction to before
  8214. the comparison as this means it can be optimised without worrying
  8215. about the FLAGS register. (CMP/MOV is generated by
  8216. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8217. As long as the second instruction doesn't use the flags or one of the
  8218. registers used by CMP or TEST (also check any references that use the
  8219. registers), then it can be moved prior to the comparison.
  8220. }
  8221. Result := False;
  8222. if not TrySwapMovOp(p, hp1) then
  8223. Exit;
  8224. if taicpu(hp1).opcode = A_LEA then
  8225. { The flags will be overwritten by the CMP/TEST instruction }
  8226. ConvertLEA(taicpu(hp1));
  8227. Result := True;
  8228. { Can we move it one further back? }
  8229. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8230. { Check to see if CMP/TEST is a comparison against zero }
  8231. (
  8232. (
  8233. (taicpu(p).opcode = A_CMP) and
  8234. MatchOperand(taicpu(p).oper[0]^, 0)
  8235. ) or
  8236. (
  8237. (taicpu(p).opcode = A_TEST) and
  8238. (
  8239. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8240. MatchOperand(taicpu(p).oper[0]^, -1)
  8241. )
  8242. )
  8243. ) and
  8244. { These instructions set the zero flag if the result is zero }
  8245. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8246. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8247. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8248. TrySwapMovOp(hp2, hp1);
  8249. end;
  8250. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8251. function IsXCHGAcceptable: Boolean; inline;
  8252. begin
  8253. { Always accept if optimising for size }
  8254. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8255. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8256. than 3, so it becomes a saving compared to three MOVs with two of
  8257. them able to execute simultaneously. [Kit] }
  8258. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8259. end;
  8260. var
  8261. NewRef: TReference;
  8262. hp1, hp2, hp3, hp4: Tai;
  8263. {$ifndef x86_64}
  8264. OperIdx: Integer;
  8265. {$endif x86_64}
  8266. NewInstr : Taicpu;
  8267. NewAligh : Tai_align;
  8268. DestLabel: TAsmLabel;
  8269. TempTracking: TAllUsedRegs;
  8270. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8271. var
  8272. NextInstr: tai;
  8273. begin
  8274. Result := False;
  8275. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8276. if not GetNextInstruction(InputInstr, NextInstr) or
  8277. (
  8278. { The FLAGS register isn't always tracked properly, so do not
  8279. perform this optimisation if a conditional statement follows }
  8280. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8281. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8282. ) then
  8283. begin
  8284. reference_reset(NewRef, 1, []);
  8285. NewRef.base := taicpu(p).oper[0]^.reg;
  8286. NewRef.scalefactor := 1;
  8287. if taicpu(InputInstr).opcode = A_ADD then
  8288. begin
  8289. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8290. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8291. end
  8292. else
  8293. begin
  8294. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8295. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8296. end;
  8297. taicpu(p).opcode := A_LEA;
  8298. taicpu(p).loadref(0, NewRef);
  8299. RemoveInstruction(InputInstr);
  8300. Result := True;
  8301. end;
  8302. end;
  8303. begin
  8304. Result:=false;
  8305. { This optimisation adds an instruction, so only do it for speed }
  8306. if not (cs_opt_size in current_settings.optimizerswitches) and
  8307. MatchOpType(taicpu(p), top_const, top_reg) and
  8308. (taicpu(p).oper[0]^.val = 0) then
  8309. begin
  8310. { To avoid compiler warning }
  8311. DestLabel := nil;
  8312. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8313. InternalError(2021040750);
  8314. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8315. Exit;
  8316. case hp1.typ of
  8317. ait_align,
  8318. ait_label:
  8319. begin
  8320. { Change:
  8321. mov $0,%reg mov $0,%reg
  8322. @Lbl1: @Lbl1:
  8323. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8324. je @Lbl2 jne @Lbl2
  8325. To: To:
  8326. mov $0,%reg mov $0,%reg
  8327. jmp @Lbl2 jmp @Lbl3
  8328. (align) (align)
  8329. @Lbl1: @Lbl1:
  8330. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8331. je @Lbl2 je @Lbl2
  8332. @Lbl3: <-- Only if label exists
  8333. (Not if it's optimised for size)
  8334. }
  8335. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8336. Exit;
  8337. if (hp2.typ = ait_instruction) and
  8338. (
  8339. { Register sizes must exactly match }
  8340. (
  8341. (taicpu(hp2).opcode = A_CMP) and
  8342. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8343. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8344. ) or (
  8345. (taicpu(hp2).opcode = A_TEST) and
  8346. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8347. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8348. )
  8349. ) and GetNextInstruction(hp2, hp3) and
  8350. (hp3.typ = ait_instruction) and
  8351. (taicpu(hp3).opcode = A_JCC) and
  8352. (taicpu(hp3).oper[0]^.typ=top_ref) and (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and (taicpu(hp3).oper[0]^.ref^.base=NR_NO) and
  8353. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8354. begin
  8355. { Check condition of jump }
  8356. { Always true? }
  8357. if condition_in(C_E, taicpu(hp3).condition) then
  8358. begin
  8359. { Copy label symbol and obtain matching label entry for the
  8360. conditional jump, as this will be our destination}
  8361. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8362. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8363. Result := True;
  8364. end
  8365. { Always false? }
  8366. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8367. begin
  8368. { This is only worth it if there's a jump to take }
  8369. case hp2.typ of
  8370. ait_instruction:
  8371. begin
  8372. if taicpu(hp2).opcode = A_JMP then
  8373. begin
  8374. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8375. { An unconditional jump follows the conditional jump which will always be false,
  8376. so use this jump's destination for the new jump }
  8377. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8378. Result := True;
  8379. end
  8380. else if taicpu(hp2).opcode = A_JCC then
  8381. begin
  8382. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8383. if condition_in(C_E, taicpu(hp2).condition) then
  8384. begin
  8385. { A second conditional jump follows the conditional jump which will always be false,
  8386. while the second jump is always True, so use this jump's destination for the new jump }
  8387. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8388. Result := True;
  8389. end;
  8390. { Don't risk it if the jump isn't always true (Result remains False) }
  8391. end;
  8392. end;
  8393. else
  8394. { If anything else don't optimise };
  8395. end;
  8396. end;
  8397. if Result then
  8398. begin
  8399. { Just so we have something to insert as a paremeter}
  8400. reference_reset(NewRef, 1, []);
  8401. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8402. { Now actually load the correct parameter (this also
  8403. increases the reference count) }
  8404. NewInstr.loadsymbol(0, DestLabel, 0);
  8405. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8406. begin
  8407. { Get instruction before original label (may not be p under -O3) }
  8408. if not GetLastInstruction(hp1, hp2) then
  8409. { Shouldn't fail here }
  8410. InternalError(2021040701);
  8411. { Before the aligns too }
  8412. while (hp2.typ = ait_align) do
  8413. if not GetLastInstruction(hp2, hp2) then
  8414. { Shouldn't fail here }
  8415. InternalError(2021040702);
  8416. end
  8417. else
  8418. hp2 := p;
  8419. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8420. AsmL.InsertAfter(NewInstr, hp2);
  8421. { Add new alignment field }
  8422. (* AsmL.InsertAfter(
  8423. cai_align.create_max(
  8424. current_settings.alignment.jumpalign,
  8425. current_settings.alignment.jumpalignskipmax
  8426. ),
  8427. NewInstr
  8428. ); *)
  8429. end;
  8430. Exit;
  8431. end;
  8432. end;
  8433. else
  8434. ;
  8435. end;
  8436. end;
  8437. if not GetNextInstruction(p, hp1) then
  8438. Exit;
  8439. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8440. and DoMovCmpMemOpt(p, hp1, True) then
  8441. begin
  8442. Result := True;
  8443. Exit;
  8444. end
  8445. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8446. begin
  8447. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8448. further, but we can't just put this jump optimisation in pass 1
  8449. because it tends to perform worse when conditional jumps are
  8450. nearby (e.g. when converting CMOV instructions). [Kit] }
  8451. CopyUsedRegs(TempTracking);
  8452. UpdateUsedRegs(tai(p.Next));
  8453. if OptPass2JMP(hp1) then
  8454. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8455. Result := OptPass1MOV(p);
  8456. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8457. returned True and the instruction is still a MOV, thus checking
  8458. the optimisations below }
  8459. { If OptPass2JMP returned False, no optimisations were done to
  8460. the jump and there are no further optimisations that can be done
  8461. to the MOV instruction on this pass }
  8462. { Restore register state }
  8463. RestoreUsedRegs(TempTracking);
  8464. ReleaseUsedRegs(TempTracking);
  8465. end
  8466. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8467. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8468. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8469. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8470. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8471. begin
  8472. { Change:
  8473. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8474. addl/q $x,%reg2 subl/q $x,%reg2
  8475. To:
  8476. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8477. }
  8478. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8479. { be lazy, checking separately for sub would be slightly better }
  8480. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8481. begin
  8482. TransferUsedRegs(TmpUsedRegs);
  8483. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8484. if TryMovArith2Lea(hp1) then
  8485. begin
  8486. Result := True;
  8487. Exit;
  8488. end
  8489. end
  8490. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8491. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8492. { Same as above, but also adds or subtracts to %reg2 in between.
  8493. It's still valid as long as the flags aren't in use }
  8494. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8495. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8496. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8497. { be lazy, checking separately for sub would be slightly better }
  8498. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8499. begin
  8500. TransferUsedRegs(TmpUsedRegs);
  8501. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8502. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8503. if TryMovArith2Lea(hp2) then
  8504. begin
  8505. Result := True;
  8506. Exit;
  8507. end;
  8508. end;
  8509. end
  8510. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8511. {$ifdef x86_64}
  8512. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8513. {$else x86_64}
  8514. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8515. {$endif x86_64}
  8516. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8517. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8518. { mov reg1, reg2 mov reg1, reg2
  8519. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8520. begin
  8521. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8522. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8523. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8524. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8525. TransferUsedRegs(TmpUsedRegs);
  8526. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8527. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8528. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8529. then
  8530. begin
  8531. RemoveCurrentP(p, hp1);
  8532. Result:=true;
  8533. end;
  8534. exit;
  8535. end
  8536. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8537. IsXCHGAcceptable and
  8538. { XCHG doesn't support 8-byte registers }
  8539. (taicpu(p).opsize <> S_B) and
  8540. MatchInstruction(hp1, A_MOV, []) and
  8541. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8542. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8543. GetNextInstruction(hp1, hp2) and
  8544. MatchInstruction(hp2, A_MOV, []) and
  8545. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8546. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8547. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8548. begin
  8549. { mov %reg1,%reg2
  8550. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8551. mov %reg2,%reg3
  8552. (%reg2 not used afterwards)
  8553. Note that xchg takes 3 cycles to execute, and generally mov's take
  8554. only one cycle apiece, but the first two mov's can be executed in
  8555. parallel, only taking 2 cycles overall. Older processors should
  8556. therefore only optimise for size. [Kit]
  8557. }
  8558. TransferUsedRegs(TmpUsedRegs);
  8559. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8560. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8561. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8562. begin
  8563. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8564. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8565. taicpu(hp1).opcode := A_XCHG;
  8566. RemoveCurrentP(p, hp1);
  8567. RemoveInstruction(hp2);
  8568. Result := True;
  8569. Exit;
  8570. end;
  8571. end
  8572. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8573. MatchInstruction(hp1, A_SAR, []) then
  8574. begin
  8575. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8576. begin
  8577. { the use of %edx also covers the opsize being S_L }
  8578. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8579. begin
  8580. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8581. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8582. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8583. begin
  8584. { Change:
  8585. movl %eax,%edx
  8586. sarl $31,%edx
  8587. To:
  8588. cltd
  8589. }
  8590. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8591. RemoveInstruction(hp1);
  8592. taicpu(p).opcode := A_CDQ;
  8593. taicpu(p).opsize := S_NO;
  8594. taicpu(p).clearop(1);
  8595. taicpu(p).clearop(0);
  8596. taicpu(p).ops:=0;
  8597. Result := True;
  8598. end
  8599. else if (cs_opt_size in current_settings.optimizerswitches) and
  8600. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8601. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8602. begin
  8603. { Change:
  8604. movl %edx,%eax
  8605. sarl $31,%edx
  8606. To:
  8607. movl %edx,%eax
  8608. cltd
  8609. Note that this creates a dependency between the two instructions,
  8610. so only perform if optimising for size.
  8611. }
  8612. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8613. taicpu(hp1).opcode := A_CDQ;
  8614. taicpu(hp1).opsize := S_NO;
  8615. taicpu(hp1).clearop(1);
  8616. taicpu(hp1).clearop(0);
  8617. taicpu(hp1).ops:=0;
  8618. end;
  8619. {$ifndef x86_64}
  8620. end
  8621. { Don't bother if CMOV is supported, because a more optimal
  8622. sequence would have been generated for the Abs() intrinsic }
  8623. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8624. { the use of %eax also covers the opsize being S_L }
  8625. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8626. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8627. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8628. GetNextInstruction(hp1, hp2) and
  8629. MatchInstruction(hp2, A_XOR, [S_L]) and
  8630. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8631. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8632. GetNextInstruction(hp2, hp3) and
  8633. MatchInstruction(hp3, A_SUB, [S_L]) and
  8634. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8635. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8636. begin
  8637. { Change:
  8638. movl %eax,%edx
  8639. sarl $31,%eax
  8640. xorl %eax,%edx
  8641. subl %eax,%edx
  8642. (Instruction that uses %edx)
  8643. (%eax deallocated)
  8644. (%edx deallocated)
  8645. To:
  8646. cltd
  8647. xorl %edx,%eax <-- Note the registers have swapped
  8648. subl %edx,%eax
  8649. (Instruction that uses %eax) <-- %eax rather than %edx
  8650. }
  8651. TransferUsedRegs(TmpUsedRegs);
  8652. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8653. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8654. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8655. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8656. begin
  8657. if GetNextInstruction(hp3, hp4) and
  8658. not RegModifiedByInstruction(NR_EDX, hp4) and
  8659. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8660. begin
  8661. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8662. taicpu(p).opcode := A_CDQ;
  8663. taicpu(p).clearop(1);
  8664. taicpu(p).clearop(0);
  8665. taicpu(p).ops:=0;
  8666. RemoveInstruction(hp1);
  8667. taicpu(hp2).loadreg(0, NR_EDX);
  8668. taicpu(hp2).loadreg(1, NR_EAX);
  8669. taicpu(hp3).loadreg(0, NR_EDX);
  8670. taicpu(hp3).loadreg(1, NR_EAX);
  8671. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8672. { Convert references in the following instruction (hp4) from %edx to %eax }
  8673. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8674. with taicpu(hp4).oper[OperIdx]^ do
  8675. case typ of
  8676. top_reg:
  8677. if getsupreg(reg) = RS_EDX then
  8678. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8679. top_ref:
  8680. begin
  8681. if getsupreg(reg) = RS_EDX then
  8682. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8683. if getsupreg(reg) = RS_EDX then
  8684. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8685. end;
  8686. else
  8687. ;
  8688. end;
  8689. end;
  8690. end;
  8691. {$else x86_64}
  8692. end;
  8693. end
  8694. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8695. { the use of %rdx also covers the opsize being S_Q }
  8696. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8697. begin
  8698. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8699. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8700. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8701. begin
  8702. { Change:
  8703. movq %rax,%rdx
  8704. sarq $63,%rdx
  8705. To:
  8706. cqto
  8707. }
  8708. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8709. RemoveInstruction(hp1);
  8710. taicpu(p).opcode := A_CQO;
  8711. taicpu(p).opsize := S_NO;
  8712. taicpu(p).clearop(1);
  8713. taicpu(p).clearop(0);
  8714. taicpu(p).ops:=0;
  8715. Result := True;
  8716. end
  8717. else if (cs_opt_size in current_settings.optimizerswitches) and
  8718. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8719. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8720. begin
  8721. { Change:
  8722. movq %rdx,%rax
  8723. sarq $63,%rdx
  8724. To:
  8725. movq %rdx,%rax
  8726. cqto
  8727. Note that this creates a dependency between the two instructions,
  8728. so only perform if optimising for size.
  8729. }
  8730. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8731. taicpu(hp1).opcode := A_CQO;
  8732. taicpu(hp1).opsize := S_NO;
  8733. taicpu(hp1).clearop(1);
  8734. taicpu(hp1).clearop(0);
  8735. taicpu(hp1).ops:=0;
  8736. {$endif x86_64}
  8737. end;
  8738. end;
  8739. end
  8740. else if MatchInstruction(hp1, A_MOV, []) and
  8741. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8742. { Though "GetNextInstruction" could be factored out, along with
  8743. the instructions that depend on hp2, it is an expensive call that
  8744. should be delayed for as long as possible, hence we do cheaper
  8745. checks first that are likely to be False. [Kit] }
  8746. begin
  8747. if (
  8748. (
  8749. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8750. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8751. (
  8752. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8753. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8754. )
  8755. ) or
  8756. (
  8757. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8758. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8759. (
  8760. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8761. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8762. )
  8763. )
  8764. ) and
  8765. GetNextInstruction(hp1, hp2) and
  8766. MatchInstruction(hp2, A_SAR, []) and
  8767. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8768. begin
  8769. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8770. begin
  8771. { Change:
  8772. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8773. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8774. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8775. To:
  8776. movl r/m,%eax <- Note the change in register
  8777. cltd
  8778. }
  8779. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8780. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8781. taicpu(p).loadreg(1, NR_EAX);
  8782. taicpu(hp1).opcode := A_CDQ;
  8783. taicpu(hp1).clearop(1);
  8784. taicpu(hp1).clearop(0);
  8785. taicpu(hp1).ops:=0;
  8786. RemoveInstruction(hp2);
  8787. (*
  8788. {$ifdef x86_64}
  8789. end
  8790. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8791. { This code sequence does not get generated - however it might become useful
  8792. if and when 128-bit signed integer types make an appearance, so the code
  8793. is kept here for when it is eventually needed. [Kit] }
  8794. (
  8795. (
  8796. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8797. (
  8798. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8799. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8800. )
  8801. ) or
  8802. (
  8803. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8804. (
  8805. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8806. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8807. )
  8808. )
  8809. ) and
  8810. GetNextInstruction(hp1, hp2) and
  8811. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8812. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8813. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8814. begin
  8815. { Change:
  8816. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8817. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8818. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8819. To:
  8820. movq r/m,%rax <- Note the change in register
  8821. cqto
  8822. }
  8823. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8824. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8825. taicpu(p).loadreg(1, NR_RAX);
  8826. taicpu(hp1).opcode := A_CQO;
  8827. taicpu(hp1).clearop(1);
  8828. taicpu(hp1).clearop(0);
  8829. taicpu(hp1).ops:=0;
  8830. RemoveInstruction(hp2);
  8831. {$endif x86_64}
  8832. *)
  8833. end;
  8834. end;
  8835. {$ifdef x86_64}
  8836. end
  8837. else if (taicpu(p).opsize = S_L) and
  8838. (taicpu(p).oper[1]^.typ = top_reg) and
  8839. (
  8840. MatchInstruction(hp1, A_MOV,[]) and
  8841. (taicpu(hp1).opsize = S_L) and
  8842. (taicpu(hp1).oper[1]^.typ = top_reg)
  8843. ) and (
  8844. GetNextInstruction(hp1, hp2) and
  8845. (tai(hp2).typ=ait_instruction) and
  8846. (taicpu(hp2).opsize = S_Q) and
  8847. (
  8848. (
  8849. MatchInstruction(hp2, A_ADD,[]) and
  8850. (taicpu(hp2).opsize = S_Q) and
  8851. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8852. (
  8853. (
  8854. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8855. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8856. ) or (
  8857. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8858. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8859. )
  8860. )
  8861. ) or (
  8862. MatchInstruction(hp2, A_LEA,[]) and
  8863. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8864. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8865. (
  8866. (
  8867. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8868. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8869. ) or (
  8870. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8871. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8872. )
  8873. ) and (
  8874. (
  8875. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8876. ) or (
  8877. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8878. )
  8879. )
  8880. )
  8881. )
  8882. ) and (
  8883. GetNextInstruction(hp2, hp3) and
  8884. MatchInstruction(hp3, A_SHR,[]) and
  8885. (taicpu(hp3).opsize = S_Q) and
  8886. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8887. (taicpu(hp3).oper[0]^.val = 1) and
  8888. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8889. ) then
  8890. begin
  8891. { Change movl x, reg1d movl x, reg1d
  8892. movl y, reg2d movl y, reg2d
  8893. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8894. shrq $1, reg1q shrq $1, reg1q
  8895. ( reg1d and reg2d can be switched around in the first two instructions )
  8896. To movl x, reg1d
  8897. addl y, reg1d
  8898. rcrl $1, reg1d
  8899. This corresponds to the common expression (x + y) shr 1, where
  8900. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  8901. smaller code, but won't account for x + y causing an overflow). [Kit]
  8902. }
  8903. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  8904. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8905. { Change first MOV command to have the same register as the final output }
  8906. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  8907. else
  8908. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  8909. { Change second MOV command to an ADD command. This is easier than
  8910. converting the existing command because it means we don't have to
  8911. touch 'y', which might be a complicated reference, and also the
  8912. fact that the third command might either be ADD or LEA. [Kit] }
  8913. taicpu(hp1).opcode := A_ADD;
  8914. { Delete old ADD/LEA instruction }
  8915. RemoveInstruction(hp2);
  8916. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  8917. taicpu(hp3).opcode := A_RCR;
  8918. taicpu(hp3).changeopsize(S_L);
  8919. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  8920. {$endif x86_64}
  8921. end;
  8922. if FuncMov2Func(p, hp1) then
  8923. begin
  8924. Result := True;
  8925. Exit;
  8926. end;
  8927. end;
  8928. {$push}
  8929. {$q-}{$r-}
  8930. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  8931. var
  8932. ThisReg: TRegister;
  8933. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  8934. TargetSubReg: TSubRegister;
  8935. hp1, hp2: tai;
  8936. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  8937. { Store list of found instructions so we don't have to call
  8938. GetNextInstructionUsingReg multiple times }
  8939. InstrList: array of taicpu;
  8940. InstrMax, Index: Integer;
  8941. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  8942. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  8943. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  8944. WorkingValue: TCgInt;
  8945. PreMessage: string;
  8946. { Data flow analysis }
  8947. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  8948. BitwiseOnly, OrXorUsed,
  8949. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  8950. function CheckOverflowConditions: Boolean;
  8951. begin
  8952. Result := True;
  8953. if (TestValSignedMax > SignedUpperLimit) then
  8954. UpperSignedOverflow := True;
  8955. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  8956. LowerSignedOverflow := True;
  8957. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  8958. LowerUnsignedOverflow := True;
  8959. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  8960. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  8961. begin
  8962. { Absolute overflow }
  8963. Result := False;
  8964. Exit;
  8965. end;
  8966. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  8967. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8968. ShiftDownOverflow := True;
  8969. if (TestValMin < 0) or (TestValMax < 0) then
  8970. begin
  8971. LowerUnsignedOverflow := True;
  8972. UpperUnsignedOverflow := True;
  8973. end;
  8974. end;
  8975. function AdjustInitialLoadAndSize: Boolean;
  8976. begin
  8977. Result := False;
  8978. if not p_removed then
  8979. begin
  8980. if TargetSize = MinSize then
  8981. begin
  8982. { Convert the input MOVZX to a MOV }
  8983. if (taicpu(p).oper[0]^.typ = top_reg) and
  8984. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8985. begin
  8986. { Or remove it completely! }
  8987. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8988. RemoveCurrentP(p);
  8989. p_removed := True;
  8990. end
  8991. else
  8992. begin
  8993. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8994. taicpu(p).opcode := A_MOV;
  8995. taicpu(p).oper[1]^.reg := ThisReg;
  8996. taicpu(p).opsize := TargetSize;
  8997. end;
  8998. Result := True;
  8999. end
  9000. else if TargetSize <> MaxSize then
  9001. begin
  9002. case MaxSize of
  9003. S_L:
  9004. if TargetSize = S_W then
  9005. begin
  9006. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9007. taicpu(p).opsize := S_BW;
  9008. taicpu(p).oper[1]^.reg := ThisReg;
  9009. Result := True;
  9010. end
  9011. else
  9012. InternalError(2020112341);
  9013. S_W:
  9014. if TargetSize = S_L then
  9015. begin
  9016. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9017. taicpu(p).opsize := S_BL;
  9018. taicpu(p).oper[1]^.reg := ThisReg;
  9019. Result := True;
  9020. end
  9021. else
  9022. InternalError(2020112342);
  9023. else
  9024. ;
  9025. end;
  9026. end
  9027. else if not hp1_removed and not RegInUse then
  9028. begin
  9029. { If we have something like:
  9030. movzbl (oper),%regd
  9031. add x, %regd
  9032. movzbl %regb, %regd
  9033. We can reduce the register size to the input of the final
  9034. movzbl instruction. Overflows won't have any effect.
  9035. }
  9036. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9037. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9038. begin
  9039. TargetSize := S_B;
  9040. setsubreg(ThisReg, R_SUBL);
  9041. Result := True;
  9042. end
  9043. else if (taicpu(p).opsize = S_WL) and
  9044. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9045. begin
  9046. TargetSize := S_W;
  9047. setsubreg(ThisReg, R_SUBW);
  9048. Result := True;
  9049. end;
  9050. if Result then
  9051. begin
  9052. { Convert the input MOVZX to a MOV }
  9053. if (taicpu(p).oper[0]^.typ = top_reg) and
  9054. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9055. begin
  9056. { Or remove it completely! }
  9057. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9058. RemoveCurrentP(p);
  9059. p_removed := True;
  9060. end
  9061. else
  9062. begin
  9063. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9064. taicpu(p).opcode := A_MOV;
  9065. taicpu(p).oper[1]^.reg := ThisReg;
  9066. taicpu(p).opsize := TargetSize;
  9067. end;
  9068. end;
  9069. end;
  9070. end;
  9071. end;
  9072. procedure AdjustFinalLoad;
  9073. begin
  9074. if not LowerUnsignedOverflow then
  9075. begin
  9076. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9077. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9078. begin
  9079. { Convert the output MOVZX to a MOV }
  9080. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9081. begin
  9082. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9083. if (MinSize = S_B) or
  9084. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9085. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9086. begin
  9087. { Remove it completely! }
  9088. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9089. { Be careful; if p = hp1 and p was also removed, p
  9090. will become a dangling pointer }
  9091. if p = hp1 then
  9092. begin
  9093. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9094. p_removed := True;
  9095. end
  9096. else
  9097. RemoveInstruction(hp1);
  9098. hp1_removed := True;
  9099. end;
  9100. end
  9101. else
  9102. begin
  9103. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9104. taicpu(hp1).opcode := A_MOV;
  9105. taicpu(hp1).oper[0]^.reg := ThisReg;
  9106. taicpu(hp1).opsize := TargetSize;
  9107. end;
  9108. end
  9109. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9110. begin
  9111. { Need to change the size of the output }
  9112. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9113. taicpu(hp1).oper[0]^.reg := ThisReg;
  9114. taicpu(hp1).opsize := S_BL;
  9115. end;
  9116. end;
  9117. end;
  9118. function CompressInstructions: Boolean;
  9119. var
  9120. LocalIndex: Integer;
  9121. begin
  9122. Result := False;
  9123. { The objective here is to try to find a combination that
  9124. removes one of the MOV/Z instructions. }
  9125. if (
  9126. (taicpu(p).oper[0]^.typ <> top_reg) or
  9127. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9128. ) and
  9129. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9130. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9131. begin
  9132. { Make a preference to remove the second MOVZX instruction }
  9133. case taicpu(hp1).opsize of
  9134. S_BL, S_WL:
  9135. begin
  9136. TargetSize := S_L;
  9137. TargetSubReg := R_SUBD;
  9138. end;
  9139. S_BW:
  9140. begin
  9141. TargetSize := S_W;
  9142. TargetSubReg := R_SUBW;
  9143. end;
  9144. else
  9145. InternalError(2020112302);
  9146. end;
  9147. end
  9148. else
  9149. begin
  9150. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9151. begin
  9152. { Exceeded lower bound but not upper bound }
  9153. TargetSize := MaxSize;
  9154. end
  9155. else if not LowerUnsignedOverflow then
  9156. begin
  9157. { Size didn't exceed lower bound }
  9158. TargetSize := MinSize;
  9159. end
  9160. else
  9161. Exit;
  9162. end;
  9163. case TargetSize of
  9164. S_B:
  9165. TargetSubReg := R_SUBL;
  9166. S_W:
  9167. TargetSubReg := R_SUBW;
  9168. S_L:
  9169. TargetSubReg := R_SUBD;
  9170. else
  9171. InternalError(2020112350);
  9172. end;
  9173. { Update the register to its new size }
  9174. setsubreg(ThisReg, TargetSubReg);
  9175. RegInUse := False;
  9176. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9177. begin
  9178. { Check to see if the active register is used afterwards;
  9179. if not, we can change it and make a saving. }
  9180. TransferUsedRegs(TmpUsedRegs);
  9181. { The target register may be marked as in use to cross
  9182. a jump to a distant label, so exclude it }
  9183. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9184. hp2 := p;
  9185. repeat
  9186. { Explicitly check for the excluded register (don't include the first
  9187. instruction as it may be reading from here }
  9188. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9189. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9190. begin
  9191. RegInUse := True;
  9192. Break;
  9193. end;
  9194. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9195. if not GetNextInstruction(hp2, hp2) then
  9196. InternalError(2020112340);
  9197. until (hp2 = hp1);
  9198. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9199. { We might still be able to get away with this }
  9200. RegInUse := not
  9201. (
  9202. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9203. (hp2.typ = ait_instruction) and
  9204. (
  9205. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9206. instruction that doesn't actually contain ThisReg }
  9207. (cs_opt_level3 in current_settings.optimizerswitches) or
  9208. RegInInstruction(ThisReg, hp2)
  9209. ) and
  9210. RegLoadedWithNewValue(ThisReg, hp2)
  9211. );
  9212. if not RegInUse then
  9213. begin
  9214. { Force the register size to the same as this instruction so it can be removed}
  9215. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9216. begin
  9217. TargetSize := S_L;
  9218. TargetSubReg := R_SUBD;
  9219. end
  9220. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9221. begin
  9222. TargetSize := S_W;
  9223. TargetSubReg := R_SUBW;
  9224. end;
  9225. ThisReg := taicpu(hp1).oper[1]^.reg;
  9226. setsubreg(ThisReg, TargetSubReg);
  9227. RegChanged := True;
  9228. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9229. TransferUsedRegs(TmpUsedRegs);
  9230. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9231. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9232. if p = hp1 then
  9233. begin
  9234. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9235. p_removed := True;
  9236. end
  9237. else
  9238. RemoveInstruction(hp1);
  9239. hp1_removed := True;
  9240. { Instruction will become "mov %reg,%reg" }
  9241. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9242. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9243. begin
  9244. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9245. RemoveCurrentP(p);
  9246. p_removed := True;
  9247. end
  9248. else
  9249. taicpu(p).oper[1]^.reg := ThisReg;
  9250. Result := True;
  9251. end
  9252. else
  9253. begin
  9254. if TargetSize <> MaxSize then
  9255. begin
  9256. { Since the register is in use, we have to force it to
  9257. MaxSize otherwise part of it may become undefined later on }
  9258. TargetSize := MaxSize;
  9259. case TargetSize of
  9260. S_B:
  9261. TargetSubReg := R_SUBL;
  9262. S_W:
  9263. TargetSubReg := R_SUBW;
  9264. S_L:
  9265. TargetSubReg := R_SUBD;
  9266. else
  9267. InternalError(2020112351);
  9268. end;
  9269. setsubreg(ThisReg, TargetSubReg);
  9270. end;
  9271. AdjustFinalLoad;
  9272. end;
  9273. end
  9274. else
  9275. AdjustFinalLoad;
  9276. Result := AdjustInitialLoadAndSize or Result;
  9277. { Now go through every instruction we found and change the
  9278. size. If TargetSize = MaxSize, then almost no changes are
  9279. needed and Result can remain False if it hasn't been set
  9280. yet.
  9281. If RegChanged is True, then the register requires changing
  9282. and so the point about TargetSize = MaxSize doesn't apply. }
  9283. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9284. begin
  9285. for LocalIndex := 0 to InstrMax do
  9286. begin
  9287. { If p_removed is true, then the original MOV/Z was removed
  9288. and removing the AND instruction may not be safe if it
  9289. appears first }
  9290. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9291. InternalError(2020112310);
  9292. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9293. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9294. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9295. InstrList[LocalIndex].opsize := TargetSize;
  9296. end;
  9297. Result := True;
  9298. end;
  9299. end;
  9300. begin
  9301. Result := False;
  9302. p_removed := False;
  9303. hp1_removed := False;
  9304. ThisReg := taicpu(p).oper[1]^.reg;
  9305. { Check for:
  9306. movs/z ###,%ecx (or %cx or %rcx)
  9307. ...
  9308. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9309. (dealloc %ecx)
  9310. Change to:
  9311. mov ###,%cl (if ### = %cl, then remove completely)
  9312. ...
  9313. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9314. }
  9315. if (getsupreg(ThisReg) = RS_ECX) and
  9316. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9317. (hp1.typ = ait_instruction) and
  9318. (
  9319. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9320. instruction that doesn't actually contain ECX }
  9321. (cs_opt_level3 in current_settings.optimizerswitches) or
  9322. RegInInstruction(NR_ECX, hp1) or
  9323. (
  9324. { It's common for the shift/rotate's read/write register to be
  9325. initialised in between, so under -O2 and under, search ahead
  9326. one more instruction
  9327. }
  9328. GetNextInstruction(hp1, hp1) and
  9329. (hp1.typ = ait_instruction) and
  9330. RegInInstruction(NR_ECX, hp1)
  9331. )
  9332. ) and
  9333. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9334. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9335. begin
  9336. TransferUsedRegs(TmpUsedRegs);
  9337. hp2 := p;
  9338. repeat
  9339. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9340. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9341. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9342. begin
  9343. case taicpu(p).opsize of
  9344. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9345. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9346. begin
  9347. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9348. RemoveCurrentP(p);
  9349. end
  9350. else
  9351. begin
  9352. taicpu(p).opcode := A_MOV;
  9353. taicpu(p).opsize := S_B;
  9354. taicpu(p).oper[1]^.reg := NR_CL;
  9355. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9356. end;
  9357. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9358. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9359. begin
  9360. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9361. RemoveCurrentP(p);
  9362. end
  9363. else
  9364. begin
  9365. taicpu(p).opcode := A_MOV;
  9366. taicpu(p).opsize := S_W;
  9367. taicpu(p).oper[1]^.reg := NR_CX;
  9368. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9369. end;
  9370. {$ifdef x86_64}
  9371. S_LQ:
  9372. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9373. begin
  9374. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9375. RemoveCurrentP(p);
  9376. end
  9377. else
  9378. begin
  9379. taicpu(p).opcode := A_MOV;
  9380. taicpu(p).opsize := S_L;
  9381. taicpu(p).oper[1]^.reg := NR_ECX;
  9382. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9383. end;
  9384. {$endif x86_64}
  9385. else
  9386. InternalError(2021120401);
  9387. end;
  9388. Result := True;
  9389. Exit;
  9390. end;
  9391. end;
  9392. { This is anything but quick! }
  9393. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9394. Exit;
  9395. SetLength(InstrList, 0);
  9396. InstrMax := -1;
  9397. case taicpu(p).opsize of
  9398. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9399. begin
  9400. {$if defined(i386) or defined(i8086)}
  9401. { If the target size is 8-bit, make sure we can actually encode it }
  9402. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9403. Exit;
  9404. {$endif i386 or i8086}
  9405. LowerLimit := $FF;
  9406. SignedLowerLimit := $7F;
  9407. SignedLowerLimitBottom := -128;
  9408. MinSize := S_B;
  9409. if taicpu(p).opsize = S_BW then
  9410. begin
  9411. MaxSize := S_W;
  9412. UpperLimit := $FFFF;
  9413. SignedUpperLimit := $7FFF;
  9414. SignedUpperLimitBottom := -32768;
  9415. end
  9416. else
  9417. begin
  9418. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9419. MaxSize := S_L;
  9420. UpperLimit := $FFFFFFFF;
  9421. SignedUpperLimit := $7FFFFFFF;
  9422. SignedUpperLimitBottom := -2147483648;
  9423. end;
  9424. end;
  9425. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9426. begin
  9427. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9428. LowerLimit := $FFFF;
  9429. SignedLowerLimit := $7FFF;
  9430. SignedLowerLimitBottom := -32768;
  9431. UpperLimit := $FFFFFFFF;
  9432. SignedUpperLimit := $7FFFFFFF;
  9433. SignedUpperLimitBottom := -2147483648;
  9434. MinSize := S_W;
  9435. MaxSize := S_L;
  9436. end;
  9437. {$ifdef x86_64}
  9438. S_LQ:
  9439. begin
  9440. { Both the lower and upper limits are set to 32-bit. If a limit
  9441. is breached, then optimisation is impossible }
  9442. LowerLimit := $FFFFFFFF;
  9443. SignedLowerLimit := $7FFFFFFF;
  9444. SignedLowerLimitBottom := -2147483648;
  9445. UpperLimit := $FFFFFFFF;
  9446. SignedUpperLimit := $7FFFFFFF;
  9447. SignedUpperLimitBottom := -2147483648;
  9448. MinSize := S_L;
  9449. MaxSize := S_L;
  9450. end;
  9451. {$endif x86_64}
  9452. else
  9453. InternalError(2020112301);
  9454. end;
  9455. TestValMin := 0;
  9456. TestValMax := LowerLimit;
  9457. TestValSignedMax := SignedLowerLimit;
  9458. TryShiftDownLimit := LowerLimit;
  9459. TryShiftDown := S_NO;
  9460. ShiftDownOverflow := False;
  9461. RegChanged := False;
  9462. BitwiseOnly := True;
  9463. OrXorUsed := False;
  9464. UpperSignedOverflow := False;
  9465. LowerSignedOverflow := False;
  9466. UpperUnsignedOverflow := False;
  9467. LowerUnsignedOverflow := False;
  9468. hp1 := p;
  9469. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9470. (hp1.typ = ait_instruction) and
  9471. (
  9472. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9473. instruction that doesn't actually contain ThisReg }
  9474. (cs_opt_level3 in current_settings.optimizerswitches) or
  9475. { This allows this Movx optimisation to work through the SETcc instructions
  9476. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9477. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9478. skip over these SETcc instructions). }
  9479. (taicpu(hp1).opcode = A_SETcc) or
  9480. RegInInstruction(ThisReg, hp1)
  9481. ) do
  9482. begin
  9483. case taicpu(hp1).opcode of
  9484. A_INC,A_DEC:
  9485. begin
  9486. { Has to be an exact match on the register }
  9487. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9488. Break;
  9489. if taicpu(hp1).opcode = A_INC then
  9490. begin
  9491. Inc(TestValMin);
  9492. Inc(TestValMax);
  9493. Inc(TestValSignedMax);
  9494. end
  9495. else
  9496. begin
  9497. Dec(TestValMin);
  9498. Dec(TestValMax);
  9499. Dec(TestValSignedMax);
  9500. end;
  9501. end;
  9502. A_TEST, A_CMP:
  9503. begin
  9504. if (
  9505. { Too high a risk of non-linear behaviour that breaks DFA
  9506. here, unless it's cmp $0,%reg, which is equivalent to
  9507. test %reg,%reg }
  9508. OrXorUsed and
  9509. (taicpu(hp1).opcode = A_CMP) and
  9510. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9511. ) or
  9512. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9513. { Has to be an exact match on the register }
  9514. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9515. (
  9516. { Permit "test %reg,%reg" }
  9517. (taicpu(hp1).opcode = A_TEST) and
  9518. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9519. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9520. ) or
  9521. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9522. { Make sure the comparison value is not smaller than the
  9523. smallest allowed signed value for the minimum size (e.g.
  9524. -128 for 8-bit) }
  9525. not (
  9526. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9527. { Is it in the negative range? }
  9528. (
  9529. (taicpu(hp1).oper[0]^.val < 0) and
  9530. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9531. )
  9532. ) then
  9533. Break;
  9534. { Check to see if the active register is used afterwards }
  9535. TransferUsedRegs(TmpUsedRegs);
  9536. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9537. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9538. begin
  9539. { Make sure the comparison or any previous instructions
  9540. hasn't pushed the test values outside of the range of
  9541. MinSize }
  9542. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9543. begin
  9544. { Exceeded lower bound but not upper bound }
  9545. Exit;
  9546. end
  9547. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9548. begin
  9549. { Size didn't exceed lower bound }
  9550. TargetSize := MinSize;
  9551. end
  9552. else
  9553. Break;
  9554. case TargetSize of
  9555. S_B:
  9556. TargetSubReg := R_SUBL;
  9557. S_W:
  9558. TargetSubReg := R_SUBW;
  9559. S_L:
  9560. TargetSubReg := R_SUBD;
  9561. else
  9562. InternalError(2021051002);
  9563. end;
  9564. if TargetSize <> MaxSize then
  9565. begin
  9566. { Update the register to its new size }
  9567. setsubreg(ThisReg, TargetSubReg);
  9568. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9569. taicpu(hp1).oper[1]^.reg := ThisReg;
  9570. taicpu(hp1).opsize := TargetSize;
  9571. { Convert the input MOVZX to a MOV if necessary }
  9572. AdjustInitialLoadAndSize;
  9573. if (InstrMax >= 0) then
  9574. begin
  9575. for Index := 0 to InstrMax do
  9576. begin
  9577. { If p_removed is true, then the original MOV/Z was removed
  9578. and removing the AND instruction may not be safe if it
  9579. appears first }
  9580. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9581. InternalError(2020112311);
  9582. if InstrList[Index].oper[0]^.typ = top_reg then
  9583. InstrList[Index].oper[0]^.reg := ThisReg;
  9584. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9585. InstrList[Index].opsize := MinSize;
  9586. end;
  9587. end;
  9588. Result := True;
  9589. end;
  9590. Exit;
  9591. end;
  9592. end;
  9593. A_SETcc:
  9594. begin
  9595. { This allows this Movx optimisation to work through the SETcc instructions
  9596. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9597. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9598. skip over these SETcc instructions). }
  9599. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9600. { Of course, break out if the current register is used }
  9601. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9602. Break
  9603. else
  9604. { We must use Continue so the instruction doesn't get added
  9605. to InstrList }
  9606. Continue;
  9607. end;
  9608. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9609. begin
  9610. if
  9611. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9612. { Has to be an exact match on the register }
  9613. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9614. (
  9615. (
  9616. (taicpu(hp1).oper[0]^.typ = top_const) and
  9617. (
  9618. (
  9619. (taicpu(hp1).opcode = A_SHL) and
  9620. (
  9621. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9622. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9623. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9624. )
  9625. ) or (
  9626. (taicpu(hp1).opcode <> A_SHL) and
  9627. (
  9628. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9629. { Is it in the negative range? }
  9630. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9631. )
  9632. )
  9633. )
  9634. ) or (
  9635. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9636. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9637. )
  9638. ) then
  9639. Break;
  9640. { Only process OR and XOR if there are only bitwise operations,
  9641. since otherwise they can too easily fool the data flow
  9642. analysis (they can cause non-linear behaviour) }
  9643. case taicpu(hp1).opcode of
  9644. A_ADD:
  9645. begin
  9646. if OrXorUsed then
  9647. { Too high a risk of non-linear behaviour that breaks DFA here }
  9648. Break
  9649. else
  9650. BitwiseOnly := False;
  9651. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9652. begin
  9653. TestValMin := TestValMin * 2;
  9654. TestValMax := TestValMax * 2;
  9655. TestValSignedMax := TestValSignedMax * 2;
  9656. end
  9657. else
  9658. begin
  9659. WorkingValue := taicpu(hp1).oper[0]^.val;
  9660. TestValMin := TestValMin + WorkingValue;
  9661. TestValMax := TestValMax + WorkingValue;
  9662. TestValSignedMax := TestValSignedMax + WorkingValue;
  9663. end;
  9664. end;
  9665. A_SUB:
  9666. begin
  9667. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9668. begin
  9669. TestValMin := 0;
  9670. TestValMax := 0;
  9671. TestValSignedMax := 0;
  9672. end
  9673. else
  9674. begin
  9675. if OrXorUsed then
  9676. { Too high a risk of non-linear behaviour that breaks DFA here }
  9677. Break
  9678. else
  9679. BitwiseOnly := False;
  9680. WorkingValue := taicpu(hp1).oper[0]^.val;
  9681. TestValMin := TestValMin - WorkingValue;
  9682. TestValMax := TestValMax - WorkingValue;
  9683. TestValSignedMax := TestValSignedMax - WorkingValue;
  9684. end;
  9685. end;
  9686. A_AND:
  9687. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9688. begin
  9689. { we might be able to go smaller if AND appears first }
  9690. if InstrMax = -1 then
  9691. case MinSize of
  9692. S_B:
  9693. ;
  9694. S_W:
  9695. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9696. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9697. begin
  9698. TryShiftDown := S_B;
  9699. TryShiftDownLimit := $FF;
  9700. end;
  9701. S_L:
  9702. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9703. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9704. begin
  9705. TryShiftDown := S_B;
  9706. TryShiftDownLimit := $FF;
  9707. end
  9708. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9709. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9710. begin
  9711. TryShiftDown := S_W;
  9712. TryShiftDownLimit := $FFFF;
  9713. end;
  9714. else
  9715. InternalError(2020112320);
  9716. end;
  9717. WorkingValue := taicpu(hp1).oper[0]^.val;
  9718. TestValMin := TestValMin and WorkingValue;
  9719. TestValMax := TestValMax and WorkingValue;
  9720. TestValSignedMax := TestValSignedMax and WorkingValue;
  9721. end;
  9722. A_OR:
  9723. begin
  9724. if not BitwiseOnly then
  9725. Break;
  9726. OrXorUsed := True;
  9727. WorkingValue := taicpu(hp1).oper[0]^.val;
  9728. TestValMin := TestValMin or WorkingValue;
  9729. TestValMax := TestValMax or WorkingValue;
  9730. TestValSignedMax := TestValSignedMax or WorkingValue;
  9731. end;
  9732. A_XOR:
  9733. begin
  9734. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9735. begin
  9736. TestValMin := 0;
  9737. TestValMax := 0;
  9738. TestValSignedMax := 0;
  9739. end
  9740. else
  9741. begin
  9742. if not BitwiseOnly then
  9743. Break;
  9744. OrXorUsed := True;
  9745. WorkingValue := taicpu(hp1).oper[0]^.val;
  9746. TestValMin := TestValMin xor WorkingValue;
  9747. TestValMax := TestValMax xor WorkingValue;
  9748. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9749. end;
  9750. end;
  9751. A_SHL:
  9752. begin
  9753. BitwiseOnly := False;
  9754. WorkingValue := taicpu(hp1).oper[0]^.val;
  9755. TestValMin := TestValMin shl WorkingValue;
  9756. TestValMax := TestValMax shl WorkingValue;
  9757. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9758. end;
  9759. A_SHR,
  9760. { The first instruction was MOVZX, so the value won't be negative }
  9761. A_SAR:
  9762. begin
  9763. if InstrMax <> -1 then
  9764. BitwiseOnly := False
  9765. else
  9766. { we might be able to go smaller if SHR appears first }
  9767. case MinSize of
  9768. S_B:
  9769. ;
  9770. S_W:
  9771. if (taicpu(hp1).oper[0]^.val >= 8) then
  9772. begin
  9773. TryShiftDown := S_B;
  9774. TryShiftDownLimit := $FF;
  9775. TryShiftDownSignedLimit := $7F;
  9776. TryShiftDownSignedLimitLower := -128;
  9777. end;
  9778. S_L:
  9779. if (taicpu(hp1).oper[0]^.val >= 24) then
  9780. begin
  9781. TryShiftDown := S_B;
  9782. TryShiftDownLimit := $FF;
  9783. TryShiftDownSignedLimit := $7F;
  9784. TryShiftDownSignedLimitLower := -128;
  9785. end
  9786. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9787. begin
  9788. TryShiftDown := S_W;
  9789. TryShiftDownLimit := $FFFF;
  9790. TryShiftDownSignedLimit := $7FFF;
  9791. TryShiftDownSignedLimitLower := -32768;
  9792. end;
  9793. else
  9794. InternalError(2020112321);
  9795. end;
  9796. WorkingValue := taicpu(hp1).oper[0]^.val;
  9797. if taicpu(hp1).opcode = A_SAR then
  9798. begin
  9799. TestValMin := SarInt64(TestValMin, WorkingValue);
  9800. TestValMax := SarInt64(TestValMax, WorkingValue);
  9801. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9802. end
  9803. else
  9804. begin
  9805. TestValMin := TestValMin shr WorkingValue;
  9806. TestValMax := TestValMax shr WorkingValue;
  9807. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9808. end;
  9809. end;
  9810. else
  9811. InternalError(2020112303);
  9812. end;
  9813. end;
  9814. (*
  9815. A_IMUL:
  9816. case taicpu(hp1).ops of
  9817. 2:
  9818. begin
  9819. if not MatchOpType(hp1, top_reg, top_reg) or
  9820. { Has to be an exact match on the register }
  9821. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9822. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9823. Break;
  9824. TestValMin := TestValMin * TestValMin;
  9825. TestValMax := TestValMax * TestValMax;
  9826. TestValSignedMax := TestValSignedMax * TestValMax;
  9827. end;
  9828. 3:
  9829. begin
  9830. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9831. { Has to be an exact match on the register }
  9832. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9833. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9834. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9835. { Is it in the negative range? }
  9836. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9837. Break;
  9838. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9839. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9840. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9841. end;
  9842. else
  9843. Break;
  9844. end;
  9845. A_IDIV:
  9846. case taicpu(hp1).ops of
  9847. 3:
  9848. begin
  9849. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9850. { Has to be an exact match on the register }
  9851. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9852. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9853. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9854. { Is it in the negative range? }
  9855. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9856. Break;
  9857. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9858. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9859. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9860. end;
  9861. else
  9862. Break;
  9863. end;
  9864. *)
  9865. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9866. begin
  9867. { If there are no instructions in between, then we might be able to make a saving }
  9868. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9869. Break;
  9870. { We have something like:
  9871. movzbw %dl,%dx
  9872. ...
  9873. movswl %dx,%edx
  9874. Change the latter to a zero-extension then enter the
  9875. A_MOVZX case branch.
  9876. }
  9877. {$ifdef x86_64}
  9878. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9879. begin
  9880. { this becomes a zero extension from 32-bit to 64-bit, but
  9881. the upper 32 bits are already zero, so just delete the
  9882. instruction }
  9883. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9884. RemoveInstruction(hp1);
  9885. Result := True;
  9886. Exit;
  9887. end
  9888. else
  9889. {$endif x86_64}
  9890. begin
  9891. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9892. taicpu(hp1).opcode := A_MOVZX;
  9893. {$ifdef x86_64}
  9894. case taicpu(hp1).opsize of
  9895. S_BQ:
  9896. begin
  9897. taicpu(hp1).opsize := S_BL;
  9898. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9899. end;
  9900. S_WQ:
  9901. begin
  9902. taicpu(hp1).opsize := S_WL;
  9903. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9904. end;
  9905. S_LQ:
  9906. begin
  9907. taicpu(hp1).opcode := A_MOV;
  9908. taicpu(hp1).opsize := S_L;
  9909. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9910. { In this instance, we need to break out because the
  9911. instruction is no longer MOVZX or MOVSXD }
  9912. Result := True;
  9913. Exit;
  9914. end;
  9915. else
  9916. ;
  9917. end;
  9918. {$endif x86_64}
  9919. Result := CompressInstructions;
  9920. Exit;
  9921. end;
  9922. end;
  9923. A_MOVZX:
  9924. begin
  9925. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  9926. Break;
  9927. if (InstrMax = -1) then
  9928. begin
  9929. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  9930. begin
  9931. { Optimise around i40003 }
  9932. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  9933. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  9934. {$ifndef x86_64}
  9935. and (
  9936. (taicpu(p).oper[0]^.typ <> top_reg) or
  9937. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  9938. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  9939. )
  9940. {$endif not x86_64}
  9941. then
  9942. begin
  9943. if (taicpu(p).oper[0]^.typ = top_reg) then
  9944. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  9945. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  9946. taicpu(p).opsize := S_BL;
  9947. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  9948. RemoveInstruction(hp1);
  9949. Result := True;
  9950. Exit;
  9951. end;
  9952. end
  9953. else
  9954. begin
  9955. { Will return false if the second parameter isn't ThisReg
  9956. (can happen on -O2 and under) }
  9957. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9958. begin
  9959. { The two MOVZX instructions are adjacent, so remove the first one }
  9960. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  9961. RemoveCurrentP(p);
  9962. Result := True;
  9963. Exit;
  9964. end;
  9965. Break;
  9966. end;
  9967. end;
  9968. Result := CompressInstructions;
  9969. Exit;
  9970. end;
  9971. else
  9972. { This includes ADC, SBB and IDIV }
  9973. Break;
  9974. end;
  9975. if not CheckOverflowConditions then
  9976. Break;
  9977. { Contains highest index (so instruction count - 1) }
  9978. Inc(InstrMax);
  9979. if InstrMax > High(InstrList) then
  9980. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9981. InstrList[InstrMax] := taicpu(hp1);
  9982. end;
  9983. end;
  9984. {$pop}
  9985. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  9986. var
  9987. hp1 : tai;
  9988. begin
  9989. Result:=false;
  9990. if (taicpu(p).ops >= 2) and
  9991. ((taicpu(p).oper[0]^.typ = top_const) or
  9992. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  9993. (taicpu(p).oper[1]^.typ = top_reg) and
  9994. ((taicpu(p).ops = 2) or
  9995. ((taicpu(p).oper[2]^.typ = top_reg) and
  9996. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  9997. GetLastInstruction(p,hp1) and
  9998. MatchInstruction(hp1,A_MOV,[]) and
  9999. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10000. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10001. begin
  10002. TransferUsedRegs(TmpUsedRegs);
  10003. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10004. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10005. { change
  10006. mov reg1,reg2
  10007. imul y,reg2 to imul y,reg1,reg2 }
  10008. begin
  10009. taicpu(p).ops := 3;
  10010. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10011. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10012. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10013. RemoveInstruction(hp1);
  10014. result:=true;
  10015. end;
  10016. end;
  10017. end;
  10018. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10019. var
  10020. ThisLabel: TAsmLabel;
  10021. begin
  10022. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10023. ThisLabel.decrefs;
  10024. taicpu(p).condition := C_None;
  10025. taicpu(p).opcode := A_RET;
  10026. taicpu(p).is_jmp := false;
  10027. taicpu(p).ops := taicpu(ret_p).ops;
  10028. case taicpu(ret_p).ops of
  10029. 0:
  10030. taicpu(p).clearop(0);
  10031. 1:
  10032. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10033. else
  10034. internalerror(2016041301);
  10035. end;
  10036. { If the original label is now dead, it might turn out that the label
  10037. immediately follows p. As a result, everything beyond it, which will
  10038. be just some final register configuration and a RET instruction, is
  10039. now dead code. [Kit] }
  10040. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10041. running RemoveDeadCodeAfterJump for each RET instruction, because
  10042. this optimisation rarely happens and most RETs appear at the end of
  10043. routines where there is nothing that can be stripped. [Kit] }
  10044. if not ThisLabel.is_used then
  10045. RemoveDeadCodeAfterJump(p);
  10046. end;
  10047. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10048. var
  10049. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10050. Unconditional, PotentialModified: Boolean;
  10051. OperPtr: POper;
  10052. NewRef: TReference;
  10053. InstrList: array of taicpu;
  10054. InstrMax, Index: Integer;
  10055. const
  10056. {$ifdef DEBUG_AOPTCPU}
  10057. SNoFlags: shortstring = ' so the flags aren''t modified';
  10058. {$else DEBUG_AOPTCPU}
  10059. SNoFlags = '';
  10060. {$endif DEBUG_AOPTCPU}
  10061. begin
  10062. Result:=false;
  10063. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10064. begin
  10065. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10066. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10067. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10068. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10069. GetNextInstruction(hp1, hp2) and
  10070. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10071. { Change from: To:
  10072. set(C) %reg j(~C) label
  10073. test %reg,%reg/cmp $0,%reg
  10074. je label
  10075. set(C) %reg j(C) label
  10076. test %reg,%reg/cmp $0,%reg
  10077. jne label
  10078. (Also do something similar with sete/setne instead of je/jne)
  10079. }
  10080. begin
  10081. { Before we do anything else, we need to check the instructions
  10082. in between SETcc and TEST to make sure they don't modify the
  10083. FLAGS register - if -O2 or under, there won't be any
  10084. instructions between SET and TEST }
  10085. TransferUsedRegs(TmpUsedRegs);
  10086. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10087. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10088. begin
  10089. next := p;
  10090. SetLength(InstrList, 0);
  10091. InstrMax := -1;
  10092. PotentialModified := False;
  10093. { Make a note of every instruction that modifies the FLAGS
  10094. register }
  10095. while GetNextInstruction(next, next) and (next <> hp1) do
  10096. begin
  10097. if next.typ <> ait_instruction then
  10098. { GetNextInstructionUsingReg should have returned False }
  10099. InternalError(2021051701);
  10100. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10101. begin
  10102. case taicpu(next).opcode of
  10103. A_SETcc,
  10104. A_CMOVcc,
  10105. A_Jcc:
  10106. begin
  10107. if PotentialModified then
  10108. { Not safe because the flags were modified earlier }
  10109. Exit
  10110. else
  10111. { Condition is the same as the initial SETcc, so this is safe
  10112. (don't add to instruction list though) }
  10113. Continue;
  10114. end;
  10115. A_ADD:
  10116. begin
  10117. if (taicpu(next).opsize = S_B) or
  10118. { LEA doesn't support 8-bit operands }
  10119. (taicpu(next).oper[1]^.typ <> top_reg) or
  10120. { Must write to a register }
  10121. (taicpu(next).oper[0]^.typ = top_ref) then
  10122. { Require a constant or a register }
  10123. Exit;
  10124. PotentialModified := True;
  10125. end;
  10126. A_SUB:
  10127. begin
  10128. if (taicpu(next).opsize = S_B) or
  10129. { LEA doesn't support 8-bit operands }
  10130. (taicpu(next).oper[1]^.typ <> top_reg) or
  10131. { Must write to a register }
  10132. (taicpu(next).oper[0]^.typ <> top_const) or
  10133. (taicpu(next).oper[0]^.val = $80000000) then
  10134. { Can't subtract a register with LEA - also
  10135. check that the value isn't -2^31, as this
  10136. can't be negated }
  10137. Exit;
  10138. PotentialModified := True;
  10139. end;
  10140. A_SAL,
  10141. A_SHL:
  10142. begin
  10143. if (taicpu(next).opsize = S_B) or
  10144. { LEA doesn't support 8-bit operands }
  10145. (taicpu(next).oper[1]^.typ <> top_reg) or
  10146. { Must write to a register }
  10147. (taicpu(next).oper[0]^.typ <> top_const) or
  10148. (taicpu(next).oper[0]^.val < 0) or
  10149. (taicpu(next).oper[0]^.val > 3) then
  10150. Exit;
  10151. PotentialModified := True;
  10152. end;
  10153. A_IMUL:
  10154. begin
  10155. if (taicpu(next).ops <> 3) or
  10156. (taicpu(next).oper[1]^.typ <> top_reg) or
  10157. { Must write to a register }
  10158. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10159. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10160. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10161. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10162. Exit
  10163. else
  10164. PotentialModified := True;
  10165. end;
  10166. else
  10167. { Don't know how to change this, so abort }
  10168. Exit;
  10169. end;
  10170. { Contains highest index (so instruction count - 1) }
  10171. Inc(InstrMax);
  10172. if InstrMax > High(InstrList) then
  10173. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10174. InstrList[InstrMax] := taicpu(next);
  10175. end;
  10176. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10177. end;
  10178. if not Assigned(next) or (next <> hp1) then
  10179. { It should be equal to hp1 }
  10180. InternalError(2021051702);
  10181. { Cycle through each instruction and check to see if we can
  10182. change them to versions that don't modify the flags }
  10183. if (InstrMax >= 0) then
  10184. begin
  10185. for Index := 0 to InstrMax do
  10186. case InstrList[Index].opcode of
  10187. A_ADD:
  10188. begin
  10189. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10190. InstrList[Index].opcode := A_LEA;
  10191. reference_reset(NewRef, 1, []);
  10192. NewRef.base := InstrList[Index].oper[1]^.reg;
  10193. if InstrList[Index].oper[0]^.typ = top_reg then
  10194. begin
  10195. NewRef.index := InstrList[Index].oper[0]^.reg;
  10196. NewRef.scalefactor := 1;
  10197. end
  10198. else
  10199. NewRef.offset := InstrList[Index].oper[0]^.val;
  10200. InstrList[Index].loadref(0, NewRef);
  10201. end;
  10202. A_SUB:
  10203. begin
  10204. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10205. InstrList[Index].opcode := A_LEA;
  10206. reference_reset(NewRef, 1, []);
  10207. NewRef.base := InstrList[Index].oper[1]^.reg;
  10208. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10209. InstrList[Index].loadref(0, NewRef);
  10210. end;
  10211. A_SHL,
  10212. A_SAL:
  10213. begin
  10214. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10215. InstrList[Index].opcode := A_LEA;
  10216. reference_reset(NewRef, 1, []);
  10217. NewRef.index := InstrList[Index].oper[1]^.reg;
  10218. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10219. InstrList[Index].loadref(0, NewRef);
  10220. end;
  10221. A_IMUL:
  10222. begin
  10223. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10224. InstrList[Index].opcode := A_LEA;
  10225. reference_reset(NewRef, 1, []);
  10226. NewRef.index := InstrList[Index].oper[1]^.reg;
  10227. case InstrList[Index].oper[0]^.val of
  10228. 2, 4, 8:
  10229. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10230. else {3, 5 and 9}
  10231. begin
  10232. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10233. NewRef.base := InstrList[Index].oper[1]^.reg;
  10234. end;
  10235. end;
  10236. InstrList[Index].loadref(0, NewRef);
  10237. end;
  10238. else
  10239. InternalError(2021051710);
  10240. end;
  10241. end;
  10242. { Mark the FLAGS register as used across this whole block }
  10243. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10244. end;
  10245. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10246. JumpC := taicpu(hp2).condition;
  10247. Unconditional := False;
  10248. if conditions_equal(JumpC, C_E) then
  10249. SetC := inverse_cond(taicpu(p).condition)
  10250. else if conditions_equal(JumpC, C_NE) then
  10251. SetC := taicpu(p).condition
  10252. else
  10253. { We've got something weird here (and inefficent) }
  10254. begin
  10255. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10256. SetC := C_NONE;
  10257. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10258. if condition_in(C_AE, JumpC) then
  10259. Unconditional := True
  10260. else
  10261. { Not sure what to do with this jump - drop out }
  10262. Exit;
  10263. end;
  10264. RemoveInstruction(hp1);
  10265. if Unconditional then
  10266. MakeUnconditional(taicpu(hp2))
  10267. else
  10268. begin
  10269. if SetC = C_NONE then
  10270. InternalError(2018061402);
  10271. taicpu(hp2).SetCondition(SetC);
  10272. end;
  10273. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10274. TmpUsedRegs }
  10275. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10276. begin
  10277. RemoveCurrentp(p, hp2);
  10278. if taicpu(hp2).opcode = A_SETcc then
  10279. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10280. else
  10281. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10282. end
  10283. else
  10284. if taicpu(hp2).opcode = A_SETcc then
  10285. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10286. else
  10287. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10288. Result := True;
  10289. end
  10290. else if
  10291. { Make sure the instructions are adjacent }
  10292. (
  10293. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10294. GetNextInstruction(p, hp1)
  10295. ) and
  10296. MatchInstruction(hp1, A_MOV, [S_B]) and
  10297. { Writing to memory is allowed }
  10298. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10299. begin
  10300. {
  10301. Watch out for sequences such as:
  10302. set(c)b %regb
  10303. movb %regb,(ref)
  10304. movb $0,1(ref)
  10305. movb $0,2(ref)
  10306. movb $0,3(ref)
  10307. Much more efficient to turn it into:
  10308. movl $0,%regl
  10309. set(c)b %regb
  10310. movl %regl,(ref)
  10311. Or:
  10312. set(c)b %regb
  10313. movzbl %regb,%regl
  10314. movl %regl,(ref)
  10315. }
  10316. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10317. GetNextInstruction(hp1, hp2) and
  10318. MatchInstruction(hp2, A_MOV, [S_B]) and
  10319. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10320. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10321. begin
  10322. { Don't do anything else except set Result to True }
  10323. end
  10324. else
  10325. begin
  10326. if taicpu(p).oper[0]^.typ = top_reg then
  10327. begin
  10328. TransferUsedRegs(TmpUsedRegs);
  10329. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10330. end;
  10331. { If it's not a register, it's a memory address }
  10332. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10333. begin
  10334. { Even if the register is still in use, we can minimise the
  10335. pipeline stall by changing the MOV into another SETcc. }
  10336. taicpu(hp1).opcode := A_SETcc;
  10337. taicpu(hp1).condition := taicpu(p).condition;
  10338. if taicpu(hp1).oper[1]^.typ = top_ref then
  10339. begin
  10340. { Swapping the operand pointers like this is probably a
  10341. bit naughty, but it is far faster than using loadoper
  10342. to transfer the reference from oper[1] to oper[0] if
  10343. you take into account the extra procedure calls and
  10344. the memory allocation and deallocation required }
  10345. OperPtr := taicpu(hp1).oper[1];
  10346. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10347. taicpu(hp1).oper[0] := OperPtr;
  10348. end
  10349. else
  10350. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10351. taicpu(hp1).clearop(1);
  10352. taicpu(hp1).ops := 1;
  10353. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10354. end
  10355. else
  10356. begin
  10357. if taicpu(hp1).oper[1]^.typ = top_reg then
  10358. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10359. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10360. RemoveInstruction(hp1);
  10361. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10362. end
  10363. end;
  10364. Result := True;
  10365. end;
  10366. end;
  10367. end;
  10368. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10369. var
  10370. hp1: tai;
  10371. Count: Integer;
  10372. OrigLabel: TAsmLabel;
  10373. begin
  10374. result := False;
  10375. { Sometimes, the optimisations below can permit this }
  10376. RemoveDeadCodeAfterJump(p);
  10377. if (taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full) and (taicpu(p).oper[0]^.ref^.base=NR_NO) and
  10378. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10379. begin
  10380. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10381. { Also a side-effect of optimisations }
  10382. if CollapseZeroDistJump(p, OrigLabel) then
  10383. begin
  10384. Result := True;
  10385. Exit;
  10386. end;
  10387. hp1 := GetLabelWithSym(OrigLabel);
  10388. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10389. begin
  10390. if taicpu(hp1).opcode = A_RET then
  10391. begin
  10392. {
  10393. change
  10394. jmp .L1
  10395. ...
  10396. .L1:
  10397. ret
  10398. into
  10399. ret
  10400. }
  10401. begin
  10402. ConvertJumpToRET(p, hp1);
  10403. result:=true;
  10404. end;
  10405. end
  10406. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10407. not (cs_opt_size in current_settings.optimizerswitches) and
  10408. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10409. begin
  10410. Result := True;
  10411. Exit;
  10412. end;
  10413. end;
  10414. end;
  10415. end;
  10416. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai) : boolean;
  10417. begin
  10418. Result := assigned(p) and
  10419. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10420. (taicpu(p).oper[1]^.typ = top_reg) and
  10421. (
  10422. (taicpu(p).oper[0]^.typ = top_reg) or
  10423. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10424. it is not expected that this can cause a seg. violation }
  10425. (
  10426. (taicpu(p).oper[0]^.typ = top_ref) and
  10427. { TODO: Can we detect which references become constants at this
  10428. stage so we don't have to do a blanket ban? }
  10429. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10430. (
  10431. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10432. (
  10433. { If the reference also appears in the condition, then we know it's safe, otherwise
  10434. any kind of access violation would have occurred already }
  10435. Assigned(cond_p) and
  10436. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10437. (cond_p.typ = ait_instruction) and
  10438. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10439. { Just consider 2-operand comparison instructions for now to be safe }
  10440. (taicpu(cond_p).ops = 2) and
  10441. (
  10442. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10443. (
  10444. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10445. { Don't risk identical registers but different offsets, as we may have constructs
  10446. such as buffer streams with things like length fields that indicate whether
  10447. any more data follows. And there are probably some contrived examples where
  10448. writing to offsets behind the one being read also lead to access violations }
  10449. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10450. (
  10451. { Check that we're not modifying a register that appears in the reference }
  10452. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10453. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10454. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10455. )
  10456. )
  10457. )
  10458. )
  10459. )
  10460. )
  10461. );
  10462. end;
  10463. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10464. begin
  10465. { Update integer registers, ignoring deallocations }
  10466. repeat
  10467. while assigned(p) and
  10468. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10469. (p.typ = ait_label) or
  10470. ((p.typ = ait_marker) and
  10471. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10472. p := tai(p.next);
  10473. while assigned(p) and
  10474. (p.typ=ait_RegAlloc) Do
  10475. begin
  10476. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10477. begin
  10478. case tai_regalloc(p).ratype of
  10479. ra_alloc :
  10480. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10481. else
  10482. ;
  10483. end;
  10484. end;
  10485. p := tai(p.next);
  10486. end;
  10487. until not(assigned(p)) or
  10488. (not(p.typ in SkipInstr) and
  10489. not((p.typ = ait_label) and
  10490. labelCanBeSkipped(tai_label(p))));
  10491. end;
  10492. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10493. var
  10494. hp1,hp2: tai;
  10495. carryadd_opcode : TAsmOp;
  10496. symbol: TAsmSymbol;
  10497. increg, tmpreg: TRegister;
  10498. {$ifndef i8086}
  10499. { Code and variables specific to CMOV optimisations }
  10500. hp3,hp4,hp5,
  10501. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10502. l, c, w, x : Longint;
  10503. condition, second_condition : TAsmCond;
  10504. FoundMatchingJump, RegMatch: Boolean;
  10505. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10506. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10507. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10508. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10509. new register to store the constant }
  10510. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10511. var
  10512. RegSize: TSubRegister;
  10513. CurrentVal: TCGInt;
  10514. NewReg: TRegister;
  10515. X: ShortInt;
  10516. begin
  10517. Result := False;
  10518. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10519. Exit;
  10520. if StoredCount >= MAX_CMOV_REGISTERS then
  10521. { Arrays are full }
  10522. Exit;
  10523. { Remember that CMOV can't encode 8-bit registers }
  10524. case taicpu(p).opsize of
  10525. S_W:
  10526. RegSize := R_SUBW;
  10527. S_L:
  10528. RegSize := R_SUBD;
  10529. S_Q:
  10530. RegSize := R_SUBQ;
  10531. else
  10532. InternalError(2021100401);
  10533. end;
  10534. { See if the value has already been reserved for another CMOV instruction }
  10535. CurrentVal := taicpu(p).oper[0]^.val;
  10536. for X := 0 to StoredCount - 1 do
  10537. if ConstVals[X] = CurrentVal then
  10538. begin
  10539. ConstRegs[StoredCount] := ConstRegs[X];
  10540. ConstVals[StoredCount] := CurrentVal;
  10541. Result := True;
  10542. Inc(StoredCount);
  10543. { Don't increase CMOVCount this time, since we're re-using a register }
  10544. Exit;
  10545. end;
  10546. NewReg := GetIntRegisterBetween(RegSize, TmpUsedRegs, search_start_p, stop_search_p, True);
  10547. if NewReg = NR_NO then
  10548. { No free registers }
  10549. Exit;
  10550. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10551. up vying for the same register }
  10552. IncludeRegInUsedRegs(NewReg, TmpUsedRegs);
  10553. ConstRegs[StoredCount] := NewReg;
  10554. ConstVals[StoredCount] := CurrentVal;
  10555. Inc(StoredCount);
  10556. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10557. MOV required adds complexity and will cause diminishing returns
  10558. sooner than normal. This is more of an approximate weighting than
  10559. anything else. }
  10560. Inc(CMOVCount);
  10561. Result := True;
  10562. end;
  10563. {$endif i8086}
  10564. begin
  10565. result:=false;
  10566. if GetNextInstruction(p,hp1) then
  10567. begin
  10568. if (hp1.typ=ait_label) then
  10569. begin
  10570. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10571. Exit;
  10572. end
  10573. else if (hp1.typ<>ait_instruction) then
  10574. Exit;
  10575. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10576. if (
  10577. (
  10578. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10579. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10580. (Taicpu(hp1).oper[0]^.val=1)
  10581. ) or
  10582. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10583. ) and
  10584. GetNextInstruction(hp1,hp2) and
  10585. SkipAligns(hp2, hp2) and
  10586. (hp2.typ = ait_label) and
  10587. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10588. { jb @@1 cmc
  10589. inc/dec operand --> adc/sbb operand,0
  10590. @@1:
  10591. ... and ...
  10592. jnb @@1
  10593. inc/dec operand --> adc/sbb operand,0
  10594. @@1: }
  10595. begin
  10596. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10597. begin
  10598. case taicpu(hp1).opcode of
  10599. A_INC,
  10600. A_ADD:
  10601. carryadd_opcode:=A_ADC;
  10602. A_DEC,
  10603. A_SUB:
  10604. carryadd_opcode:=A_SBB;
  10605. else
  10606. InternalError(2021011001);
  10607. end;
  10608. Taicpu(p).clearop(0);
  10609. Taicpu(p).ops:=0;
  10610. Taicpu(p).is_jmp:=false;
  10611. Taicpu(p).opcode:=A_CMC;
  10612. Taicpu(p).condition:=C_NONE;
  10613. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10614. Taicpu(hp1).ops:=2;
  10615. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10616. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10617. else
  10618. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10619. Taicpu(hp1).loadconst(0,0);
  10620. Taicpu(hp1).opcode:=carryadd_opcode;
  10621. result:=true;
  10622. exit;
  10623. end
  10624. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10625. begin
  10626. case taicpu(hp1).opcode of
  10627. A_INC,
  10628. A_ADD:
  10629. carryadd_opcode:=A_ADC;
  10630. A_DEC,
  10631. A_SUB:
  10632. carryadd_opcode:=A_SBB;
  10633. else
  10634. InternalError(2021011002);
  10635. end;
  10636. Taicpu(hp1).ops:=2;
  10637. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10638. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10639. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10640. else
  10641. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10642. Taicpu(hp1).loadconst(0,0);
  10643. Taicpu(hp1).opcode:=carryadd_opcode;
  10644. RemoveCurrentP(p, hp1);
  10645. result:=true;
  10646. exit;
  10647. end
  10648. {
  10649. jcc @@1 setcc tmpreg
  10650. inc/dec/add/sub operand -> (movzx tmpreg)
  10651. @@1: add/sub tmpreg,operand
  10652. While this increases code size slightly, it makes the code much faster if the
  10653. jump is unpredictable
  10654. }
  10655. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10656. begin
  10657. { search for an available register which is volatile }
  10658. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10659. if increg <> NR_NO then
  10660. begin
  10661. { We don't need to check if tmpreg is in hp1 or not, because
  10662. it will be marked as in use at p (if not, this is
  10663. indictive of a compiler bug). }
  10664. TAsmLabel(symbol).decrefs;
  10665. Taicpu(p).clearop(0);
  10666. Taicpu(p).ops:=1;
  10667. Taicpu(p).is_jmp:=false;
  10668. Taicpu(p).opcode:=A_SETcc;
  10669. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10670. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10671. Taicpu(p).loadreg(0,increg);
  10672. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10673. begin
  10674. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10675. R_SUBW:
  10676. begin
  10677. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10678. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10679. end;
  10680. R_SUBD:
  10681. begin
  10682. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10683. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10684. end;
  10685. {$ifdef x86_64}
  10686. R_SUBQ:
  10687. begin
  10688. { MOVZX doesn't have a 64-bit variant, because
  10689. the 32-bit version implicitly zeroes the
  10690. upper 32-bits of the destination register }
  10691. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10692. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10693. setsubreg(tmpreg, R_SUBQ);
  10694. end;
  10695. {$endif x86_64}
  10696. else
  10697. Internalerror(2020030601);
  10698. end;
  10699. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10700. asml.InsertAfter(hp2,p);
  10701. end
  10702. else
  10703. tmpreg := increg;
  10704. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10705. begin
  10706. Taicpu(hp1).ops:=2;
  10707. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10708. end;
  10709. Taicpu(hp1).loadreg(0,tmpreg);
  10710. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10711. Result := True;
  10712. { p is no longer a Jcc instruction, so exit }
  10713. Exit;
  10714. end;
  10715. end;
  10716. end;
  10717. { Detect the following:
  10718. jmp<cond> @Lbl1
  10719. jmp @Lbl2
  10720. ...
  10721. @Lbl1:
  10722. ret
  10723. Change to:
  10724. jmp<inv_cond> @Lbl2
  10725. ret
  10726. }
  10727. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10728. begin
  10729. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10730. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10731. MatchInstruction(hp2,A_RET,[S_NO]) then
  10732. begin
  10733. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10734. { Change label address to that of the unconditional jump }
  10735. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10736. TAsmLabel(symbol).DecRefs;
  10737. taicpu(hp1).opcode := A_RET;
  10738. taicpu(hp1).is_jmp := false;
  10739. taicpu(hp1).ops := taicpu(hp2).ops;
  10740. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10741. case taicpu(hp2).ops of
  10742. 0:
  10743. taicpu(hp1).clearop(0);
  10744. 1:
  10745. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10746. else
  10747. internalerror(2016041302);
  10748. end;
  10749. end;
  10750. {$ifndef i8086}
  10751. end
  10752. {
  10753. convert
  10754. j<c> .L1
  10755. mov 1,reg
  10756. jmp .L2
  10757. .L1
  10758. mov 0,reg
  10759. .L2
  10760. into
  10761. mov 0,reg
  10762. set<not(c)> reg
  10763. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10764. would destroy the flag contents
  10765. }
  10766. else if MatchInstruction(hp1,A_MOV,[]) and
  10767. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10768. {$ifdef i386}
  10769. (
  10770. { Under i386, ESI, EDI, EBP and ESP
  10771. don't have an 8-bit representation }
  10772. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10773. ) and
  10774. {$endif i386}
  10775. (taicpu(hp1).oper[0]^.val=1) and
  10776. GetNextInstruction(hp1,hp2) and
  10777. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10778. GetNextInstruction(hp2,hp3) and
  10779. { skip align }
  10780. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10781. (hp3.typ=ait_label) and
  10782. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10783. (tai_label(hp3).labsym.getrefs=1) and
  10784. GetNextInstruction(hp3,hp4) and
  10785. MatchInstruction(hp4,A_MOV,[]) and
  10786. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10787. (taicpu(hp4).oper[0]^.val=0) and
  10788. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10789. GetNextInstruction(hp4,hp5) and
  10790. (hp5.typ=ait_label) and
  10791. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10792. (tai_label(hp5).labsym.getrefs=1) then
  10793. begin
  10794. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10795. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10796. { remove last label }
  10797. RemoveInstruction(hp5);
  10798. { remove second label }
  10799. RemoveInstruction(hp3);
  10800. { if align is present remove it }
  10801. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10802. RemoveInstruction(hp3);
  10803. { remove jmp }
  10804. RemoveInstruction(hp2);
  10805. if taicpu(hp1).opsize=S_B then
  10806. RemoveInstruction(hp1)
  10807. else
  10808. taicpu(hp1).loadconst(0,0);
  10809. taicpu(hp4).opcode:=A_SETcc;
  10810. taicpu(hp4).opsize:=S_B;
  10811. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10812. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10813. taicpu(hp4).opercnt:=1;
  10814. taicpu(hp4).ops:=1;
  10815. taicpu(hp4).freeop(1);
  10816. RemoveCurrentP(p);
  10817. Result:=true;
  10818. exit;
  10819. end
  10820. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.optimizecputype]) and
  10821. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  10822. begin
  10823. { check for
  10824. jCC xxx
  10825. <several movs>
  10826. xxx:
  10827. Also spot:
  10828. Jcc xxx
  10829. <several movs>
  10830. jmp xxx
  10831. Change to:
  10832. <several cmovs with inverted condition>
  10833. jmp xxx (only for the 2nd case)
  10834. }
  10835. hp2 := p;
  10836. hp_lblxxx := hp1;
  10837. hp_flagalloc := nil;
  10838. hp_stop := nil;
  10839. FoundMatchingJump := False;
  10840. { Remember the first instruction in the first block of MOVs }
  10841. hpmov1 := hp1;
  10842. TransferUsedRegs(TmpUsedRegs);
  10843. while assigned(hp_lblxxx) and
  10844. { stop on labels }
  10845. (hp_lblxxx.typ <> ait_label) do
  10846. begin
  10847. { Keep track of all integer registers that are used }
  10848. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  10849. if hp_lblxxx.typ = ait_instruction then
  10850. begin
  10851. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  10852. IsJumpToLabel(taicpu(hp_lblxxx)) then
  10853. begin
  10854. hp_stop := hp_lblxxx;
  10855. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  10856. begin
  10857. { We found Jcc xxx; <several movs>; Jmp xxx }
  10858. FoundMatchingJump := True;
  10859. Break;
  10860. end;
  10861. { If it's not the jump we're looking for, it's
  10862. possibly the "if..else" variant }
  10863. end
  10864. { Check to see if we have a valid MOV instruction instead }
  10865. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  10866. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  10867. Break
  10868. else
  10869. { This will be a valid MOV }
  10870. hp_stop := hp_lblxxx;
  10871. end;
  10872. hp2 := hp_lblxxx;
  10873. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  10874. end;
  10875. { Just make sure the last MOV is included if there's no jump }
  10876. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  10877. hp_stop := hp_lblxxx;
  10878. { Note, the logic behind using hp_stop over hp_lblxxx in the
  10879. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  10880. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  10881. jmp yyy; xxx:; movs; yyy:" variation }
  10882. if assigned(hp_lblxxx) and
  10883. (
  10884. { If we found JMP xxx, we don't actually need a label
  10885. (hp_lblxxx is the JMP instruction instead) }
  10886. FoundMatchingJump or
  10887. { Make sure we actually have the right label }
  10888. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  10889. ) then
  10890. begin
  10891. { Use TmpUsedRegs to track registers that we reserve }
  10892. { When allocating temporary registers, try to look one
  10893. instruction back, as defining them before a CMP or TEST
  10894. instruction will be faster, and also avoid picking a
  10895. register that was only just deallocated }
  10896. if GetLastInstruction(p, hp_prev) and
  10897. MatchInstruction(hp_prev, [A_CMP, A_TEST, A_BSR, A_BSF, A_COMISS, A_COMISD, A_UCOMISS, A_UCOMISD, A_VCOMISS, A_VCOMISD, A_VUCOMISS, A_VUCOMISD], []) then
  10898. begin
  10899. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  10900. for l := 0 to 1 do
  10901. with taicpu(hp_prev).oper[l]^ do
  10902. case typ of
  10903. top_reg:
  10904. if getregtype(reg) = R_INTREGISTER then
  10905. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  10906. top_ref:
  10907. begin
  10908. if
  10909. {$ifdef x86_64}
  10910. (ref^.base <> NR_RIP) and
  10911. {$endif x86_64}
  10912. (ref^.base <> NR_NO) then
  10913. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  10914. if (ref^.index <> NR_NO) then
  10915. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  10916. end
  10917. else
  10918. ;
  10919. end;
  10920. { When inserting instructions before hp_prev, try to insert
  10921. them before the allocation of the FLAGS register }
  10922. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  10923. { If not found, set it equal to hp_prev so it's something sensible }
  10924. hp_flagalloc := hp_prev;
  10925. hp_prev2 := nil;
  10926. { When dealing with a comparison against zero, take
  10927. note of the instruction before it to see if we can
  10928. move instructions further back in order to benefit
  10929. PostPeepholeOptTestOr.
  10930. }
  10931. if (
  10932. (
  10933. (taicpu(hp_prev).opcode = A_CMP) and
  10934. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  10935. ) or
  10936. (
  10937. (taicpu(hp_prev).opcode = A_TEST) and
  10938. (
  10939. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  10940. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  10941. )
  10942. )
  10943. ) and
  10944. GetLastInstruction(hp_prev, hp_prev2) then
  10945. begin
  10946. if (hp_prev2.typ = ait_instruction) and
  10947. { These instructions set the zero flag if the result is zero }
  10948. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  10949. begin
  10950. { Also mark all the registers in this previous instruction
  10951. as 'in use', even if they've just been deallocated }
  10952. for l := 0 to 1 do
  10953. with taicpu(hp_prev2).oper[l]^ do
  10954. case typ of
  10955. top_reg:
  10956. if getregtype(reg) = R_INTREGISTER then
  10957. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  10958. top_ref:
  10959. begin
  10960. if
  10961. {$ifdef x86_64}
  10962. (ref^.base <> NR_RIP) and
  10963. {$endif x86_64}
  10964. (ref^.base <> NR_NO) then
  10965. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  10966. if (ref^.index <> NR_NO) then
  10967. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  10968. end
  10969. else
  10970. ;
  10971. end;
  10972. end
  10973. else
  10974. { Unsuitable instruction }
  10975. hp_prev2 := nil;
  10976. end;
  10977. end
  10978. else
  10979. begin
  10980. hp_prev := p;
  10981. { When inserting instructions before hp_prev, try to insert
  10982. them before the allocation of the FLAGS register }
  10983. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  10984. { If not found, set it equal to p so it's something sensible }
  10985. hp_flagalloc := p;
  10986. hp_prev2 := nil;
  10987. end;
  10988. l := 0;
  10989. c := 0;
  10990. { Initialise RegWrites, ConstRegs and ConstVals }
  10991. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  10992. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  10993. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  10994. while assigned(hp1) and
  10995. { Stop on the label we found }
  10996. (hp1 <> hp_lblxxx) do
  10997. begin
  10998. case hp1.typ of
  10999. ait_instruction:
  11000. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11001. begin
  11002. if CanBeCMOV(hp1, hp_prev) then
  11003. Inc(l)
  11004. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11005. { CMOV with constants grows the code size }
  11006. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  11007. begin
  11008. { Register was reserved by TryCMOVConst and
  11009. stored on ConstRegs[c] }
  11010. end
  11011. else
  11012. Break;
  11013. end
  11014. else
  11015. Break;
  11016. else
  11017. ;
  11018. end;
  11019. GetNextInstruction(hp1,hp1);
  11020. end;
  11021. if (hp1 = hp_lblxxx) then
  11022. begin
  11023. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  11024. begin
  11025. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11026. TmpUsedRegs[R_INTREGISTER].Clear;
  11027. x := 0;
  11028. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  11029. condition := inverse_cond(taicpu(p).condition);
  11030. UpdateUsedRegs(tai(p.next));
  11031. hp1 := hpmov1;
  11032. repeat
  11033. if not Assigned(hp1) then
  11034. InternalError(2018062900);
  11035. if (hp1.typ = ait_instruction) then
  11036. begin
  11037. { Extra safeguard }
  11038. if (taicpu(hp1).opcode <> A_MOV) then
  11039. InternalError(2018062901);
  11040. if taicpu(hp1).oper[0]^.typ = top_const then
  11041. begin
  11042. if x >= MAX_CMOV_REGISTERS then
  11043. InternalError(2021100410);
  11044. { If it's in TmpUsedRegs, then this register
  11045. is being used more than once and hence has
  11046. already had its value defined (it gets
  11047. added to UsedRegs through AllocRegBetween
  11048. below) }
  11049. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11050. begin
  11051. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11052. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  11053. asml.InsertBefore(hp_new, hp_flagalloc);
  11054. if Assigned(hp_prev2) then
  11055. TrySwapMovOp(hp_prev2, hp_new);
  11056. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11057. end
  11058. else
  11059. { We just need an instruction between hp_prev and hp1
  11060. where we know the register is marked as in use }
  11061. hp_new := hpmov1;
  11062. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11063. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11064. Inc(x);
  11065. end;
  11066. taicpu(hp1).opcode := A_CMOVcc;
  11067. taicpu(hp1).condition := condition;
  11068. end;
  11069. UpdateUsedRegs(tai(hp1.next));
  11070. GetNextInstruction(hp1, hp1);
  11071. until (hp1 = hp_lblxxx);
  11072. hp2 := hp_lblxxx;
  11073. repeat
  11074. if not Assigned(hp2) then
  11075. InternalError(2018062910);
  11076. case hp2.typ of
  11077. ait_label:
  11078. { What we expected - break out of the loop (it won't be a dead label at the top of
  11079. a cluster because that was optimised at an earlier stage) }
  11080. Break;
  11081. ait_align:
  11082. { Go to the next entry until a label is found (may be multiple aligns before it) }
  11083. begin
  11084. hp2 := tai(hp2.Next);
  11085. Continue;
  11086. end;
  11087. ait_instruction:
  11088. begin
  11089. if taicpu(hp2).opcode<>A_JMP then
  11090. InternalError(2018062912);
  11091. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  11092. Break;
  11093. end
  11094. else
  11095. begin
  11096. { Might be a comment or temporary allocation entry }
  11097. if not (hp2.typ in SkipInstr) then
  11098. InternalError(2018062911);
  11099. hp2 := tai(hp2.Next);
  11100. Continue;
  11101. end;
  11102. end;
  11103. until False;
  11104. { Now we can safely decrement the reference count }
  11105. tasmlabel(symbol).decrefs;
  11106. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  11107. { Remove the original jump }
  11108. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  11109. if hp2.typ=ait_instruction then
  11110. begin
  11111. p := hp2;
  11112. Result := True;
  11113. end
  11114. else
  11115. begin
  11116. UpdateUsedRegs(tai(hp2.next));
  11117. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  11118. { Remove the label if this is its final reference }
  11119. if (tasmlabel(symbol).getrefs=0) then
  11120. begin
  11121. { Make sure the aligns get stripped too }
  11122. hp1 := tai(hp_lblxxx.Previous);
  11123. while Assigned(hp1) and (hp1.typ = ait_align) do
  11124. begin
  11125. hp_lblxxx := hp1;
  11126. hp1 := tai(hp_lblxxx.Previous);
  11127. end;
  11128. StripLabelFast(hp_lblxxx);
  11129. end;
  11130. end;
  11131. Exit;
  11132. end;
  11133. end
  11134. else if assigned(hp_lblxxx) and
  11135. { check further for
  11136. jCC xxx
  11137. <several movs 1>
  11138. jmp yyy
  11139. xxx:
  11140. <several movs 2>
  11141. yyy:
  11142. }
  11143. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11144. { hp1 should be pointing to jmp yyy }
  11145. MatchInstruction(hp1, A_JMP, []) and
  11146. { real label and jump, no further references to the
  11147. label are allowed }
  11148. (TAsmLabel(symbol).getrefs=1) and
  11149. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  11150. begin
  11151. hp_jump := hp1;
  11152. { Don't set c to zero }
  11153. l := 0;
  11154. w := 0;
  11155. GetNextInstruction(hp_lblxxx, hpmov2);
  11156. hp2 := hp_lblxxx;
  11157. hp_lblyyy := hpmov2;
  11158. while assigned(hp_lblyyy) and
  11159. { stop on labels }
  11160. (hp_lblyyy.typ <> ait_label) do
  11161. begin
  11162. { Keep track of all integer registers that are used }
  11163. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11164. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11165. Break;
  11166. hp2 := hp_lblyyy;
  11167. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  11168. end;
  11169. { Analyse the second batch of MOVs to see if the setup is valid }
  11170. hp1 := hpmov2;
  11171. while assigned(hp1) and
  11172. (hp1 <> hp_lblyyy) do
  11173. begin
  11174. case hp1.typ of
  11175. ait_instruction:
  11176. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11177. begin
  11178. if CanBeCMOV(hp1, hp_prev) then
  11179. Inc(l)
  11180. else if not (cs_opt_size in current_settings.optimizerswitches)
  11181. { CMOV with constants grows the code size }
  11182. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  11183. begin
  11184. { Register was reserved by TryCMOVConst and
  11185. stored on ConstRegs[c] }
  11186. end
  11187. else
  11188. Break;
  11189. end
  11190. else
  11191. Break;
  11192. else
  11193. ;
  11194. end;
  11195. GetNextInstruction(hp1,hp1);
  11196. end;
  11197. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11198. TmpUsedRegs[R_INTREGISTER].Clear;
  11199. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11200. (hp1 = hp_lblyyy) and
  11201. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  11202. begin
  11203. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  11204. second_condition := taicpu(p).condition;
  11205. condition := inverse_cond(taicpu(p).condition);
  11206. UpdateUsedRegs(tai(p.next));
  11207. { Scan through the first set of MOVs to update UsedRegs,
  11208. but don't process them yet }
  11209. hp1 := hpmov1;
  11210. repeat
  11211. if not Assigned(hp1) then
  11212. InternalError(2018062901);
  11213. UpdateUsedRegs(tai(hp1.next));
  11214. GetNextInstruction(hp1, hp1);
  11215. until (hp1 = hp_lblxxx);
  11216. UpdateUsedRegs(tai(hp_lblxxx.next));
  11217. { Process the second set of MOVs first,
  11218. because if a destination register is
  11219. shared between the first and second MOV
  11220. sets, it is more efficient to turn the
  11221. first one into a MOV instruction and place
  11222. it before the CMP if possible, but we
  11223. won't know which registers are shared
  11224. until we've processed at least one list,
  11225. so we might as well make it the second
  11226. one since that won't be modified again. }
  11227. hp1 := hpmov2;
  11228. repeat
  11229. if not Assigned(hp1) then
  11230. InternalError(2018062902);
  11231. if (hp1.typ = ait_instruction) then
  11232. begin
  11233. { Extra safeguard }
  11234. if (taicpu(hp1).opcode <> A_MOV) then
  11235. InternalError(2018062903);
  11236. if taicpu(hp1).oper[0]^.typ = top_const then
  11237. begin
  11238. RegMatch := False;
  11239. for x := 0 to c - 1 do
  11240. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11241. begin
  11242. RegMatch := True;
  11243. { If it's in TmpUsedRegs, then this register
  11244. is being used more than once and hence has
  11245. already had its value defined (it gets
  11246. added to UsedRegs through AllocRegBetween
  11247. below) }
  11248. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11249. begin
  11250. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11251. asml.InsertBefore(hp_new, hp_flagalloc);
  11252. if Assigned(hp_prev2) then
  11253. TrySwapMovOp(hp_prev2, hp_new);
  11254. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11255. end
  11256. else
  11257. { We just need an instruction between hp_prev and hp1
  11258. where we know the register is marked as in use }
  11259. hp_new := hpmov2;
  11260. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11261. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11262. Break;
  11263. end;
  11264. if not RegMatch then
  11265. InternalError(2021100411);
  11266. end;
  11267. taicpu(hp1).opcode := A_CMOVcc;
  11268. taicpu(hp1).condition := second_condition;
  11269. { Store these writes to search for
  11270. duplicates later on }
  11271. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11272. Inc(w);
  11273. end;
  11274. UpdateUsedRegs(tai(hp1.next));
  11275. GetNextInstruction(hp1, hp1);
  11276. until (hp1 = hp_lblyyy);
  11277. { Now do the first set of MOVs }
  11278. hp1 := hpmov1;
  11279. repeat
  11280. if not Assigned(hp1) then
  11281. InternalError(2018062904);
  11282. if (hp1.typ = ait_instruction) then
  11283. begin
  11284. RegMatch := False;
  11285. { Extra safeguard }
  11286. if (taicpu(hp1).opcode <> A_MOV) then
  11287. InternalError(2018062905);
  11288. { Search through the RegWrites list to see
  11289. if there are any opposing CMOV pairs that
  11290. write to the same register }
  11291. for x := 0 to w - 1 do
  11292. if (RegWrites[x] = taicpu(hp1).oper[1]^.reg) then
  11293. begin
  11294. { We have a match. Keep this as a MOV }
  11295. { Move ahead in preparation }
  11296. GetNextInstruction(hp1, hp1);
  11297. RegMatch := True;
  11298. Break;
  11299. end;
  11300. if RegMatch then
  11301. Continue;
  11302. if taicpu(hp1).oper[0]^.typ = top_const then
  11303. begin
  11304. RegMatch := False;
  11305. for x := 0 to c - 1 do
  11306. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11307. begin
  11308. RegMatch := True;
  11309. { If it's in TmpUsedRegs, then this register
  11310. is being used more than once and hence has
  11311. already had its value defined (it gets
  11312. added to UsedRegs through AllocRegBetween
  11313. below) }
  11314. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11315. begin
  11316. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11317. asml.InsertBefore(hp_new, hp_flagalloc);
  11318. if Assigned(hp_prev2) then
  11319. TrySwapMovOp(hp_prev2, hp_new);
  11320. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11321. end
  11322. else
  11323. { We just need an instruction between hp_prev and hp1
  11324. where we know the register is marked as in use }
  11325. hp_new := hpmov1;
  11326. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11327. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11328. Break;
  11329. end;
  11330. if not RegMatch then
  11331. InternalError(2021100412);
  11332. end;
  11333. taicpu(hp1).opcode := A_CMOVcc;
  11334. taicpu(hp1).condition := condition;
  11335. end;
  11336. GetNextInstruction(hp1, hp1);
  11337. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11338. UpdateUsedRegs(tai(hp_jump.next));
  11339. UpdateUsedRegs(tai(hp_lblyyy.next));
  11340. { Get first instruction after label }
  11341. hp1 := p;
  11342. GetNextInstruction(hp_lblyyy, p);
  11343. { Don't dereference yet, as doing so will cause
  11344. GetNextInstruction to skip the label and
  11345. optional align marker. [Kit] }
  11346. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11347. { remove Jcc }
  11348. RemoveInstruction(hp1);
  11349. { Now we can safely decrement it }
  11350. tasmlabel(symbol).decrefs;
  11351. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11352. { Make sure the aligns get stripped too }
  11353. hp1 := tai(hp_lblxxx.Previous);
  11354. while Assigned(hp1) and (hp1.typ = ait_align) do
  11355. begin
  11356. hp_lblxxx := hp1;
  11357. hp1 := tai(hp_lblxxx.Previous);
  11358. end;
  11359. StripLabelFast(hp_lblxxx);
  11360. { remove jmp }
  11361. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11362. RemoveInstruction(hp_jump);
  11363. { As before, now we can safely decrement it }
  11364. TAsmLabel(symbol).decrefs;
  11365. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11366. if TAsmLabel(symbol).getrefs = 0 then
  11367. begin
  11368. { Make sure the aligns get stripped too }
  11369. hp1 := tai(hp_lblyyy.Previous);
  11370. while Assigned(hp1) and (hp1.typ = ait_align) do
  11371. begin
  11372. hp_lblyyy := hp1;
  11373. hp1 := tai(hp_lblyyy.Previous);
  11374. end;
  11375. StripLabelFast(hp_lblyyy);
  11376. end;
  11377. if Assigned(p) then
  11378. result := True;
  11379. exit;
  11380. end;
  11381. end;
  11382. end;
  11383. {$endif i8086}
  11384. end;
  11385. end;
  11386. end;
  11387. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11388. var
  11389. hp1,hp2,hp3: tai;
  11390. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11391. NewSize: TOpSize;
  11392. NewRegSize: TSubRegister;
  11393. Limit: TCgInt;
  11394. SwapOper: POper;
  11395. begin
  11396. result:=false;
  11397. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11398. GetNextInstruction(p,hp1) and
  11399. (hp1.typ = ait_instruction);
  11400. if reg_and_hp1_is_instr and
  11401. (
  11402. (taicpu(hp1).opcode <> A_LEA) or
  11403. { If the LEA instruction can be converted into an arithmetic instruction,
  11404. it may be possible to then fold it. }
  11405. (
  11406. { If the flags register is in use, don't change the instruction
  11407. to an ADD otherwise this will scramble the flags. [Kit] }
  11408. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11409. ConvertLEA(taicpu(hp1))
  11410. )
  11411. ) and
  11412. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11413. GetNextInstruction(hp1,hp2) and
  11414. MatchInstruction(hp2,A_MOV,[]) and
  11415. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11416. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11417. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11418. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11419. {$ifdef i386}
  11420. { not all registers have byte size sub registers on i386 }
  11421. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11422. {$endif i386}
  11423. (((taicpu(hp1).ops=2) and
  11424. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11425. ((taicpu(hp1).ops=1) and
  11426. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11427. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11428. begin
  11429. { change movsX/movzX reg/ref, reg2
  11430. add/sub/or/... reg3/$const, reg2
  11431. mov reg2 reg/ref
  11432. to add/sub/or/... reg3/$const, reg/ref }
  11433. { by example:
  11434. movswl %si,%eax movswl %si,%eax p
  11435. decl %eax addl %edx,%eax hp1
  11436. movw %ax,%si movw %ax,%si hp2
  11437. ->
  11438. movswl %si,%eax movswl %si,%eax p
  11439. decw %eax addw %edx,%eax hp1
  11440. movw %ax,%si movw %ax,%si hp2
  11441. }
  11442. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11443. {
  11444. ->
  11445. movswl %si,%eax movswl %si,%eax p
  11446. decw %si addw %dx,%si hp1
  11447. movw %ax,%si movw %ax,%si hp2
  11448. }
  11449. case taicpu(hp1).ops of
  11450. 1:
  11451. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11452. 2:
  11453. begin
  11454. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11455. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11456. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11457. end;
  11458. else
  11459. internalerror(2008042702);
  11460. end;
  11461. {
  11462. ->
  11463. decw %si addw %dx,%si p
  11464. }
  11465. DebugMsg(SPeepholeOptimization + 'var3',p);
  11466. RemoveCurrentP(p, hp1);
  11467. RemoveInstruction(hp2);
  11468. Result := True;
  11469. Exit;
  11470. end;
  11471. if reg_and_hp1_is_instr and
  11472. (taicpu(hp1).opcode = A_MOV) and
  11473. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11474. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11475. {$ifdef x86_64}
  11476. { check for implicit extension to 64 bit }
  11477. or
  11478. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11479. (taicpu(hp1).opsize=S_Q) and
  11480. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11481. )
  11482. {$endif x86_64}
  11483. )
  11484. then
  11485. begin
  11486. { change
  11487. movx %reg1,%reg2
  11488. mov %reg2,%reg3
  11489. dealloc %reg2
  11490. into
  11491. movx %reg,%reg3
  11492. }
  11493. TransferUsedRegs(TmpUsedRegs);
  11494. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11495. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11496. begin
  11497. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11498. {$ifdef x86_64}
  11499. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11500. (taicpu(hp1).opsize=S_Q) then
  11501. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11502. else
  11503. {$endif x86_64}
  11504. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11505. RemoveInstruction(hp1);
  11506. Result := True;
  11507. Exit;
  11508. end;
  11509. end;
  11510. if reg_and_hp1_is_instr and
  11511. ((taicpu(hp1).opcode=A_MOV) or
  11512. (taicpu(hp1).opcode=A_ADD) or
  11513. (taicpu(hp1).opcode=A_SUB) or
  11514. (taicpu(hp1).opcode=A_CMP) or
  11515. (taicpu(hp1).opcode=A_OR) or
  11516. (taicpu(hp1).opcode=A_XOR) or
  11517. (taicpu(hp1).opcode=A_AND)
  11518. ) and
  11519. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11520. begin
  11521. AndTest := (taicpu(hp1).opcode=A_AND) and
  11522. GetNextInstruction(hp1, hp2) and
  11523. (hp2.typ = ait_instruction) and
  11524. (
  11525. (
  11526. (taicpu(hp2).opcode=A_TEST) and
  11527. (
  11528. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11529. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11530. (
  11531. { If the AND and TEST instructions share a constant, this is also valid }
  11532. (taicpu(hp1).oper[0]^.typ = top_const) and
  11533. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11534. )
  11535. ) and
  11536. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11537. ) or
  11538. (
  11539. (taicpu(hp2).opcode=A_CMP) and
  11540. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11541. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11542. )
  11543. );
  11544. { change
  11545. movx (oper),%reg2
  11546. and $x,%reg2
  11547. test %reg2,%reg2
  11548. dealloc %reg2
  11549. into
  11550. op %reg1,%reg3
  11551. if the second op accesses only the bits stored in reg1
  11552. }
  11553. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11554. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11555. (taicpu(hp1).oper[0]^.typ = top_const) and
  11556. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11557. AndTest then
  11558. begin
  11559. { Check if the AND constant is in range }
  11560. case taicpu(p).opsize of
  11561. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11562. begin
  11563. NewSize := S_B;
  11564. Limit := $FF;
  11565. end;
  11566. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11567. begin
  11568. NewSize := S_W;
  11569. Limit := $FFFF;
  11570. end;
  11571. {$ifdef x86_64}
  11572. S_LQ:
  11573. begin
  11574. NewSize := S_L;
  11575. Limit := $FFFFFFFF;
  11576. end;
  11577. {$endif x86_64}
  11578. else
  11579. InternalError(2021120303);
  11580. end;
  11581. if (
  11582. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11583. { Check for negative operands }
  11584. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11585. ) and
  11586. GetNextInstruction(hp2,hp3) and
  11587. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11588. (taicpu(hp3).condition in [C_E,C_NE]) then
  11589. begin
  11590. TransferUsedRegs(TmpUsedRegs);
  11591. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11592. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11593. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11594. begin
  11595. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11596. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11597. taicpu(hp1).opcode := A_TEST;
  11598. taicpu(hp1).opsize := NewSize;
  11599. RemoveInstruction(hp2);
  11600. RemoveCurrentP(p, hp1);
  11601. Result:=true;
  11602. exit;
  11603. end;
  11604. end;
  11605. end;
  11606. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11607. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11608. (taicpu(hp1).opsize=S_B)) or
  11609. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11610. (taicpu(hp1).opsize=S_W))
  11611. {$ifdef x86_64}
  11612. or ((taicpu(p).opsize=S_LQ) and
  11613. (taicpu(hp1).opsize=S_L))
  11614. {$endif x86_64}
  11615. ) and
  11616. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11617. begin
  11618. { change
  11619. movx %reg1,%reg2
  11620. op %reg2,%reg3
  11621. dealloc %reg2
  11622. into
  11623. op %reg1,%reg3
  11624. if the second op accesses only the bits stored in reg1
  11625. }
  11626. TransferUsedRegs(TmpUsedRegs);
  11627. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11628. if AndTest then
  11629. begin
  11630. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11631. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11632. end
  11633. else
  11634. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11635. if not RegUsed then
  11636. begin
  11637. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11638. if taicpu(p).oper[0]^.typ=top_reg then
  11639. begin
  11640. case taicpu(hp1).opsize of
  11641. S_B:
  11642. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11643. S_W:
  11644. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11645. S_L:
  11646. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11647. else
  11648. Internalerror(2020102301);
  11649. end;
  11650. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11651. end
  11652. else
  11653. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11654. RemoveCurrentP(p);
  11655. if AndTest then
  11656. RemoveInstruction(hp2);
  11657. result:=true;
  11658. exit;
  11659. end;
  11660. end
  11661. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11662. (
  11663. { Bitwise operations only }
  11664. (taicpu(hp1).opcode=A_AND) or
  11665. (taicpu(hp1).opcode=A_TEST) or
  11666. (
  11667. (taicpu(hp1).oper[0]^.typ = top_const) and
  11668. (
  11669. (taicpu(hp1).opcode=A_OR) or
  11670. (taicpu(hp1).opcode=A_XOR)
  11671. )
  11672. )
  11673. ) and
  11674. (
  11675. (taicpu(hp1).oper[0]^.typ = top_const) or
  11676. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11677. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11678. ) then
  11679. begin
  11680. { change
  11681. movx %reg2,%reg2
  11682. op const,%reg2
  11683. into
  11684. op const,%reg2 (smaller version)
  11685. movx %reg2,%reg2
  11686. also change
  11687. movx %reg1,%reg2
  11688. and/test (oper),%reg2
  11689. dealloc %reg2
  11690. into
  11691. and/test (oper),%reg1
  11692. }
  11693. case taicpu(p).opsize of
  11694. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11695. begin
  11696. NewSize := S_B;
  11697. NewRegSize := R_SUBL;
  11698. Limit := $FF;
  11699. end;
  11700. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11701. begin
  11702. NewSize := S_W;
  11703. NewRegSize := R_SUBW;
  11704. Limit := $FFFF;
  11705. end;
  11706. {$ifdef x86_64}
  11707. S_LQ:
  11708. begin
  11709. NewSize := S_L;
  11710. NewRegSize := R_SUBD;
  11711. Limit := $FFFFFFFF;
  11712. end;
  11713. {$endif x86_64}
  11714. else
  11715. Internalerror(2021120302);
  11716. end;
  11717. TransferUsedRegs(TmpUsedRegs);
  11718. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11719. if AndTest then
  11720. begin
  11721. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11722. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11723. end
  11724. else
  11725. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11726. if
  11727. (
  11728. (taicpu(p).opcode = A_MOVZX) and
  11729. (
  11730. (taicpu(hp1).opcode=A_AND) or
  11731. (taicpu(hp1).opcode=A_TEST)
  11732. ) and
  11733. not (
  11734. { If both are references, then the final instruction will have
  11735. both operands as references, which is not allowed }
  11736. (taicpu(p).oper[0]^.typ = top_ref) and
  11737. (taicpu(hp1).oper[0]^.typ = top_ref)
  11738. ) and
  11739. not RegUsed
  11740. ) or
  11741. (
  11742. (
  11743. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  11744. not RegUsed
  11745. ) and
  11746. (taicpu(p).oper[0]^.typ = top_reg) and
  11747. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11748. (taicpu(hp1).oper[0]^.typ = top_const) and
  11749. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  11750. ) then
  11751. begin
  11752. {$if defined(i386) or defined(i8086)}
  11753. { If the target size is 8-bit, make sure we can actually encode it }
  11754. if (NewRegSize = R_SUBL) and (taicpu(hp1).oper[0]^.typ = top_reg) and not (GetSupReg(taicpu(hp1).oper[0]^.reg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  11755. Exit;
  11756. {$endif i386 or i8086}
  11757. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  11758. taicpu(hp1).opsize := NewSize;
  11759. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11760. if AndTest then
  11761. begin
  11762. RemoveInstruction(hp2);
  11763. if not RegUsed then
  11764. begin
  11765. taicpu(hp1).opcode := A_TEST;
  11766. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  11767. begin
  11768. { Make sure the reference is the second operand }
  11769. SwapOper := taicpu(hp1).oper[0];
  11770. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  11771. taicpu(hp1).oper[1] := SwapOper;
  11772. end;
  11773. end;
  11774. end;
  11775. case taicpu(hp1).oper[0]^.typ of
  11776. top_reg:
  11777. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  11778. top_const:
  11779. { For the AND/TEST case }
  11780. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  11781. else
  11782. ;
  11783. end;
  11784. if RegUsed then
  11785. begin
  11786. AsmL.Remove(p);
  11787. AsmL.InsertAfter(p, hp1);
  11788. p := hp1;
  11789. end
  11790. else
  11791. RemoveCurrentP(p, hp1);
  11792. result:=true;
  11793. exit;
  11794. end;
  11795. end;
  11796. end;
  11797. if reg_and_hp1_is_instr and
  11798. (taicpu(p).oper[0]^.typ = top_reg) and
  11799. (
  11800. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  11801. ) and
  11802. (taicpu(hp1).oper[0]^.typ = top_const) and
  11803. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11804. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11805. { Minimum shift value allowed is the bit difference between the sizes }
  11806. (taicpu(hp1).oper[0]^.val >=
  11807. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11808. 8 * (
  11809. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  11810. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11811. )
  11812. ) then
  11813. begin
  11814. { For:
  11815. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  11816. shl/sal ##, %reg1
  11817. Remove the movsx/movzx instruction if the shift overwrites the
  11818. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  11819. }
  11820. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  11821. RemoveCurrentP(p, hp1);
  11822. Result := True;
  11823. Exit;
  11824. end
  11825. else if reg_and_hp1_is_instr and
  11826. (taicpu(p).oper[0]^.typ = top_reg) and
  11827. (
  11828. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  11829. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  11830. ) and
  11831. (taicpu(hp1).oper[0]^.typ = top_const) and
  11832. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11833. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11834. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  11835. (taicpu(hp1).oper[0]^.val <
  11836. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11837. 8 * (
  11838. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11839. )
  11840. ) then
  11841. begin
  11842. { For:
  11843. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  11844. sar ##, %reg1 shr ##, %reg1
  11845. Move the shift to before the movx instruction if the shift value
  11846. is not too large.
  11847. }
  11848. asml.Remove(hp1);
  11849. asml.InsertBefore(hp1, p);
  11850. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11851. case taicpu(p).opsize of
  11852. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  11853. taicpu(hp1).opsize := S_B;
  11854. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  11855. taicpu(hp1).opsize := S_W;
  11856. {$ifdef x86_64}
  11857. S_LQ:
  11858. taicpu(hp1).opsize := S_L;
  11859. {$endif}
  11860. else
  11861. InternalError(2020112401);
  11862. end;
  11863. if (taicpu(hp1).opcode = A_SHR) then
  11864. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  11865. else
  11866. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  11867. Result := True;
  11868. end;
  11869. if reg_and_hp1_is_instr and
  11870. (taicpu(p).oper[0]^.typ = top_reg) and
  11871. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11872. (
  11873. (taicpu(hp1).opcode = taicpu(p).opcode)
  11874. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  11875. {$ifdef x86_64}
  11876. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  11877. {$endif x86_64}
  11878. ) then
  11879. begin
  11880. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  11881. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  11882. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11883. begin
  11884. {
  11885. For example:
  11886. movzbw %al,%ax
  11887. movzwl %ax,%eax
  11888. Compress into:
  11889. movzbl %al,%eax
  11890. }
  11891. RegUsed := False;
  11892. case taicpu(p).opsize of
  11893. S_BW:
  11894. case taicpu(hp1).opsize of
  11895. S_WL:
  11896. begin
  11897. taicpu(p).opsize := S_BL;
  11898. RegUsed := True;
  11899. end;
  11900. {$ifdef x86_64}
  11901. S_WQ:
  11902. begin
  11903. if taicpu(p).opcode = A_MOVZX then
  11904. begin
  11905. taicpu(p).opsize := S_BL;
  11906. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11907. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11908. end
  11909. else
  11910. taicpu(p).opsize := S_BQ;
  11911. RegUsed := True;
  11912. end;
  11913. {$endif x86_64}
  11914. else
  11915. ;
  11916. end;
  11917. {$ifdef x86_64}
  11918. S_BL:
  11919. case taicpu(hp1).opsize of
  11920. S_LQ:
  11921. begin
  11922. if taicpu(p).opcode = A_MOVZX then
  11923. begin
  11924. taicpu(p).opsize := S_BL;
  11925. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11926. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11927. end
  11928. else
  11929. taicpu(p).opsize := S_BQ;
  11930. RegUsed := True;
  11931. end;
  11932. else
  11933. ;
  11934. end;
  11935. S_WL:
  11936. case taicpu(hp1).opsize of
  11937. S_LQ:
  11938. begin
  11939. if taicpu(p).opcode = A_MOVZX then
  11940. begin
  11941. taicpu(p).opsize := S_WL;
  11942. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11943. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11944. end
  11945. else
  11946. taicpu(p).opsize := S_WQ;
  11947. RegUsed := True;
  11948. end;
  11949. else
  11950. ;
  11951. end;
  11952. {$endif x86_64}
  11953. else
  11954. ;
  11955. end;
  11956. if RegUsed then
  11957. begin
  11958. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  11959. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  11960. RemoveInstruction(hp1);
  11961. Result := True;
  11962. Exit;
  11963. end;
  11964. end;
  11965. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  11966. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  11967. GetNextInstruction(hp1, hp2) and
  11968. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  11969. (
  11970. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  11971. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  11972. {$ifdef x86_64}
  11973. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  11974. {$endif x86_64}
  11975. ) and
  11976. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11977. (
  11978. (
  11979. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11980. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11981. ) or
  11982. (
  11983. { Only allow the operands in reverse order for TEST instructions }
  11984. (taicpu(hp2).opcode = A_TEST) and
  11985. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11986. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  11987. )
  11988. ) then
  11989. begin
  11990. {
  11991. For example:
  11992. movzbl %al,%eax
  11993. movzbl (ref),%edx
  11994. andl %edx,%eax
  11995. (%edx deallocated)
  11996. Change to:
  11997. andb (ref),%al
  11998. movzbl %al,%eax
  11999. Rules are:
  12000. - First two instructions have the same opcode and opsize
  12001. - First instruction's operands are the same super-register
  12002. - Second instruction operates on a different register
  12003. - Third instruction is AND, OR, XOR or TEST
  12004. - Third instruction's operands are the destination registers of the first two instructions
  12005. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12006. - Second instruction's destination register is deallocated afterwards
  12007. }
  12008. TransferUsedRegs(TmpUsedRegs);
  12009. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12010. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12011. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12012. begin
  12013. case taicpu(p).opsize of
  12014. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12015. NewSize := S_B;
  12016. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12017. NewSize := S_W;
  12018. {$ifdef x86_64}
  12019. S_LQ:
  12020. NewSize := S_L;
  12021. {$endif x86_64}
  12022. else
  12023. InternalError(2021120301);
  12024. end;
  12025. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12026. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12027. taicpu(hp2).opsize := NewSize;
  12028. RemoveInstruction(hp1);
  12029. { With TEST, it's best to keep the MOVX instruction at the top }
  12030. if (taicpu(hp2).opcode <> A_TEST) then
  12031. begin
  12032. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12033. asml.Remove(p);
  12034. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12035. asml.InsertAfter(p, hp2);
  12036. p := hp2;
  12037. end
  12038. else
  12039. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12040. Result := True;
  12041. Exit;
  12042. end;
  12043. end;
  12044. end;
  12045. if taicpu(p).opcode=A_MOVZX then
  12046. begin
  12047. { removes superfluous And's after movzx's }
  12048. if reg_and_hp1_is_instr and
  12049. (taicpu(hp1).opcode = A_AND) and
  12050. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12051. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12052. {$ifdef x86_64}
  12053. { check for implicit extension to 64 bit }
  12054. or
  12055. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12056. (taicpu(hp1).opsize=S_Q) and
  12057. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12058. )
  12059. {$endif x86_64}
  12060. )
  12061. then
  12062. begin
  12063. case taicpu(p).opsize Of
  12064. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12065. if (taicpu(hp1).oper[0]^.val = $ff) then
  12066. begin
  12067. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12068. RemoveInstruction(hp1);
  12069. Result:=true;
  12070. exit;
  12071. end;
  12072. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12073. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12074. begin
  12075. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12076. RemoveInstruction(hp1);
  12077. Result:=true;
  12078. exit;
  12079. end;
  12080. {$ifdef x86_64}
  12081. S_LQ:
  12082. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12083. begin
  12084. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12085. RemoveInstruction(hp1);
  12086. Result:=true;
  12087. exit;
  12088. end;
  12089. {$endif x86_64}
  12090. else
  12091. ;
  12092. end;
  12093. { we cannot get rid of the and, but can we get rid of the movz ?}
  12094. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12095. begin
  12096. case taicpu(p).opsize Of
  12097. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12098. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12099. begin
  12100. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12101. RemoveCurrentP(p,hp1);
  12102. Result:=true;
  12103. exit;
  12104. end;
  12105. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12106. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12107. begin
  12108. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12109. RemoveCurrentP(p,hp1);
  12110. Result:=true;
  12111. exit;
  12112. end;
  12113. {$ifdef x86_64}
  12114. S_LQ:
  12115. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12116. begin
  12117. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12118. RemoveCurrentP(p,hp1);
  12119. Result:=true;
  12120. exit;
  12121. end;
  12122. {$endif x86_64}
  12123. else
  12124. ;
  12125. end;
  12126. end;
  12127. end;
  12128. { changes some movzx constructs to faster synonyms (all examples
  12129. are given with eax/ax, but are also valid for other registers)}
  12130. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12131. begin
  12132. case taicpu(p).opsize of
  12133. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12134. (the machine code is equivalent to movzbl %al,%eax), but the
  12135. code generator still generates that assembler instruction and
  12136. it is silently converted. This should probably be checked.
  12137. [Kit] }
  12138. S_BW:
  12139. begin
  12140. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12141. (
  12142. not IsMOVZXAcceptable
  12143. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12144. or (
  12145. (cs_opt_size in current_settings.optimizerswitches) and
  12146. (taicpu(p).oper[1]^.reg = NR_AX)
  12147. )
  12148. ) then
  12149. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12150. begin
  12151. DebugMsg(SPeepholeOptimization + 'var7',p);
  12152. taicpu(p).opcode := A_AND;
  12153. taicpu(p).changeopsize(S_W);
  12154. taicpu(p).loadConst(0,$ff);
  12155. Result := True;
  12156. end
  12157. else if not IsMOVZXAcceptable and
  12158. GetNextInstruction(p, hp1) and
  12159. (tai(hp1).typ = ait_instruction) and
  12160. (taicpu(hp1).opcode = A_AND) and
  12161. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12162. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12163. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12164. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12165. begin
  12166. DebugMsg(SPeepholeOptimization + 'var8',p);
  12167. taicpu(p).opcode := A_MOV;
  12168. taicpu(p).changeopsize(S_W);
  12169. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12170. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12171. Result := True;
  12172. end;
  12173. end;
  12174. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12175. S_BL:
  12176. if not IsMOVZXAcceptable then
  12177. begin
  12178. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12179. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12180. begin
  12181. DebugMsg(SPeepholeOptimization + 'var9',p);
  12182. taicpu(p).opcode := A_AND;
  12183. taicpu(p).changeopsize(S_L);
  12184. taicpu(p).loadConst(0,$ff);
  12185. Result := True;
  12186. end
  12187. else if GetNextInstruction(p, hp1) and
  12188. (tai(hp1).typ = ait_instruction) and
  12189. (taicpu(hp1).opcode = A_AND) and
  12190. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12191. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12192. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12193. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12194. begin
  12195. DebugMsg(SPeepholeOptimization + 'var10',p);
  12196. taicpu(p).opcode := A_MOV;
  12197. taicpu(p).changeopsize(S_L);
  12198. { do not use R_SUBWHOLE
  12199. as movl %rdx,%eax
  12200. is invalid in assembler PM }
  12201. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12202. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12203. Result := True;
  12204. end;
  12205. end;
  12206. {$endif i8086}
  12207. S_WL:
  12208. if not IsMOVZXAcceptable then
  12209. begin
  12210. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12211. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12212. begin
  12213. DebugMsg(SPeepholeOptimization + 'var11',p);
  12214. taicpu(p).opcode := A_AND;
  12215. taicpu(p).changeopsize(S_L);
  12216. taicpu(p).loadConst(0,$ffff);
  12217. Result := True;
  12218. end
  12219. else if GetNextInstruction(p, hp1) and
  12220. (tai(hp1).typ = ait_instruction) and
  12221. (taicpu(hp1).opcode = A_AND) and
  12222. (taicpu(hp1).oper[0]^.typ = top_const) and
  12223. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12224. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12225. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12226. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12227. begin
  12228. DebugMsg(SPeepholeOptimization + 'var12',p);
  12229. taicpu(p).opcode := A_MOV;
  12230. taicpu(p).changeopsize(S_L);
  12231. { do not use R_SUBWHOLE
  12232. as movl %rdx,%eax
  12233. is invalid in assembler PM }
  12234. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12235. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12236. Result := True;
  12237. end;
  12238. end;
  12239. else
  12240. InternalError(2017050705);
  12241. end;
  12242. end
  12243. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12244. begin
  12245. if GetNextInstruction(p, hp1) and
  12246. (tai(hp1).typ = ait_instruction) and
  12247. (taicpu(hp1).opcode = A_AND) and
  12248. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12249. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12250. begin
  12251. //taicpu(p).opcode := A_MOV;
  12252. case taicpu(p).opsize Of
  12253. S_BL:
  12254. begin
  12255. DebugMsg(SPeepholeOptimization + 'var13',p);
  12256. taicpu(hp1).changeopsize(S_L);
  12257. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12258. end;
  12259. S_WL:
  12260. begin
  12261. DebugMsg(SPeepholeOptimization + 'var14',p);
  12262. taicpu(hp1).changeopsize(S_L);
  12263. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12264. end;
  12265. S_BW:
  12266. begin
  12267. DebugMsg(SPeepholeOptimization + 'var15',p);
  12268. taicpu(hp1).changeopsize(S_W);
  12269. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12270. end;
  12271. else
  12272. Internalerror(2017050704)
  12273. end;
  12274. Result := True;
  12275. end;
  12276. end;
  12277. end;
  12278. end;
  12279. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12280. var
  12281. hp1, hp2 : tai;
  12282. MaskLength : Cardinal;
  12283. MaskedBits : TCgInt;
  12284. ActiveReg : TRegister;
  12285. begin
  12286. Result:=false;
  12287. { There are no optimisations for reference targets }
  12288. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12289. Exit;
  12290. while GetNextInstruction(p, hp1) and
  12291. (hp1.typ = ait_instruction) do
  12292. begin
  12293. if (taicpu(p).oper[0]^.typ = top_const) then
  12294. begin
  12295. case taicpu(hp1).opcode of
  12296. A_AND:
  12297. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12298. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12299. { the second register must contain the first one, so compare their subreg types }
  12300. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12301. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12302. { change
  12303. and const1, reg
  12304. and const2, reg
  12305. to
  12306. and (const1 and const2), reg
  12307. }
  12308. begin
  12309. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12310. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12311. RemoveCurrentP(p, hp1);
  12312. Result:=true;
  12313. exit;
  12314. end;
  12315. A_CMP:
  12316. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12317. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12318. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12319. { Just check that the condition on the next instruction is compatible }
  12320. GetNextInstruction(hp1, hp2) and
  12321. (hp2.typ = ait_instruction) and
  12322. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12323. then
  12324. { change
  12325. and 2^n, reg
  12326. cmp 2^n, reg
  12327. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12328. to
  12329. and 2^n, reg
  12330. test reg, reg
  12331. j(~c) / set(~c) / cmov(~c)
  12332. }
  12333. begin
  12334. { Keep TEST instruction in, rather than remove it, because
  12335. it may trigger other optimisations such as MovAndTest2Test }
  12336. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12337. taicpu(hp1).opcode := A_TEST;
  12338. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12339. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12340. Result := True;
  12341. Exit;
  12342. end
  12343. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  12344. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12345. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  12346. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  12347. { change
  12348. and $ff/$ff/$ffff, reg
  12349. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  12350. dealloc reg
  12351. to
  12352. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  12353. }
  12354. begin
  12355. TransferUsedRegs(TmpUsedRegs);
  12356. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12357. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  12358. begin
  12359. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  12360. case taicpu(p).oper[0]^.val of
  12361. $ff:
  12362. begin
  12363. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  12364. taicpu(hp1).opsize:=S_B;
  12365. end;
  12366. $ffff:
  12367. begin
  12368. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  12369. taicpu(hp1).opsize:=S_W;
  12370. end;
  12371. $ffffffff:
  12372. begin
  12373. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12374. taicpu(hp1).opsize:=S_L;
  12375. end;
  12376. else
  12377. Internalerror(2023030401);
  12378. end;
  12379. RemoveCurrentP(p);
  12380. Result := True;
  12381. Exit;
  12382. end;
  12383. end;
  12384. A_MOVZX:
  12385. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12386. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12387. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12388. (
  12389. (
  12390. (taicpu(p).opsize=S_W) and
  12391. (taicpu(hp1).opsize=S_BW)
  12392. ) or
  12393. (
  12394. (taicpu(p).opsize=S_L) and
  12395. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12396. )
  12397. {$ifdef x86_64}
  12398. or
  12399. (
  12400. (taicpu(p).opsize=S_Q) and
  12401. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12402. )
  12403. {$endif x86_64}
  12404. ) then
  12405. begin
  12406. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12407. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12408. ) or
  12409. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12410. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12411. then
  12412. begin
  12413. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12414. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12415. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12416. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12417. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12418. }
  12419. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12420. RemoveInstruction(hp1);
  12421. { See if there are other optimisations possible }
  12422. Continue;
  12423. end;
  12424. end;
  12425. A_SHL:
  12426. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12427. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12428. begin
  12429. {$ifopt R+}
  12430. {$define RANGE_WAS_ON}
  12431. {$R-}
  12432. {$endif}
  12433. { get length of potential and mask }
  12434. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12435. { really a mask? }
  12436. {$ifdef RANGE_WAS_ON}
  12437. {$R+}
  12438. {$endif}
  12439. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12440. { unmasked part shifted out? }
  12441. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12442. begin
  12443. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12444. RemoveCurrentP(p, hp1);
  12445. Result:=true;
  12446. exit;
  12447. end;
  12448. end;
  12449. A_SHR:
  12450. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12451. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12452. (taicpu(hp1).oper[0]^.val <= 63) then
  12453. begin
  12454. { Does SHR combined with the AND cover all the bits?
  12455. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12456. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12457. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12458. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12459. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12460. begin
  12461. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12462. RemoveCurrentP(p, hp1);
  12463. Result := True;
  12464. Exit;
  12465. end;
  12466. end;
  12467. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12468. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12469. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12470. begin
  12471. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12472. (
  12473. (
  12474. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12475. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12476. ) or (
  12477. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12478. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12479. {$ifdef x86_64}
  12480. ) or (
  12481. (taicpu(hp1).opsize = S_LQ) and
  12482. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12483. {$endif x86_64}
  12484. )
  12485. ) then
  12486. begin
  12487. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12488. begin
  12489. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12490. RemoveInstruction(hp1);
  12491. { See if there are other optimisations possible }
  12492. Continue;
  12493. end;
  12494. { The super-registers are the same though.
  12495. Note that this change by itself doesn't improve
  12496. code speed, but it opens up other optimisations. }
  12497. {$ifdef x86_64}
  12498. { Convert 64-bit register to 32-bit }
  12499. case taicpu(hp1).opsize of
  12500. S_BQ:
  12501. begin
  12502. taicpu(hp1).opsize := S_BL;
  12503. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12504. end;
  12505. S_WQ:
  12506. begin
  12507. taicpu(hp1).opsize := S_WL;
  12508. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12509. end
  12510. else
  12511. ;
  12512. end;
  12513. {$endif x86_64}
  12514. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12515. taicpu(hp1).opcode := A_MOVZX;
  12516. { See if there are other optimisations possible }
  12517. Continue;
  12518. end;
  12519. end;
  12520. else
  12521. ;
  12522. end;
  12523. end
  12524. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12525. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12526. begin
  12527. {$ifdef x86_64}
  12528. if (taicpu(p).opsize = S_Q) then
  12529. begin
  12530. { Never necessary }
  12531. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12532. RemoveCurrentP(p, hp1);
  12533. Result := True;
  12534. Exit;
  12535. end;
  12536. {$endif x86_64}
  12537. { Forward check to determine necessity of and %reg,%reg }
  12538. TransferUsedRegs(TmpUsedRegs);
  12539. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12540. { Saves on a bunch of dereferences }
  12541. ActiveReg := taicpu(p).oper[1]^.reg;
  12542. case taicpu(hp1).opcode of
  12543. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12544. if (
  12545. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12546. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12547. ) and
  12548. (
  12549. (taicpu(hp1).opcode <> A_MOV) or
  12550. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12551. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12552. ) and
  12553. not (
  12554. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12555. (taicpu(hp1).opcode = A_MOV) and
  12556. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12557. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12558. ) and
  12559. (
  12560. (
  12561. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12562. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12563. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12564. ) or
  12565. (
  12566. {$ifdef x86_64}
  12567. (
  12568. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12569. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12570. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12571. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12572. ) and
  12573. {$endif x86_64}
  12574. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12575. )
  12576. ) then
  12577. begin
  12578. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12579. RemoveCurrentP(p, hp1);
  12580. Result := True;
  12581. Exit;
  12582. end;
  12583. A_ADD,
  12584. A_AND,
  12585. A_BSF,
  12586. A_BSR,
  12587. A_BTC,
  12588. A_BTR,
  12589. A_BTS,
  12590. A_OR,
  12591. A_SUB,
  12592. A_XOR:
  12593. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12594. if (
  12595. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12596. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12597. ) and
  12598. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12599. begin
  12600. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12601. RemoveCurrentP(p, hp1);
  12602. Result := True;
  12603. Exit;
  12604. end;
  12605. A_CMP,
  12606. A_TEST:
  12607. if (
  12608. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12609. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12610. ) and
  12611. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12612. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12613. begin
  12614. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12615. RemoveCurrentP(p, hp1);
  12616. Result := True;
  12617. Exit;
  12618. end;
  12619. A_BSWAP,
  12620. A_NEG,
  12621. A_NOT:
  12622. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12623. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12624. begin
  12625. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12626. RemoveCurrentP(p, hp1);
  12627. Result := True;
  12628. Exit;
  12629. end;
  12630. else
  12631. ;
  12632. end;
  12633. end;
  12634. if (taicpu(hp1).is_jmp) and
  12635. (taicpu(hp1).opcode<>A_JMP) and
  12636. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12637. begin
  12638. { change
  12639. and x, reg
  12640. jxx
  12641. to
  12642. test x, reg
  12643. jxx
  12644. if reg is deallocated before the
  12645. jump, but only if it's a conditional jump (PFV)
  12646. }
  12647. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12648. taicpu(p).opcode := A_TEST;
  12649. Exit;
  12650. end;
  12651. Break;
  12652. end;
  12653. { Lone AND tests }
  12654. if (taicpu(p).oper[0]^.typ = top_const) then
  12655. begin
  12656. {
  12657. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12658. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12659. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12660. }
  12661. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12662. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12663. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12664. begin
  12665. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12666. if taicpu(p).opsize = S_L then
  12667. begin
  12668. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12669. Result := True;
  12670. end;
  12671. end;
  12672. end;
  12673. { Backward check to determine necessity of and %reg,%reg }
  12674. if (taicpu(p).oper[0]^.typ = top_reg) and
  12675. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12676. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12677. GetLastInstruction(p, hp2) and
  12678. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12679. { Check size of adjacent instruction to determine if the AND is
  12680. effectively a null operation }
  12681. (
  12682. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12683. { Note: Don't include S_Q }
  12684. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12685. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12686. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  12687. ) then
  12688. begin
  12689. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  12690. { If GetNextInstruction returned False, hp1 will be nil }
  12691. RemoveCurrentP(p, hp1);
  12692. Result := True;
  12693. Exit;
  12694. end;
  12695. end;
  12696. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  12697. var
  12698. hp1, hp2: tai;
  12699. NewRef: TReference;
  12700. Distance: Cardinal;
  12701. TempTracking: TAllUsedRegs;
  12702. { This entire nested function is used in an if-statement below, but we
  12703. want to avoid all the used reg transfers and GetNextInstruction calls
  12704. until we really have to check }
  12705. function MemRegisterNotUsedLater: Boolean; inline;
  12706. var
  12707. hp2: tai;
  12708. begin
  12709. TransferUsedRegs(TmpUsedRegs);
  12710. hp2 := p;
  12711. repeat
  12712. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12713. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12714. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  12715. end;
  12716. begin
  12717. Result := False;
  12718. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12719. (taicpu(p).oper[1]^.typ = top_reg) then
  12720. begin
  12721. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12722. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12723. (hp1.typ <> ait_instruction) or
  12724. not
  12725. (
  12726. (cs_opt_level3 in current_settings.optimizerswitches) or
  12727. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12728. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12729. ) then
  12730. Exit;
  12731. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12732. addq $x, %rax
  12733. movq %rax, %rdx
  12734. sarq $63, %rdx
  12735. (%rax still in use)
  12736. ...letting OptPass2ADD run its course (and without -Os) will produce:
  12737. leaq $x(%rax),%rdx
  12738. addq $x, %rax
  12739. sarq $63, %rdx
  12740. ...which is okay since it breaks the dependency chain between
  12741. addq and movq, but if OptPass2MOV is called first:
  12742. addq $x, %rax
  12743. cqto
  12744. ...which is better in all ways, taking only 2 cycles to execute
  12745. and much smaller in code size.
  12746. }
  12747. { The extra register tracking is quite strenuous }
  12748. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12749. MatchInstruction(hp1, A_MOV, []) then
  12750. begin
  12751. { Update the register tracking to the MOV instruction }
  12752. CopyUsedRegs(TempTracking);
  12753. hp2 := p;
  12754. repeat
  12755. UpdateUsedRegs(tai(hp2.Next));
  12756. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12757. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12758. OptPass2ADD get called again }
  12759. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12760. begin
  12761. { Reset the tracking to the current instruction }
  12762. RestoreUsedRegs(TempTracking);
  12763. ReleaseUsedRegs(TempTracking);
  12764. Result := True;
  12765. Exit;
  12766. end;
  12767. { Reset the tracking to the current instruction }
  12768. RestoreUsedRegs(TempTracking);
  12769. ReleaseUsedRegs(TempTracking);
  12770. { If OptPass2MOV returned True, we don't need to set Result to
  12771. True if hp1 didn't change because the ADD instruction didn't
  12772. get modified and we'll be evaluating hp1 again when the
  12773. peephole optimizer reaches it }
  12774. end;
  12775. { Change:
  12776. add %reg2,%reg1
  12777. (%reg2 not modified in between)
  12778. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  12779. To:
  12780. mov/s/z #(%reg1,%reg2),%reg1
  12781. }
  12782. if (taicpu(p).oper[0]^.typ = top_reg) and
  12783. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  12784. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  12785. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  12786. (
  12787. (
  12788. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  12789. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  12790. { r/esp cannot be an index }
  12791. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  12792. ) or (
  12793. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  12794. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  12795. )
  12796. ) and (
  12797. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  12798. (
  12799. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  12800. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12801. MemRegisterNotUsedLater
  12802. )
  12803. ) then
  12804. begin
  12805. if (
  12806. { Instructions are guaranteed to be adjacent on -O2 and under }
  12807. (cs_opt_level3 in current_settings.optimizerswitches) and
  12808. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  12809. ) then
  12810. begin
  12811. { If the other register is used in between, move the MOV
  12812. instruction to right after the ADD instruction so a
  12813. saving can still be made }
  12814. Asml.Remove(hp1);
  12815. Asml.InsertAfter(hp1, p);
  12816. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12817. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12818. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  12819. RemoveCurrentp(p, hp1);
  12820. end
  12821. else
  12822. begin
  12823. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  12824. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12825. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12826. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  12827. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12828. { hp1 may not be the immediate next instruction under -O3 }
  12829. RemoveCurrentp(p)
  12830. else
  12831. RemoveCurrentp(p, hp1);
  12832. end;
  12833. Result := True;
  12834. Exit;
  12835. end;
  12836. { Change:
  12837. addl/q $x,%reg1
  12838. movl/q %reg1,%reg2
  12839. To:
  12840. leal/q $x(%reg1),%reg2
  12841. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12842. Breaks the dependency chain.
  12843. }
  12844. if (taicpu(p).oper[0]^.typ = top_const) and
  12845. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12846. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12847. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12848. (
  12849. { Instructions are guaranteed to be adjacent on -O2 and under }
  12850. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12851. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12852. ) then
  12853. begin
  12854. TransferUsedRegs(TmpUsedRegs);
  12855. hp2 := p;
  12856. repeat
  12857. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12858. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12859. if (
  12860. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  12861. not (cs_opt_size in current_settings.optimizerswitches) or
  12862. (
  12863. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12864. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12865. )
  12866. ) then
  12867. begin
  12868. { Change the MOV instruction to a LEA instruction, and update the
  12869. first operand }
  12870. reference_reset(NewRef, 1, []);
  12871. NewRef.base := taicpu(p).oper[1]^.reg;
  12872. NewRef.scalefactor := 1;
  12873. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  12874. taicpu(hp1).opcode := A_LEA;
  12875. taicpu(hp1).loadref(0, NewRef);
  12876. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12877. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12878. begin
  12879. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12880. { Move what is now the LEA instruction to before the ADD instruction }
  12881. Asml.Remove(hp1);
  12882. Asml.InsertBefore(hp1, p);
  12883. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12884. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  12885. p := hp1;
  12886. end
  12887. else
  12888. begin
  12889. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12890. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  12891. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12892. { hp1 may not be the immediate next instruction under -O3 }
  12893. RemoveCurrentp(p)
  12894. else
  12895. RemoveCurrentp(p, hp1);
  12896. end;
  12897. Result := True;
  12898. end;
  12899. end;
  12900. end;
  12901. end;
  12902. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  12903. var
  12904. SubReg: TSubRegister;
  12905. begin
  12906. Result:=false;
  12907. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  12908. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12909. with taicpu(p).oper[0]^.ref^ do
  12910. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  12911. begin
  12912. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  12913. begin
  12914. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  12915. taicpu(p).opcode := A_ADD;
  12916. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  12917. Result := True;
  12918. end
  12919. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  12920. begin
  12921. if (base <> NR_NO) then
  12922. begin
  12923. if (scalefactor <= 1) then
  12924. begin
  12925. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  12926. taicpu(p).opcode := A_ADD;
  12927. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  12928. Result := True;
  12929. end;
  12930. end
  12931. else
  12932. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  12933. if (scalefactor in [2, 4, 8]) then
  12934. begin
  12935. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  12936. taicpu(p).loadconst(0, BsrByte(scalefactor));
  12937. taicpu(p).opcode := A_SHL;
  12938. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  12939. Result := True;
  12940. end;
  12941. end;
  12942. end;
  12943. end;
  12944. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  12945. var
  12946. hp1, hp2: tai;
  12947. NewRef: TReference;
  12948. Distance: Cardinal;
  12949. TempTracking: TAllUsedRegs;
  12950. begin
  12951. Result := False;
  12952. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12953. MatchOpType(taicpu(p),top_const,top_reg) then
  12954. begin
  12955. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12956. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12957. (hp1.typ <> ait_instruction) or
  12958. not
  12959. (
  12960. (cs_opt_level3 in current_settings.optimizerswitches) or
  12961. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12962. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12963. ) then
  12964. Exit;
  12965. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12966. subq $x, %rax
  12967. movq %rax, %rdx
  12968. sarq $63, %rdx
  12969. (%rax still in use)
  12970. ...letting OptPass2SUB run its course (and without -Os) will produce:
  12971. leaq $-x(%rax),%rdx
  12972. movq $x, %rax
  12973. sarq $63, %rdx
  12974. ...which is okay since it breaks the dependency chain between
  12975. subq and movq, but if OptPass2MOV is called first:
  12976. subq $x, %rax
  12977. cqto
  12978. ...which is better in all ways, taking only 2 cycles to execute
  12979. and much smaller in code size.
  12980. }
  12981. { The extra register tracking is quite strenuous }
  12982. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12983. MatchInstruction(hp1, A_MOV, []) then
  12984. begin
  12985. { Update the register tracking to the MOV instruction }
  12986. CopyUsedRegs(TempTracking);
  12987. hp2 := p;
  12988. repeat
  12989. UpdateUsedRegs(tai(hp2.Next));
  12990. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12991. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12992. OptPass2SUB get called again }
  12993. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12994. begin
  12995. { Reset the tracking to the current instruction }
  12996. RestoreUsedRegs(TempTracking);
  12997. ReleaseUsedRegs(TempTracking);
  12998. Result := True;
  12999. Exit;
  13000. end;
  13001. { Reset the tracking to the current instruction }
  13002. RestoreUsedRegs(TempTracking);
  13003. ReleaseUsedRegs(TempTracking);
  13004. { If OptPass2MOV returned True, we don't need to set Result to
  13005. True if hp1 didn't change because the SUB instruction didn't
  13006. get modified and we'll be evaluating hp1 again when the
  13007. peephole optimizer reaches it }
  13008. end;
  13009. { Change:
  13010. subl/q $x,%reg1
  13011. movl/q %reg1,%reg2
  13012. To:
  13013. leal/q $-x(%reg1),%reg2
  13014. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13015. Breaks the dependency chain and potentially permits the removal of
  13016. a CMP instruction if one follows.
  13017. }
  13018. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13019. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13020. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13021. (
  13022. { Instructions are guaranteed to be adjacent on -O2 and under }
  13023. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13024. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13025. ) then
  13026. begin
  13027. TransferUsedRegs(TmpUsedRegs);
  13028. hp2 := p;
  13029. repeat
  13030. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13031. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13032. if (
  13033. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13034. not (cs_opt_size in current_settings.optimizerswitches) or
  13035. (
  13036. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13037. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13038. )
  13039. ) then
  13040. begin
  13041. { Change the MOV instruction to a LEA instruction, and update the
  13042. first operand }
  13043. reference_reset(NewRef, 1, []);
  13044. NewRef.base := taicpu(p).oper[1]^.reg;
  13045. NewRef.scalefactor := 1;
  13046. NewRef.offset := -taicpu(p).oper[0]^.val;
  13047. taicpu(hp1).opcode := A_LEA;
  13048. taicpu(hp1).loadref(0, NewRef);
  13049. TransferUsedRegs(TmpUsedRegs);
  13050. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13051. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13052. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13053. begin
  13054. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13055. { Move what is now the LEA instruction to before the SUB instruction }
  13056. Asml.Remove(hp1);
  13057. Asml.InsertBefore(hp1, p);
  13058. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13059. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13060. p := hp1;
  13061. end
  13062. else
  13063. begin
  13064. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13065. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13066. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13067. { hp1 may not be the immediate next instruction under -O3 }
  13068. RemoveCurrentp(p)
  13069. else
  13070. RemoveCurrentp(p, hp1);
  13071. end;
  13072. Result := True;
  13073. end;
  13074. end;
  13075. end;
  13076. end;
  13077. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13078. begin
  13079. { we can skip all instructions not messing with the stack pointer }
  13080. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13081. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13082. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13083. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13084. ({(taicpu(hp1).ops=0) or }
  13085. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13086. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13087. ) and }
  13088. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13089. )
  13090. ) do
  13091. GetNextInstruction(hp1,hp1);
  13092. Result:=assigned(hp1);
  13093. end;
  13094. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13095. var
  13096. hp1, hp2, hp3, hp4, hp5: tai;
  13097. begin
  13098. Result:=false;
  13099. hp5:=nil;
  13100. { replace
  13101. leal(q) x(<stackpointer>),<stackpointer>
  13102. call procname
  13103. leal(q) -x(<stackpointer>),<stackpointer>
  13104. ret
  13105. by
  13106. jmp procname
  13107. but do it only on level 4 because it destroys stack back traces
  13108. }
  13109. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13110. MatchOpType(taicpu(p),top_ref,top_reg) and
  13111. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13112. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13113. { the -8 or -24 are not required, but bail out early if possible,
  13114. higher values are unlikely }
  13115. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13116. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13117. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13118. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13119. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13120. GetNextInstruction(p, hp1) and
  13121. { Take a copy of hp1 }
  13122. SetAndTest(hp1, hp4) and
  13123. { trick to skip label }
  13124. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13125. SkipSimpleInstructions(hp1) and
  13126. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13127. GetNextInstruction(hp1, hp2) and
  13128. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13129. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13130. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13131. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13132. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13133. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13134. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13135. { Segment register will be NR_NO }
  13136. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13137. GetNextInstruction(hp2, hp3) and
  13138. { trick to skip label }
  13139. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13140. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13141. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13142. SetAndTest(hp3,hp5) and
  13143. GetNextInstruction(hp3,hp3) and
  13144. MatchInstruction(hp3,A_RET,[S_NO])
  13145. )
  13146. ) and
  13147. (taicpu(hp3).ops=0) then
  13148. begin
  13149. taicpu(hp1).opcode := A_JMP;
  13150. taicpu(hp1).is_jmp := true;
  13151. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13152. RemoveCurrentP(p, hp4);
  13153. RemoveInstruction(hp2);
  13154. RemoveInstruction(hp3);
  13155. if Assigned(hp5) then
  13156. begin
  13157. AsmL.Remove(hp5);
  13158. ASmL.InsertBefore(hp5,hp1)
  13159. end;
  13160. Result:=true;
  13161. end;
  13162. end;
  13163. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13164. {$ifdef x86_64}
  13165. var
  13166. hp1, hp2, hp3, hp4, hp5: tai;
  13167. {$endif x86_64}
  13168. begin
  13169. Result:=false;
  13170. {$ifdef x86_64}
  13171. hp5:=nil;
  13172. { replace
  13173. push %rax
  13174. call procname
  13175. pop %rcx
  13176. ret
  13177. by
  13178. jmp procname
  13179. but do it only on level 4 because it destroys stack back traces
  13180. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13181. for all supported calling conventions
  13182. }
  13183. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13184. MatchOpType(taicpu(p),top_reg) and
  13185. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13186. GetNextInstruction(p, hp1) and
  13187. { Take a copy of hp1 }
  13188. SetAndTest(hp1, hp4) and
  13189. { trick to skip label }
  13190. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13191. SkipSimpleInstructions(hp1) and
  13192. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13193. GetNextInstruction(hp1, hp2) and
  13194. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13195. MatchOpType(taicpu(hp2),top_reg) and
  13196. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13197. GetNextInstruction(hp2, hp3) and
  13198. { trick to skip label }
  13199. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13200. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13201. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13202. SetAndTest(hp3,hp5) and
  13203. GetNextInstruction(hp3,hp3) and
  13204. MatchInstruction(hp3,A_RET,[S_NO])
  13205. )
  13206. ) and
  13207. (taicpu(hp3).ops=0) then
  13208. begin
  13209. taicpu(hp1).opcode := A_JMP;
  13210. taicpu(hp1).is_jmp := true;
  13211. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13212. RemoveCurrentP(p, hp4);
  13213. RemoveInstruction(hp2);
  13214. RemoveInstruction(hp3);
  13215. if Assigned(hp5) then
  13216. begin
  13217. AsmL.Remove(hp5);
  13218. ASmL.InsertBefore(hp5,hp1)
  13219. end;
  13220. Result:=true;
  13221. end;
  13222. {$endif x86_64}
  13223. end;
  13224. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13225. var
  13226. Value, RegName: string;
  13227. begin
  13228. Result:=false;
  13229. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13230. begin
  13231. case taicpu(p).oper[0]^.val of
  13232. 0:
  13233. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13234. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13235. begin
  13236. { change "mov $0,%reg" into "xor %reg,%reg" }
  13237. taicpu(p).opcode := A_XOR;
  13238. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13239. Result := True;
  13240. {$ifdef x86_64}
  13241. end
  13242. else if (taicpu(p).opsize = S_Q) then
  13243. begin
  13244. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13245. { The actual optimization }
  13246. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13247. taicpu(p).changeopsize(S_L);
  13248. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13249. Result := True;
  13250. end;
  13251. $1..$FFFFFFFF:
  13252. begin
  13253. { Code size reduction by J. Gareth "Kit" Moreton }
  13254. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13255. case taicpu(p).opsize of
  13256. S_Q:
  13257. begin
  13258. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13259. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13260. { The actual optimization }
  13261. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13262. taicpu(p).changeopsize(S_L);
  13263. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13264. Result := True;
  13265. end;
  13266. else
  13267. { Do nothing };
  13268. end;
  13269. {$endif x86_64}
  13270. end;
  13271. -1:
  13272. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13273. if (cs_opt_size in current_settings.optimizerswitches) and
  13274. (taicpu(p).opsize <> S_B) and
  13275. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13276. begin
  13277. { change "mov $-1,%reg" into "or $-1,%reg" }
  13278. { NOTES:
  13279. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13280. - This operation creates a false dependency on the register, so only do it when optimising for size
  13281. - It is possible to set memory operands using this method, but this creates an even greater false dependency, so don't do this at all
  13282. }
  13283. taicpu(p).opcode := A_OR;
  13284. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13285. Result := True;
  13286. end;
  13287. else
  13288. { Do nothing };
  13289. end;
  13290. end;
  13291. end;
  13292. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13293. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13294. begin
  13295. Result := False;
  13296. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13297. Exit;
  13298. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13299. so don't bother optimising }
  13300. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13301. Exit;
  13302. if (taicpu(p).oper[0]^.typ <> top_const) or
  13303. { If the value can fit into an 8-bit signed integer, a smaller
  13304. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13305. falls within this range }
  13306. (
  13307. (taicpu(p).oper[0]^.val > -128) and
  13308. (taicpu(p).oper[0]^.val <= 127)
  13309. ) then
  13310. Exit;
  13311. { If we're optimising for size, this is acceptable }
  13312. if (cs_opt_size in current_settings.optimizerswitches) then
  13313. Exit(True);
  13314. if (taicpu(p).oper[1]^.typ = top_reg) and
  13315. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13316. Exit(True);
  13317. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13318. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13319. Exit(True);
  13320. end;
  13321. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13322. var
  13323. hp1: tai;
  13324. Value: TCGInt;
  13325. begin
  13326. Result := False;
  13327. if MatchOpType(taicpu(p), top_const, top_reg) then
  13328. begin
  13329. { Detect:
  13330. andw x, %ax (0 <= x < $8000)
  13331. ...
  13332. movzwl %ax,%eax
  13333. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13334. }
  13335. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13336. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13337. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13338. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13339. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13340. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13341. begin
  13342. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13343. taicpu(hp1).opcode := A_CWDE;
  13344. taicpu(hp1).clearop(0);
  13345. taicpu(hp1).clearop(1);
  13346. taicpu(hp1).ops := 0;
  13347. { A change was made, but not with p, so don't set Result, but
  13348. notify the compiler that a change was made }
  13349. Include(OptsToCheck, aoc_ForceNewIteration);
  13350. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13351. end;
  13352. end;
  13353. { If "not x" is a power of 2 (popcnt = 1), change:
  13354. and $x, %reg/ref
  13355. To:
  13356. btr lb(x), %reg/ref
  13357. }
  13358. if IsBTXAcceptable(p) and
  13359. (
  13360. { Make sure a TEST doesn't follow that plays with the register }
  13361. not GetNextInstruction(p, hp1) or
  13362. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13363. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13364. ) then
  13365. begin
  13366. {$push}{$R-}{$Q-}
  13367. { Value is a sign-extended 32-bit integer - just correct it
  13368. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13369. checks to see if this operand is an immediate. }
  13370. Value := not taicpu(p).oper[0]^.val;
  13371. {$pop}
  13372. {$ifdef x86_64}
  13373. if taicpu(p).opsize = S_L then
  13374. {$endif x86_64}
  13375. Value := Value and $FFFFFFFF;
  13376. if (PopCnt(QWord(Value)) = 1) then
  13377. begin
  13378. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13379. taicpu(p).opcode := A_BTR;
  13380. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13381. Result := True;
  13382. Exit;
  13383. end;
  13384. end;
  13385. end;
  13386. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13387. begin
  13388. Result := False;
  13389. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13390. Exit;
  13391. { Convert:
  13392. movswl %ax,%eax -> cwtl
  13393. movslq %eax,%rax -> cdqe
  13394. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13395. refer to the same opcode and depends only on the assembler's
  13396. current operand-size attribute. [Kit]
  13397. }
  13398. with taicpu(p) do
  13399. case opsize of
  13400. S_WL:
  13401. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13402. begin
  13403. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13404. opcode := A_CWDE;
  13405. clearop(0);
  13406. clearop(1);
  13407. ops := 0;
  13408. Result := True;
  13409. end;
  13410. {$ifdef x86_64}
  13411. S_LQ:
  13412. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13413. begin
  13414. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13415. opcode := A_CDQE;
  13416. clearop(0);
  13417. clearop(1);
  13418. ops := 0;
  13419. Result := True;
  13420. end;
  13421. {$endif x86_64}
  13422. else
  13423. ;
  13424. end;
  13425. end;
  13426. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13427. var
  13428. hp1, hp2: tai;
  13429. IdentityMask, Shift: TCGInt;
  13430. LimitSize: Topsize;
  13431. DoNotMerge: Boolean;
  13432. begin
  13433. Result := False;
  13434. { All these optimisations work on "shr const,%reg" }
  13435. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13436. Exit;
  13437. DoNotMerge := False;
  13438. Shift := taicpu(p).oper[0]^.val;
  13439. LimitSize := taicpu(p).opsize;
  13440. hp1 := p;
  13441. repeat
  13442. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13443. Break;
  13444. { Detect:
  13445. shr x, %reg
  13446. and y, %reg
  13447. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13448. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13449. }
  13450. case taicpu(hp1).opcode of
  13451. A_AND:
  13452. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13453. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13454. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13455. begin
  13456. { Make sure the FLAGS register isn't in use }
  13457. TransferUsedRegs(TmpUsedRegs);
  13458. hp2 := p;
  13459. repeat
  13460. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13461. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13462. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13463. begin
  13464. { Generate the identity mask }
  13465. case taicpu(p).opsize of
  13466. S_B:
  13467. IdentityMask := $FF shr Shift;
  13468. S_W:
  13469. IdentityMask := $FFFF shr Shift;
  13470. S_L:
  13471. IdentityMask := $FFFFFFFF shr Shift;
  13472. {$ifdef x86_64}
  13473. S_Q:
  13474. { We need to force the operands to be unsigned 64-bit
  13475. integers otherwise the wrong value is generated }
  13476. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13477. {$endif x86_64}
  13478. else
  13479. InternalError(2022081501);
  13480. end;
  13481. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13482. begin
  13483. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13484. { All the possible 1 bits are covered, so we can remove the AND }
  13485. hp2 := tai(hp1.Previous);
  13486. RemoveInstruction(hp1);
  13487. { p wasn't actually changed, so don't set Result to True,
  13488. but a change was nonetheless made elsewhere }
  13489. Include(OptsToCheck, aoc_ForceNewIteration);
  13490. { Do another pass in case other AND or MOVZX instructions
  13491. follow }
  13492. hp1 := hp2;
  13493. Continue;
  13494. end;
  13495. end;
  13496. end;
  13497. A_TEST, A_CMP, A_Jcc:
  13498. { Skip over conditional jumps and relevant comparisons }
  13499. Continue;
  13500. A_MOVZX:
  13501. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13502. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13503. begin
  13504. { Since the original register is being read as is, subsequent
  13505. SHRs must not be merged at this point }
  13506. DoNotMerge := True;
  13507. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13508. begin
  13509. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13510. begin
  13511. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13512. { All the possible 1 bits are covered, so we can remove the AND }
  13513. hp2 := tai(hp1.Previous);
  13514. RemoveInstruction(hp1);
  13515. hp1 := hp2;
  13516. end
  13517. else { Different register target }
  13518. begin
  13519. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13520. taicpu(hp1).opcode := A_MOV;
  13521. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13522. case taicpu(hp1).opsize of
  13523. S_BW:
  13524. taicpu(hp1).opsize := S_W;
  13525. S_BL, S_WL:
  13526. taicpu(hp1).opsize := S_L;
  13527. else
  13528. InternalError(2022081503);
  13529. end;
  13530. end;
  13531. end
  13532. else if (Shift > 0) and
  13533. (taicpu(p).opsize = S_W) and
  13534. (taicpu(hp1).opsize = S_WL) and
  13535. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13536. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13537. begin
  13538. { Detect:
  13539. shr x, %ax (x > 0)
  13540. ...
  13541. movzwl %ax,%eax
  13542. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13543. }
  13544. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13545. taicpu(hp1).opcode := A_CWDE;
  13546. taicpu(hp1).clearop(0);
  13547. taicpu(hp1).clearop(1);
  13548. taicpu(hp1).ops := 0;
  13549. end;
  13550. { Move onto the next instruction }
  13551. Continue;
  13552. end;
  13553. A_SHL, A_SAL, A_SHR:
  13554. if (taicpu(hp1).opsize <= LimitSize) and
  13555. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13556. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13557. begin
  13558. { Make sure the sizes don't exceed the register size limit
  13559. (measured by the shift value falling below the limit) }
  13560. if taicpu(hp1).opsize < LimitSize then
  13561. LimitSize := taicpu(hp1).opsize;
  13562. if taicpu(hp1).opcode = A_SHR then
  13563. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13564. else
  13565. begin
  13566. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13567. DoNotMerge := True;
  13568. end;
  13569. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13570. Break;
  13571. { Since we've established that the combined shift is within
  13572. limits, we can actually combine the adjacent SHR
  13573. instructions even if they're different sizes }
  13574. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13575. begin
  13576. hp2 := tai(hp1.Previous);
  13577. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13578. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13579. RemoveInstruction(hp1);
  13580. hp1 := hp2;
  13581. end;
  13582. { Move onto the next instruction }
  13583. Continue;
  13584. end;
  13585. else
  13586. ;
  13587. end;
  13588. Break;
  13589. until False;
  13590. { Detect the following (looking backwards):
  13591. shr %cl,%reg
  13592. shr x, %reg
  13593. Swap the two SHR instructions to minimise a pipeline stall.
  13594. }
  13595. if GetLastInstruction(p, hp1) and
  13596. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13597. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13598. { First operand will be %cl }
  13599. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13600. { Just to be sure }
  13601. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13602. begin
  13603. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13604. { Moving the entries this way ensures the register tracking remains correct }
  13605. Asml.Remove(p);
  13606. Asml.InsertBefore(p, hp1);
  13607. p := hp1;
  13608. { Don't set Result to True because the current instruction is now
  13609. "shr %cl,%reg" and there's nothing more we can do with it }
  13610. end;
  13611. end;
  13612. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13613. var
  13614. hp1, hp2: tai;
  13615. Opposite, SecondOpposite: TAsmOp;
  13616. NewCond: TAsmCond;
  13617. begin
  13618. Result := False;
  13619. { Change:
  13620. add/sub 128,(dest)
  13621. To:
  13622. sub/add -128,(dest)
  13623. This generaally takes fewer bytes to encode because -128 can be stored
  13624. in a signed byte, whereas +128 cannot.
  13625. }
  13626. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13627. begin
  13628. if taicpu(p).opcode = A_ADD then
  13629. Opposite := A_SUB
  13630. else
  13631. Opposite := A_ADD;
  13632. { Be careful if the flags are in use, because the CF flag inverts
  13633. when changing from ADD to SUB and vice versa }
  13634. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13635. GetNextInstruction(p, hp1) then
  13636. begin
  13637. TransferUsedRegs(TmpUsedRegs);
  13638. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13639. hp2 := hp1;
  13640. { Scan ahead to check if everything's safe }
  13641. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13642. begin
  13643. if (hp1.typ <> ait_instruction) then
  13644. { Probably unsafe since the flags are still in use }
  13645. Exit;
  13646. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13647. { Stop searching at an unconditional jump }
  13648. Break;
  13649. if not
  13650. (
  13651. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13652. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13653. ) and
  13654. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13655. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13656. Exit;
  13657. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13658. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13659. { Move to the next instruction }
  13660. GetNextInstruction(hp1, hp1);
  13661. end;
  13662. while Assigned(hp2) and (hp2 <> hp1) do
  13663. begin
  13664. NewCond := C_None;
  13665. case taicpu(hp2).condition of
  13666. C_A, C_NBE:
  13667. NewCond := C_BE;
  13668. C_B, C_C, C_NAE:
  13669. NewCond := C_AE;
  13670. C_AE, C_NB, C_NC:
  13671. NewCond := C_B;
  13672. C_BE, C_NA:
  13673. NewCond := C_A;
  13674. else
  13675. { No change needed };
  13676. end;
  13677. if NewCond <> C_None then
  13678. begin
  13679. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13680. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13681. taicpu(hp2).condition := NewCond;
  13682. end
  13683. else
  13684. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13685. begin
  13686. { Because of the flipping of the carry bit, to ensure
  13687. the operation remains equivalent, ADC becomes SBB
  13688. and vice versa, and the constant is not-inverted.
  13689. If multiple ADCs or SBBs appear in a row, each one
  13690. changed causes the carry bit to invert, so they all
  13691. need to be flipped }
  13692. if taicpu(hp2).opcode = A_ADC then
  13693. SecondOpposite := A_SBB
  13694. else
  13695. SecondOpposite := A_ADC;
  13696. if taicpu(hp2).oper[0]^.typ <> top_const then
  13697. { Should have broken out of this optimisation already }
  13698. InternalError(2021112901);
  13699. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(hp2).opcode) + debug_opsize2str(taicpu(hp2).opsize) + ' $' + debug_tostr(taicpu(hp2).oper[0]^.val) + ',' + debug_operstr(taicpu(hp2).oper[1]^) + ' -> ' +
  13700. debug_op2str(SecondOpposite) + debug_opsize2str(taicpu(hp2).opsize) + ' $' + debug_tostr(not taicpu(hp2).oper[0]^.val) + ',' + debug_operstr(taicpu(hp2).oper[1]^) + ' to accommodate inverted carry bit', hp2);
  13701. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  13702. taicpu(hp2).opcode := SecondOpposite;
  13703. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  13704. end;
  13705. { Move to the next instruction }
  13706. GetNextInstruction(hp2, hp2);
  13707. end;
  13708. if (hp2 <> hp1) then
  13709. InternalError(2021111501);
  13710. end;
  13711. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  13712. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  13713. taicpu(p).opcode := Opposite;
  13714. taicpu(p).oper[0]^.val := -128;
  13715. { No further optimisations can be made on this instruction, so move
  13716. onto the next one to save time }
  13717. p := tai(p.Next);
  13718. UpdateUsedRegs(p);
  13719. Result := True;
  13720. Exit;
  13721. end;
  13722. { Detect:
  13723. add/sub %reg2,(dest)
  13724. add/sub x, (dest)
  13725. (dest can be a register or a reference)
  13726. Swap the instructions to minimise a pipeline stall. This reverses the
  13727. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  13728. optimisations could be made.
  13729. }
  13730. if (taicpu(p).oper[0]^.typ = top_reg) and
  13731. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  13732. (
  13733. (
  13734. (taicpu(p).oper[1]^.typ = top_reg) and
  13735. { We can try searching further ahead if we're writing to a register }
  13736. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  13737. ) or
  13738. (
  13739. (taicpu(p).oper[1]^.typ = top_ref) and
  13740. GetNextInstruction(p, hp1)
  13741. )
  13742. ) and
  13743. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  13744. (taicpu(hp1).oper[0]^.typ = top_const) and
  13745. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  13746. begin
  13747. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  13748. TransferUsedRegs(TmpUsedRegs);
  13749. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13750. hp2 := p;
  13751. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  13752. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  13753. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  13754. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13755. begin
  13756. asml.remove(hp1);
  13757. asml.InsertBefore(hp1, p);
  13758. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  13759. Result := True;
  13760. end;
  13761. end;
  13762. end;
  13763. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  13764. var
  13765. hp1: tai;
  13766. begin
  13767. Result:=false;
  13768. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  13769. while GetNextInstruction(p, hp1) and
  13770. TrySwapMovCmp(p, hp1) do
  13771. begin
  13772. if MatchInstruction(hp1, A_MOV, []) then
  13773. begin
  13774. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13775. begin
  13776. { A little hacky, but since CMP doesn't read the flags, only
  13777. modify them, it's safe if they get scrambled by MOV -> XOR }
  13778. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13779. Result := PostPeepholeOptMov(hp1);
  13780. {$ifdef x86_64}
  13781. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13782. { Used to shrink instruction size }
  13783. PostPeepholeOptXor(hp1);
  13784. {$endif x86_64}
  13785. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13786. end
  13787. else
  13788. begin
  13789. Result := PostPeepholeOptMov(hp1);
  13790. {$ifdef x86_64}
  13791. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13792. { Used to shrink instruction size }
  13793. PostPeepholeOptXor(hp1);
  13794. {$endif x86_64}
  13795. end;
  13796. end;
  13797. { Enabling this flag is actually a null operation, but it marks
  13798. the code as 'modified' during this pass }
  13799. Include(OptsToCheck, aoc_ForceNewIteration);
  13800. end;
  13801. { change "cmp $0, %reg" to "test %reg, %reg" }
  13802. if MatchOpType(taicpu(p),top_const,top_reg) and
  13803. (taicpu(p).oper[0]^.val = 0) then
  13804. begin
  13805. taicpu(p).opcode := A_TEST;
  13806. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  13807. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  13808. Result:=true;
  13809. end;
  13810. end;
  13811. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  13812. var
  13813. IsTestConstX, IsValid : Boolean;
  13814. hp1,hp2 : tai;
  13815. begin
  13816. Result:=false;
  13817. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  13818. if (taicpu(p).opcode = A_TEST) then
  13819. while GetNextInstruction(p, hp1) and
  13820. TrySwapMovCmp(p, hp1) do
  13821. begin
  13822. if MatchInstruction(hp1, A_MOV, []) then
  13823. begin
  13824. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13825. begin
  13826. { A little hacky, but since TEST doesn't read the flags, only
  13827. modify them, it's safe if they get scrambled by MOV -> XOR }
  13828. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13829. Result := PostPeepholeOptMov(hp1);
  13830. {$ifdef x86_64}
  13831. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13832. { Used to shrink instruction size }
  13833. PostPeepholeOptXor(hp1);
  13834. {$endif x86_64}
  13835. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13836. end
  13837. else
  13838. begin
  13839. Result := PostPeepholeOptMov(hp1);
  13840. {$ifdef x86_64}
  13841. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13842. { Used to shrink instruction size }
  13843. PostPeepholeOptXor(hp1);
  13844. {$endif x86_64}
  13845. end;
  13846. end;
  13847. { Enabling this flag is actually a null operation, but it marks
  13848. the code as 'modified' during this pass }
  13849. Include(OptsToCheck, aoc_ForceNewIteration);
  13850. end;
  13851. { If x is a power of 2 (popcnt = 1), change:
  13852. or $x, %reg/ref
  13853. To:
  13854. bts lb(x), %reg/ref
  13855. }
  13856. if (taicpu(p).opcode = A_OR) and
  13857. IsBTXAcceptable(p) and
  13858. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  13859. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13860. (
  13861. { Don't optimise if a test instruction follows }
  13862. not GetNextInstruction(p, hp1) or
  13863. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  13864. ) then
  13865. begin
  13866. DebugMsg(SPeepholeOptimization + 'Changed OR $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BTS $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Or2Bts)', p);
  13867. taicpu(p).opcode := A_BTS;
  13868. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13869. Result := True;
  13870. Exit;
  13871. end;
  13872. { If x is a power of 2 (popcnt = 1), change:
  13873. test $x, %reg/ref
  13874. je / sete / cmove (or jne / setne)
  13875. To:
  13876. bt lb(x), %reg/ref
  13877. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  13878. }
  13879. if (taicpu(p).opcode = A_TEST) and
  13880. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  13881. (taicpu(p).oper[0]^.typ = top_const) and
  13882. (
  13883. (cs_opt_size in current_settings.optimizerswitches) or
  13884. (
  13885. (taicpu(p).oper[1]^.typ = top_reg) and
  13886. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13887. ) or
  13888. (
  13889. (taicpu(p).oper[1]^.typ <> top_reg) and
  13890. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13891. )
  13892. ) and
  13893. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13894. { For sizes less than S_L, the byte size is equal or larger with BT,
  13895. so don't bother optimising }
  13896. (taicpu(p).opsize >= S_L) then
  13897. begin
  13898. IsValid := True;
  13899. { Check the next set of instructions, watching the FLAGS register
  13900. and the conditions used }
  13901. TransferUsedRegs(TmpUsedRegs);
  13902. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13903. hp1 := p;
  13904. hp2 := nil;
  13905. while GetNextInstruction(hp1, hp1) do
  13906. begin
  13907. if not Assigned(hp2) then
  13908. { The first instruction after TEST }
  13909. hp2 := hp1;
  13910. if (hp1.typ <> ait_instruction) then
  13911. begin
  13912. { If the flags are no longer in use, everything is fine }
  13913. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13914. IsValid := False;
  13915. Break;
  13916. end;
  13917. case taicpu(hp1).condition of
  13918. C_None:
  13919. begin
  13920. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13921. { Something is not quite normal, so play safe and don't change }
  13922. IsValid := False;
  13923. Break;
  13924. end;
  13925. C_E, C_Z, C_NE, C_NZ:
  13926. { This is fine };
  13927. else
  13928. begin
  13929. { Unsupported condition }
  13930. IsValid := False;
  13931. Break;
  13932. end;
  13933. end;
  13934. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13935. end;
  13936. if IsValid then
  13937. begin
  13938. while hp2 <> hp1 do
  13939. begin
  13940. case taicpu(hp2).condition of
  13941. C_Z, C_E:
  13942. taicpu(hp2).condition := C_NC;
  13943. C_NZ, C_NE:
  13944. taicpu(hp2).condition := C_C;
  13945. else
  13946. { Should not get this by this point }
  13947. InternalError(2022110701);
  13948. end;
  13949. GetNextInstruction(hp2, hp2);
  13950. end;
  13951. DebugMsg(SPeepholeOptimization + 'Changed TEST $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BT $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Test2Bt)', p);
  13952. taicpu(p).opcode := A_BT;
  13953. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13954. Result := True;
  13955. Exit;
  13956. end;
  13957. end;
  13958. { removes the line marked with (x) from the sequence
  13959. and/or/xor/add/sub/... $x, %y
  13960. test/or %y, %y | test $-1, %y (x)
  13961. j(n)z _Label
  13962. as the first instruction already adjusts the ZF
  13963. %y operand may also be a reference }
  13964. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  13965. MatchOperand(taicpu(p).oper[0]^,-1);
  13966. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  13967. GetLastInstruction(p, hp1) and
  13968. (tai(hp1).typ = ait_instruction) and
  13969. GetNextInstruction(p,hp2) and
  13970. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  13971. case taicpu(hp1).opcode Of
  13972. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  13973. { These two instructions set the zero flag if the result is zero }
  13974. A_POPCNT, A_LZCNT:
  13975. begin
  13976. if (
  13977. { With POPCNT, an input of zero will set the zero flag
  13978. because the population count of zero is zero }
  13979. (taicpu(hp1).opcode = A_POPCNT) and
  13980. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  13981. (
  13982. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  13983. { Faster than going through the second half of the 'or'
  13984. condition below }
  13985. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  13986. )
  13987. ) or (
  13988. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  13989. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13990. { and in case of carry for A(E)/B(E)/C/NC }
  13991. (
  13992. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  13993. (
  13994. (taicpu(hp1).opcode <> A_ADD) and
  13995. (taicpu(hp1).opcode <> A_SUB) and
  13996. (taicpu(hp1).opcode <> A_LZCNT)
  13997. )
  13998. )
  13999. ) then
  14000. begin
  14001. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14002. RemoveCurrentP(p, hp2);
  14003. Result:=true;
  14004. Exit;
  14005. end;
  14006. end;
  14007. A_SHL, A_SAL, A_SHR, A_SAR:
  14008. begin
  14009. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14010. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14011. { therefore, it's only safe to do this optimization for }
  14012. { shifts by a (nonzero) constant }
  14013. (taicpu(hp1).oper[0]^.typ = top_const) and
  14014. (taicpu(hp1).oper[0]^.val <> 0) and
  14015. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14016. { and in case of carry for A(E)/B(E)/C/NC }
  14017. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14018. begin
  14019. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14020. RemoveCurrentP(p, hp2);
  14021. Result:=true;
  14022. Exit;
  14023. end;
  14024. end;
  14025. A_DEC, A_INC, A_NEG:
  14026. begin
  14027. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14028. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14029. { and in case of carry for A(E)/B(E)/C/NC }
  14030. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14031. begin
  14032. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14033. RemoveCurrentP(p, hp2);
  14034. Result:=true;
  14035. Exit;
  14036. end;
  14037. end;
  14038. A_ANDN, A_BZHI:
  14039. begin
  14040. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14041. { Only the zero and sign flags are consistent with what the result is }
  14042. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14043. begin
  14044. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14045. RemoveCurrentP(p, hp2);
  14046. Result:=true;
  14047. Exit;
  14048. end;
  14049. end;
  14050. A_BEXTR:
  14051. begin
  14052. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14053. { Only the zero flag is set }
  14054. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14055. begin
  14056. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14057. RemoveCurrentP(p, hp2);
  14058. Result:=true;
  14059. Exit;
  14060. end;
  14061. end;
  14062. else
  14063. ;
  14064. end; { case }
  14065. { change "test $-1,%reg" into "test %reg,%reg" }
  14066. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14067. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14068. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14069. if MatchInstruction(p, A_OR, []) and
  14070. { Can only match if they're both registers }
  14071. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14072. begin
  14073. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14074. taicpu(p).opcode := A_TEST;
  14075. { No need to set Result to True, as we've done all the optimisations we can }
  14076. end;
  14077. end;
  14078. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14079. var
  14080. hp1,hp3 : tai;
  14081. {$ifndef x86_64}
  14082. hp2 : taicpu;
  14083. {$endif x86_64}
  14084. begin
  14085. Result:=false;
  14086. hp3:=nil;
  14087. {$ifndef x86_64}
  14088. { don't do this on modern CPUs, this really hurts them due to
  14089. broken call/ret pairing }
  14090. if (current_settings.optimizecputype < cpu_Pentium2) and
  14091. not(cs_create_pic in current_settings.moduleswitches) and
  14092. GetNextInstruction(p, hp1) and
  14093. MatchInstruction(hp1,A_JMP,[S_NO]) and
  14094. MatchOpType(taicpu(hp1),top_ref) and
  14095. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14096. begin
  14097. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14098. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14099. InsertLLItem(p.previous, p, hp2);
  14100. taicpu(p).opcode := A_JMP;
  14101. taicpu(p).is_jmp := true;
  14102. RemoveInstruction(hp1);
  14103. Result:=true;
  14104. end
  14105. else
  14106. {$endif x86_64}
  14107. { replace
  14108. call procname
  14109. ret
  14110. by
  14111. jmp procname
  14112. but do it only on level 4 because it destroys stack back traces
  14113. else if the subroutine is marked as no return, remove the ret
  14114. }
  14115. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14116. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14117. GetNextInstruction(p, hp1) and
  14118. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14119. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14120. SetAndTest(hp1,hp3) and
  14121. GetNextInstruction(hp1,hp1) and
  14122. MatchInstruction(hp1,A_RET,[S_NO])
  14123. )
  14124. ) and
  14125. (taicpu(hp1).ops=0) then
  14126. begin
  14127. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14128. { we might destroy stack alignment here if we do not do a call }
  14129. (target_info.stackalign<=sizeof(SizeUInt)) then
  14130. begin
  14131. taicpu(p).opcode := A_JMP;
  14132. taicpu(p).is_jmp := true;
  14133. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14134. end
  14135. else
  14136. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14137. RemoveInstruction(hp1);
  14138. if Assigned(hp3) then
  14139. begin
  14140. AsmL.Remove(hp3);
  14141. AsmL.InsertBefore(hp3,p)
  14142. end;
  14143. Result:=true;
  14144. end;
  14145. end;
  14146. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14147. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14148. begin
  14149. case OpSize of
  14150. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14151. Result := (Val <= $FF) and (Val >= -128);
  14152. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14153. Result := (Val <= $FFFF) and (Val >= -32768);
  14154. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14155. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14156. else
  14157. Result := True;
  14158. end;
  14159. end;
  14160. var
  14161. hp1, hp2 : tai;
  14162. SizeChange: Boolean;
  14163. PreMessage: string;
  14164. begin
  14165. Result := False;
  14166. if (taicpu(p).oper[0]^.typ = top_reg) and
  14167. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14168. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14169. begin
  14170. { Change (using movzbl %al,%eax as an example):
  14171. movzbl %al, %eax movzbl %al, %eax
  14172. cmpl x, %eax testl %eax,%eax
  14173. To:
  14174. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14175. movzbl %al, %eax movzbl %al, %eax
  14176. Smaller instruction and minimises pipeline stall as the CPU
  14177. doesn't have to wait for the register to get zero-extended. [Kit]
  14178. Also allow if the smaller of the two registers is being checked,
  14179. as this still removes the false dependency.
  14180. }
  14181. if
  14182. (
  14183. (
  14184. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14185. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14186. ) or (
  14187. { If MatchOperand returns True, they must both be registers }
  14188. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14189. )
  14190. ) and
  14191. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14192. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14193. begin
  14194. PreMessage := debug_op2str(taicpu(hp1).opcode) + debug_opsize2str(taicpu(hp1).opsize) + ' ' + debug_operstr(taicpu(hp1).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' -> ' + debug_op2str(taicpu(hp1).opcode);
  14195. asml.Remove(hp1);
  14196. asml.InsertBefore(hp1, p);
  14197. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14198. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14199. begin
  14200. taicpu(hp1).opcode := A_TEST;
  14201. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14202. end;
  14203. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14204. case taicpu(p).opsize of
  14205. S_BW, S_BL:
  14206. begin
  14207. SizeChange := taicpu(hp1).opsize <> S_B;
  14208. taicpu(hp1).changeopsize(S_B);
  14209. end;
  14210. S_WL:
  14211. begin
  14212. SizeChange := taicpu(hp1).opsize <> S_W;
  14213. taicpu(hp1).changeopsize(S_W);
  14214. end
  14215. else
  14216. InternalError(2020112701);
  14217. end;
  14218. UpdateUsedRegs(tai(p.Next));
  14219. { Check if the register is used aferwards - if not, we can
  14220. remove the movzx instruction completely }
  14221. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14222. begin
  14223. { Hp1 is a better position than p for debugging purposes }
  14224. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14225. RemoveCurrentp(p, hp1);
  14226. Result := True;
  14227. end;
  14228. if SizeChange then
  14229. DebugMsg(SPeepholeOptimization + PreMessage +
  14230. debug_opsize2str(taicpu(hp1).opsize) + ' ' + debug_operstr(taicpu(hp1).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (smaller and minimises pipeline stall - MovzxCmp2CmpMovzx)', hp1)
  14231. else
  14232. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14233. Exit;
  14234. end;
  14235. { Change (using movzwl %ax,%eax as an example):
  14236. movzwl %ax, %eax
  14237. movb %al, (dest) (Register is smaller than read register in movz)
  14238. To:
  14239. movb %al, (dest) (Move one back to avoid a false dependency)
  14240. movzwl %ax, %eax
  14241. }
  14242. if (taicpu(hp1).opcode = A_MOV) and
  14243. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14244. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14245. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14246. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14247. begin
  14248. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14249. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14250. asml.Remove(hp1);
  14251. asml.InsertBefore(hp1, p);
  14252. if taicpu(hp1).oper[1]^.typ = top_reg then
  14253. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14254. { Check if the register is used aferwards - if not, we can
  14255. remove the movzx instruction completely }
  14256. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14257. begin
  14258. { Hp1 is a better position than p for debugging purposes }
  14259. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14260. RemoveCurrentp(p, hp1);
  14261. Result := True;
  14262. end;
  14263. Exit;
  14264. end;
  14265. end;
  14266. end;
  14267. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14268. var
  14269. hp1: tai;
  14270. {$ifdef x86_64}
  14271. PreMessage, RegName: string;
  14272. {$endif x86_64}
  14273. begin
  14274. Result := False;
  14275. { If x is a power of 2 (popcnt = 1), change:
  14276. xor $x, %reg/ref
  14277. To:
  14278. btc lb(x), %reg/ref
  14279. }
  14280. if IsBTXAcceptable(p) and
  14281. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14282. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14283. (
  14284. { Don't optimise if a test instruction follows }
  14285. not GetNextInstruction(p, hp1) or
  14286. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14287. ) then
  14288. begin
  14289. DebugMsg(SPeepholeOptimization + 'Changed XOR $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BTC $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Xor2Btc)', p);
  14290. taicpu(p).opcode := A_BTC;
  14291. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14292. Result := True;
  14293. Exit;
  14294. end;
  14295. {$ifdef x86_64}
  14296. { Code size reduction by J. Gareth "Kit" Moreton }
  14297. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14298. as this removes the REX prefix }
  14299. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14300. Exit;
  14301. if taicpu(p).oper[0]^.typ <> top_reg then
  14302. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14303. InternalError(2018011500);
  14304. case taicpu(p).opsize of
  14305. S_Q:
  14306. begin
  14307. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14308. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14309. { The actual optimization }
  14310. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14311. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14312. taicpu(p).changeopsize(S_L);
  14313. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14314. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14315. end;
  14316. else
  14317. ;
  14318. end;
  14319. {$endif x86_64}
  14320. end;
  14321. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14322. var
  14323. XReg: TRegister;
  14324. begin
  14325. Result := False;
  14326. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14327. Smaller encoding and slightly faster on some platforms (also works for
  14328. ZMM-sized registers) }
  14329. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14330. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14331. begin
  14332. XReg := taicpu(p).oper[0]^.reg;
  14333. if (taicpu(p).oper[1]^.reg = XReg) then
  14334. begin
  14335. taicpu(p).changeopsize(S_XMM);
  14336. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14337. if (cs_opt_size in current_settings.optimizerswitches) then
  14338. begin
  14339. { Change input registers to %xmm0 to reduce size. Note that
  14340. there's a risk of a false dependency doing this, so only
  14341. optimise for size here }
  14342. XReg := NR_XMM0;
  14343. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14344. end
  14345. else
  14346. begin
  14347. setsubreg(XReg, R_SUBMMX);
  14348. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14349. end;
  14350. taicpu(p).oper[0]^.reg := XReg;
  14351. taicpu(p).oper[1]^.reg := XReg;
  14352. Result := True;
  14353. end;
  14354. end;
  14355. end;
  14356. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14357. var
  14358. OperIdx: Integer;
  14359. begin
  14360. for OperIdx := 0 to p.ops - 1 do
  14361. if p.oper[OperIdx]^.typ = top_ref then
  14362. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14363. end;
  14364. end.