aoptx86.pas 688 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988
  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) : 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. { Handle instructions that behave differently depending on the size and operand count }
  861. case taicpu(p1).opcode of
  862. A_MUL, A_DIV, A_IDIV:
  863. if taicpu(p1).opsize = S_B then
  864. Result := (getsupreg(Reg) = RS_EAX)
  865. else
  866. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  867. A_IMUL:
  868. if taicpu(p1).ops = 1 then
  869. begin
  870. if taicpu(p1).opsize = S_B then
  871. Result := (getsupreg(Reg) = RS_EAX)
  872. else
  873. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  874. end;
  875. { If ops are greater than 1, call inherited method }
  876. else
  877. case getsupreg(reg) of
  878. { RS_EAX = RS_RAX on x86-64 }
  879. RS_EAX:
  880. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. RS_ECX:
  882. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. RS_EDX:
  884. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  885. RS_EBX:
  886. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  887. RS_ESP:
  888. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  889. RS_EBP:
  890. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  891. RS_ESI:
  892. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. RS_EDI:
  894. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  895. else
  896. ;
  897. end;
  898. end;
  899. if result then
  900. exit;
  901. end
  902. else if getregtype(reg)=R_MMREGISTER then
  903. begin
  904. case getsupreg(reg) of
  905. RS_XMM0:
  906. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  907. else
  908. ;
  909. end;
  910. if result then
  911. exit;
  912. end
  913. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  914. begin
  915. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  916. exit(true);
  917. case getsubreg(reg) of
  918. R_SUBFLAGCARRY:
  919. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  920. R_SUBFLAGPARITY:
  921. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  922. R_SUBFLAGAUXILIARY:
  923. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  924. R_SUBFLAGZERO:
  925. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  926. R_SUBFLAGSIGN:
  927. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  928. R_SUBFLAGOVERFLOW:
  929. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  930. R_SUBFLAGINTERRUPT:
  931. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  932. R_SUBFLAGDIRECTION:
  933. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  934. R_SUBW,R_SUBD,R_SUBQ:
  935. { Everything except the direction bits }
  936. Result:=
  937. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  938. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  939. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  940. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  941. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  942. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  943. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  944. else
  945. ;
  946. end;
  947. if result then
  948. exit;
  949. end
  950. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  951. exit(true);
  952. Result:=inherited RegInInstruction(Reg, p1);
  953. end;
  954. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  955. const
  956. WriteOps: array[0..3] of set of TInsChange =
  957. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  958. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  959. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  960. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  961. var
  962. OperIdx: Integer;
  963. begin
  964. Result := False;
  965. if p1.typ <> ait_instruction then
  966. exit;
  967. with insprop[taicpu(p1).opcode] do
  968. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  969. begin
  970. case getsubreg(reg) of
  971. R_SUBW,R_SUBD,R_SUBQ:
  972. Result :=
  973. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  974. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  975. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  976. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  977. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  978. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  979. R_SUBFLAGCARRY:
  980. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  981. R_SUBFLAGPARITY:
  982. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  983. R_SUBFLAGAUXILIARY:
  984. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  985. R_SUBFLAGZERO:
  986. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  987. R_SUBFLAGSIGN:
  988. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  989. R_SUBFLAGOVERFLOW:
  990. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  991. R_SUBFLAGINTERRUPT:
  992. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  993. R_SUBFLAGDIRECTION:
  994. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  995. else
  996. internalerror(2017042602);
  997. end;
  998. exit;
  999. end;
  1000. case taicpu(p1).opcode of
  1001. A_CALL:
  1002. { We could potentially set Result to False if the register in
  1003. question is non-volatile for the subroutine's calling convention,
  1004. but this would require detecting the calling convention in use and
  1005. also assuming that the routine doesn't contain malformed assembly
  1006. language, for example... so it could only be done under -O4 as it
  1007. would be considered a side-effect. [Kit] }
  1008. Result := True;
  1009. A_MOVSD:
  1010. { special handling for SSE MOVSD }
  1011. if (taicpu(p1).ops>0) then
  1012. begin
  1013. if taicpu(p1).ops<>2 then
  1014. internalerror(2017042703);
  1015. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1016. end;
  1017. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1018. so fix it here (FK)
  1019. }
  1020. A_VMOVSS,
  1021. A_VMOVSD:
  1022. begin
  1023. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1024. exit;
  1025. end;
  1026. A_MUL, A_DIV, A_IDIV:
  1027. begin
  1028. if taicpu(p1).opsize = S_B then
  1029. Result := (getsupreg(Reg) = RS_EAX)
  1030. else
  1031. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1032. end;
  1033. A_IMUL:
  1034. begin
  1035. if taicpu(p1).ops = 1 then
  1036. begin
  1037. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1038. end
  1039. else
  1040. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1041. Exit;
  1042. end;
  1043. else
  1044. ;
  1045. end;
  1046. if Result then
  1047. exit;
  1048. with insprop[taicpu(p1).opcode] do
  1049. begin
  1050. if getregtype(reg)=R_INTREGISTER then
  1051. begin
  1052. case getsupreg(reg) of
  1053. RS_EAX:
  1054. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1055. begin
  1056. Result := True;
  1057. exit
  1058. end;
  1059. RS_ECX:
  1060. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1061. begin
  1062. Result := True;
  1063. exit
  1064. end;
  1065. RS_EDX:
  1066. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1067. begin
  1068. Result := True;
  1069. exit
  1070. end;
  1071. RS_EBX:
  1072. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1073. begin
  1074. Result := True;
  1075. exit
  1076. end;
  1077. RS_ESP:
  1078. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1079. begin
  1080. Result := True;
  1081. exit
  1082. end;
  1083. RS_EBP:
  1084. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1085. begin
  1086. Result := True;
  1087. exit
  1088. end;
  1089. RS_ESI:
  1090. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1091. begin
  1092. Result := True;
  1093. exit
  1094. end;
  1095. RS_EDI:
  1096. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1097. begin
  1098. Result := True;
  1099. exit
  1100. end;
  1101. end;
  1102. end;
  1103. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1104. if (WriteOps[OperIdx]*Ch<>[]) and
  1105. { The register doesn't get modified inside a reference }
  1106. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1107. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1108. begin
  1109. Result := true;
  1110. exit
  1111. end;
  1112. end;
  1113. end;
  1114. {$ifdef DEBUG_AOPTCPU}
  1115. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1116. begin
  1117. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1118. end;
  1119. function debug_tostr(i: tcgint): string; inline;
  1120. begin
  1121. Result := tostr(i);
  1122. end;
  1123. function debug_hexstr(i: tcgint): string;
  1124. begin
  1125. Result := '0x';
  1126. case i of
  1127. 0..$FF:
  1128. Result := Result + hexstr(i, 2);
  1129. $100..$FFFF:
  1130. Result := Result + hexstr(i, 4);
  1131. $10000..$FFFFFF:
  1132. Result := Result + hexstr(i, 6);
  1133. $1000000..$FFFFFFFF:
  1134. Result := Result + hexstr(i, 8);
  1135. else
  1136. Result := Result + hexstr(i, 16);
  1137. end;
  1138. end;
  1139. function debug_regname(r: TRegister): string; inline;
  1140. begin
  1141. Result := '%' + std_regname(r);
  1142. end;
  1143. { Debug output function - creates a string representation of an operator }
  1144. function debug_operstr(oper: TOper): string;
  1145. begin
  1146. case oper.typ of
  1147. top_const:
  1148. Result := '$' + debug_tostr(oper.val);
  1149. top_reg:
  1150. Result := debug_regname(oper.reg);
  1151. top_ref:
  1152. begin
  1153. if oper.ref^.offset <> 0 then
  1154. Result := debug_tostr(oper.ref^.offset) + '('
  1155. else
  1156. Result := '(';
  1157. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1158. begin
  1159. Result := Result + debug_regname(oper.ref^.base);
  1160. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1161. Result := Result + ',' + debug_regname(oper.ref^.index);
  1162. end
  1163. else
  1164. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1165. Result := Result + debug_regname(oper.ref^.index);
  1166. if (oper.ref^.scalefactor > 1) then
  1167. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1168. else
  1169. Result := Result + ')';
  1170. end;
  1171. else
  1172. Result := '[UNKNOWN]';
  1173. end;
  1174. end;
  1175. function debug_op2str(opcode: tasmop): string; inline;
  1176. begin
  1177. Result := std_op2str[opcode];
  1178. end;
  1179. function debug_opsize2str(opsize: topsize): string; inline;
  1180. begin
  1181. Result := gas_opsize2str[opsize];
  1182. end;
  1183. {$else DEBUG_AOPTCPU}
  1184. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1185. begin
  1186. end;
  1187. function debug_tostr(i: tcgint): string; inline;
  1188. begin
  1189. Result := '';
  1190. end;
  1191. function debug_hexstr(i: tcgint): string; inline;
  1192. begin
  1193. Result := '';
  1194. end;
  1195. function debug_regname(r: TRegister): string; inline;
  1196. begin
  1197. Result := '';
  1198. end;
  1199. function debug_operstr(oper: TOper): string; inline;
  1200. begin
  1201. Result := '';
  1202. end;
  1203. function debug_op2str(opcode: tasmop): string; inline;
  1204. begin
  1205. Result := '';
  1206. end;
  1207. function debug_opsize2str(opsize: topsize): string; inline;
  1208. begin
  1209. Result := '';
  1210. end;
  1211. {$endif DEBUG_AOPTCPU}
  1212. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1213. begin
  1214. {$ifdef x86_64}
  1215. { Always fine on x86-64 }
  1216. Result := True;
  1217. {$else x86_64}
  1218. Result :=
  1219. {$ifdef i8086}
  1220. (current_settings.cputype >= cpu_386) and
  1221. {$endif i8086}
  1222. (
  1223. { Always accept if optimising for size }
  1224. (cs_opt_size in current_settings.optimizerswitches) or
  1225. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1226. (current_settings.optimizecputype >= cpu_Pentium2)
  1227. );
  1228. {$endif x86_64}
  1229. end;
  1230. { Attempts to allocate a volatile integer register for use between p and hp,
  1231. using AUsedRegs for the current register usage information. Returns NR_NO
  1232. if no free register could be found }
  1233. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1234. var
  1235. RegSet: TCPURegisterSet;
  1236. CurrentSuperReg: Integer;
  1237. CurrentReg: TRegister;
  1238. Currentp: tai;
  1239. Breakout: Boolean;
  1240. begin
  1241. Result := NR_NO;
  1242. RegSet :=
  1243. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1244. current_procinfo.saved_regs_int;
  1245. (*
  1246. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1247. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1248. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1249. *)
  1250. for CurrentSuperReg in RegSet do
  1251. begin
  1252. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1253. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1254. {$if defined(i386) or defined(i8086)}
  1255. { If the target size is 8-bit, make sure we can actually encode it }
  1256. and (
  1257. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1258. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1259. )
  1260. {$endif i386 or i8086}
  1261. then
  1262. begin
  1263. Currentp := p;
  1264. Breakout := False;
  1265. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1266. begin
  1267. case Currentp.typ of
  1268. ait_instruction:
  1269. begin
  1270. if RegInInstruction(CurrentReg, Currentp) then
  1271. begin
  1272. Breakout := True;
  1273. Break;
  1274. end;
  1275. { Cannot allocate across an unconditional jump }
  1276. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1277. Exit;
  1278. end;
  1279. ait_marker:
  1280. { Don't try anything more if a marker is hit }
  1281. Exit;
  1282. ait_regalloc:
  1283. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1284. begin
  1285. Breakout := True;
  1286. Break;
  1287. end;
  1288. else
  1289. ;
  1290. end;
  1291. end;
  1292. if Breakout then
  1293. { Try the next register }
  1294. Continue;
  1295. { We have a free register available }
  1296. Result := CurrentReg;
  1297. if not DontAlloc then
  1298. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1299. Exit;
  1300. end;
  1301. end;
  1302. end;
  1303. { Attempts to allocate a volatile MM register for use between p and hp,
  1304. using AUsedRegs for the current register usage information. Returns NR_NO
  1305. if no free register could be found }
  1306. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1307. var
  1308. RegSet: TCPURegisterSet;
  1309. CurrentSuperReg: Integer;
  1310. CurrentReg: TRegister;
  1311. Currentp: tai;
  1312. Breakout: Boolean;
  1313. begin
  1314. Result := NR_NO;
  1315. RegSet :=
  1316. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1317. current_procinfo.saved_regs_mm;
  1318. for CurrentSuperReg in RegSet do
  1319. begin
  1320. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1321. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1322. begin
  1323. Currentp := p;
  1324. Breakout := False;
  1325. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1326. begin
  1327. case Currentp.typ of
  1328. ait_instruction:
  1329. begin
  1330. if RegInInstruction(CurrentReg, Currentp) then
  1331. begin
  1332. Breakout := True;
  1333. Break;
  1334. end;
  1335. { Cannot allocate across an unconditional jump }
  1336. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1337. Exit;
  1338. end;
  1339. ait_marker:
  1340. { Don't try anything more if a marker is hit }
  1341. Exit;
  1342. ait_regalloc:
  1343. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1344. begin
  1345. Breakout := True;
  1346. Break;
  1347. end;
  1348. else
  1349. ;
  1350. end;
  1351. end;
  1352. if Breakout then
  1353. { Try the next register }
  1354. Continue;
  1355. { We have a free register available }
  1356. Result := CurrentReg;
  1357. if not DontAlloc then
  1358. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1359. Exit;
  1360. end;
  1361. end;
  1362. end;
  1363. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1364. begin
  1365. if not SuperRegistersEqual(reg1,reg2) then
  1366. exit(false);
  1367. if getregtype(reg1)<>R_INTREGISTER then
  1368. exit(true); {because SuperRegisterEqual is true}
  1369. case getsubreg(reg1) of
  1370. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1371. higher, it preserves the high bits, so the new value depends on
  1372. reg2's previous value. In other words, it is equivalent to doing:
  1373. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1374. R_SUBL:
  1375. exit(getsubreg(reg2)=R_SUBL);
  1376. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1377. higher, it actually does a:
  1378. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1379. R_SUBH:
  1380. exit(getsubreg(reg2)=R_SUBH);
  1381. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1382. bits of reg2:
  1383. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1384. R_SUBW:
  1385. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1386. { a write to R_SUBD always overwrites every other subregister,
  1387. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1388. R_SUBD,
  1389. R_SUBQ:
  1390. exit(true);
  1391. else
  1392. internalerror(2017042801);
  1393. end;
  1394. end;
  1395. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1396. begin
  1397. if not SuperRegistersEqual(reg1,reg2) then
  1398. exit(false);
  1399. if getregtype(reg1)<>R_INTREGISTER then
  1400. exit(true); {because SuperRegisterEqual is true}
  1401. case getsubreg(reg1) of
  1402. R_SUBL:
  1403. exit(getsubreg(reg2)<>R_SUBH);
  1404. R_SUBH:
  1405. exit(getsubreg(reg2)<>R_SUBL);
  1406. R_SUBW,
  1407. R_SUBD,
  1408. R_SUBQ:
  1409. exit(true);
  1410. else
  1411. internalerror(2017042802);
  1412. end;
  1413. end;
  1414. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1415. var
  1416. hp1 : tai;
  1417. l : TCGInt;
  1418. begin
  1419. result:=false;
  1420. if not(GetNextInstruction(p, hp1)) then
  1421. exit;
  1422. { changes the code sequence
  1423. shr/sar const1, x
  1424. shl const2, x
  1425. to
  1426. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1427. if (taicpu(p).oper[0]^.typ = top_const) and
  1428. MatchInstruction(hp1,A_SHL,[]) and
  1429. (taicpu(hp1).oper[0]^.typ = top_const) and
  1430. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1431. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1432. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1433. begin
  1434. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1435. not(cs_opt_size in current_settings.optimizerswitches) then
  1436. begin
  1437. { shr/sar const1, %reg
  1438. shl const2, %reg
  1439. with const1 > const2 }
  1440. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1441. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1442. taicpu(hp1).opcode := A_AND;
  1443. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1444. case taicpu(p).opsize Of
  1445. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1446. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1447. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1448. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1449. else
  1450. Internalerror(2017050703)
  1451. end;
  1452. end
  1453. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1454. not(cs_opt_size in current_settings.optimizerswitches) then
  1455. begin
  1456. { shr/sar const1, %reg
  1457. shl const2, %reg
  1458. with const1 < const2 }
  1459. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1460. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1461. taicpu(p).opcode := A_AND;
  1462. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1463. case taicpu(p).opsize Of
  1464. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1465. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1466. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1467. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1468. else
  1469. Internalerror(2017050702)
  1470. end;
  1471. end
  1472. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1473. begin
  1474. { shr/sar const1, %reg
  1475. shl const2, %reg
  1476. with const1 = const2 }
  1477. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1478. taicpu(p).opcode := A_AND;
  1479. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1480. case taicpu(p).opsize Of
  1481. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1482. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1483. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1484. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1485. else
  1486. Internalerror(2017050701)
  1487. end;
  1488. RemoveInstruction(hp1);
  1489. end;
  1490. end;
  1491. end;
  1492. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1493. var
  1494. opsize : topsize;
  1495. hp1, hp2 : tai;
  1496. tmpref : treference;
  1497. ShiftValue : Cardinal;
  1498. BaseValue : TCGInt;
  1499. begin
  1500. result:=false;
  1501. opsize:=taicpu(p).opsize;
  1502. { changes certain "imul const, %reg"'s to lea sequences }
  1503. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1504. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1505. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1506. if (taicpu(p).oper[0]^.val = 1) then
  1507. if (taicpu(p).ops = 2) then
  1508. { remove "imul $1, reg" }
  1509. begin
  1510. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1511. Result := RemoveCurrentP(p);
  1512. end
  1513. else
  1514. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1515. begin
  1516. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1517. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1518. asml.InsertAfter(hp1, p);
  1519. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1520. RemoveCurrentP(p, hp1);
  1521. Result := True;
  1522. end
  1523. else if ((taicpu(p).ops <= 2) or
  1524. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1525. not(cs_opt_size in current_settings.optimizerswitches) and
  1526. (not(GetNextInstruction(p, hp1)) or
  1527. not((tai(hp1).typ = ait_instruction) and
  1528. ((taicpu(hp1).opcode=A_Jcc) and
  1529. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1530. begin
  1531. {
  1532. imul X, reg1, reg2 to
  1533. lea (reg1,reg1,Y), reg2
  1534. shl ZZ,reg2
  1535. imul XX, reg1 to
  1536. lea (reg1,reg1,YY), reg1
  1537. shl ZZ,reg2
  1538. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1539. it does not exist as a separate optimization target in FPC though.
  1540. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1541. at most two zeros
  1542. }
  1543. reference_reset(tmpref,1,[]);
  1544. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1545. begin
  1546. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1547. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1548. TmpRef.base := taicpu(p).oper[1]^.reg;
  1549. TmpRef.index := taicpu(p).oper[1]^.reg;
  1550. if not(BaseValue in [3,5,9]) then
  1551. Internalerror(2018110101);
  1552. TmpRef.ScaleFactor := BaseValue-1;
  1553. if (taicpu(p).ops = 2) then
  1554. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1555. else
  1556. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1557. AsmL.InsertAfter(hp1,p);
  1558. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1559. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1560. RemoveCurrentP(p, hp1);
  1561. if ShiftValue>0 then
  1562. begin
  1563. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1564. AsmL.InsertAfter(hp2,hp1);
  1565. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1566. end;
  1567. Result := True;
  1568. end;
  1569. end;
  1570. end;
  1571. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1572. begin
  1573. Result := False;
  1574. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1575. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1576. begin
  1577. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1578. taicpu(p).opcode := A_MOV;
  1579. Result := True;
  1580. end;
  1581. end;
  1582. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1583. var
  1584. p: taicpu absolute hp; { Implicit typecast }
  1585. i: Integer;
  1586. begin
  1587. Result := False;
  1588. if not assigned(hp) or
  1589. (hp.typ <> ait_instruction) then
  1590. Exit;
  1591. Prefetch(insprop[p.opcode]);
  1592. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1593. with insprop[p.opcode] do
  1594. begin
  1595. case getsubreg(reg) of
  1596. R_SUBW,R_SUBD,R_SUBQ:
  1597. Result:=
  1598. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1599. uncommon flags are checked first }
  1600. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1601. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1602. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1603. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1604. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1605. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1606. R_SUBFLAGCARRY:
  1607. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1608. R_SUBFLAGPARITY:
  1609. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1610. R_SUBFLAGAUXILIARY:
  1611. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1612. R_SUBFLAGZERO:
  1613. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1614. R_SUBFLAGSIGN:
  1615. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1616. R_SUBFLAGOVERFLOW:
  1617. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1618. R_SUBFLAGINTERRUPT:
  1619. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1620. R_SUBFLAGDIRECTION:
  1621. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1622. else
  1623. internalerror(2017050501);
  1624. end;
  1625. exit;
  1626. end;
  1627. { Handle special cases first }
  1628. case p.opcode of
  1629. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1630. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1631. begin
  1632. Result :=
  1633. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1634. (p.oper[1]^.typ = top_reg) and
  1635. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1636. (
  1637. (p.oper[0]^.typ = top_const) or
  1638. (
  1639. (p.oper[0]^.typ = top_reg) and
  1640. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1641. ) or (
  1642. (p.oper[0]^.typ = top_ref) and
  1643. not RegInRef(reg,p.oper[0]^.ref^)
  1644. )
  1645. );
  1646. end;
  1647. A_MUL, A_IMUL:
  1648. Result :=
  1649. (
  1650. (p.ops=3) and { IMUL only }
  1651. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1652. (
  1653. (
  1654. (p.oper[1]^.typ=top_reg) and
  1655. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1656. ) or (
  1657. (p.oper[1]^.typ=top_ref) and
  1658. not RegInRef(reg,p.oper[1]^.ref^)
  1659. )
  1660. )
  1661. ) or (
  1662. (
  1663. (p.ops=1) and
  1664. (
  1665. (
  1666. (
  1667. (p.oper[0]^.typ=top_reg) and
  1668. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1669. )
  1670. ) or (
  1671. (p.oper[0]^.typ=top_ref) and
  1672. not RegInRef(reg,p.oper[0]^.ref^)
  1673. )
  1674. ) and (
  1675. (
  1676. (p.opsize=S_B) and
  1677. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1678. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1679. ) or (
  1680. (p.opsize=S_W) and
  1681. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1682. ) or (
  1683. (p.opsize=S_L) and
  1684. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1685. {$ifdef x86_64}
  1686. ) or (
  1687. (p.opsize=S_Q) and
  1688. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1689. {$endif x86_64}
  1690. )
  1691. )
  1692. )
  1693. );
  1694. A_CBW:
  1695. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1696. {$ifndef x86_64}
  1697. A_LDS:
  1698. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1699. A_LES:
  1700. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1701. {$endif not x86_64}
  1702. A_LFS:
  1703. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1704. A_LGS:
  1705. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1706. A_LSS:
  1707. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1708. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1709. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1710. A_LODSB:
  1711. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1712. A_LODSW:
  1713. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1714. {$ifdef x86_64}
  1715. A_LODSQ:
  1716. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1717. {$endif x86_64}
  1718. A_LODSD:
  1719. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1720. A_FSTSW, A_FNSTSW:
  1721. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1722. else
  1723. begin
  1724. with insprop[p.opcode] do
  1725. begin
  1726. if (
  1727. { xor %reg,%reg etc. is classed as a new value }
  1728. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1729. MatchOpType(p, top_reg, top_reg) and
  1730. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1731. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1732. ) then
  1733. begin
  1734. Result := True;
  1735. Exit;
  1736. end;
  1737. { Make sure the entire register is overwritten }
  1738. if (getregtype(reg) = R_INTREGISTER) then
  1739. begin
  1740. if (p.ops > 0) then
  1741. begin
  1742. if RegInOp(reg, p.oper[0]^) then
  1743. begin
  1744. if (p.oper[0]^.typ = top_ref) then
  1745. begin
  1746. if RegInRef(reg, p.oper[0]^.ref^) then
  1747. begin
  1748. Result := False;
  1749. Exit;
  1750. end;
  1751. end
  1752. else if (p.oper[0]^.typ = top_reg) then
  1753. begin
  1754. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1755. begin
  1756. Result := False;
  1757. Exit;
  1758. end
  1759. else if ([Ch_WOp1]*Ch<>[]) then
  1760. begin
  1761. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1762. Result := True
  1763. else
  1764. begin
  1765. Result := False;
  1766. Exit;
  1767. end;
  1768. end;
  1769. end;
  1770. end;
  1771. if (p.ops > 1) then
  1772. begin
  1773. if RegInOp(reg, p.oper[1]^) then
  1774. begin
  1775. if (p.oper[1]^.typ = top_ref) then
  1776. begin
  1777. if RegInRef(reg, p.oper[1]^.ref^) then
  1778. begin
  1779. Result := False;
  1780. Exit;
  1781. end;
  1782. end
  1783. else if (p.oper[1]^.typ = top_reg) then
  1784. begin
  1785. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1786. begin
  1787. Result := False;
  1788. Exit;
  1789. end
  1790. else if ([Ch_WOp2]*Ch<>[]) then
  1791. begin
  1792. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1793. Result := True
  1794. else
  1795. begin
  1796. Result := False;
  1797. Exit;
  1798. end;
  1799. end;
  1800. end;
  1801. end;
  1802. if (p.ops > 2) then
  1803. begin
  1804. if RegInOp(reg, p.oper[2]^) then
  1805. begin
  1806. if (p.oper[2]^.typ = top_ref) then
  1807. begin
  1808. if RegInRef(reg, p.oper[2]^.ref^) then
  1809. begin
  1810. Result := False;
  1811. Exit;
  1812. end;
  1813. end
  1814. else if (p.oper[2]^.typ = top_reg) then
  1815. begin
  1816. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1817. begin
  1818. Result := False;
  1819. Exit;
  1820. end
  1821. else if ([Ch_WOp3]*Ch<>[]) then
  1822. begin
  1823. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1824. Result := True
  1825. else
  1826. begin
  1827. Result := False;
  1828. Exit;
  1829. end;
  1830. end;
  1831. end;
  1832. end;
  1833. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1834. begin
  1835. if (p.oper[3]^.typ = top_ref) then
  1836. begin
  1837. if RegInRef(reg, p.oper[3]^.ref^) then
  1838. begin
  1839. Result := False;
  1840. Exit;
  1841. end;
  1842. end
  1843. else if (p.oper[3]^.typ = top_reg) then
  1844. begin
  1845. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1846. begin
  1847. Result := False;
  1848. Exit;
  1849. end
  1850. else if ([Ch_WOp4]*Ch<>[]) then
  1851. begin
  1852. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1853. Result := True
  1854. else
  1855. begin
  1856. Result := False;
  1857. Exit;
  1858. end;
  1859. end;
  1860. end;
  1861. end;
  1862. end;
  1863. end;
  1864. end;
  1865. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1866. case getsupreg(reg) of
  1867. RS_EAX:
  1868. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1869. begin
  1870. Result := True;
  1871. Exit;
  1872. end;
  1873. RS_ECX:
  1874. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1875. begin
  1876. Result := True;
  1877. Exit;
  1878. end;
  1879. RS_EDX:
  1880. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1881. begin
  1882. Result := True;
  1883. Exit;
  1884. end;
  1885. RS_EBX:
  1886. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1887. begin
  1888. Result := True;
  1889. Exit;
  1890. end;
  1891. RS_ESP:
  1892. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1893. begin
  1894. Result := True;
  1895. Exit;
  1896. end;
  1897. RS_EBP:
  1898. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1899. begin
  1900. Result := True;
  1901. Exit;
  1902. end;
  1903. RS_ESI:
  1904. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1905. begin
  1906. Result := True;
  1907. Exit;
  1908. end;
  1909. RS_EDI:
  1910. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1911. begin
  1912. Result := True;
  1913. Exit;
  1914. end;
  1915. else
  1916. ;
  1917. end;
  1918. end;
  1919. end;
  1920. end;
  1921. end;
  1922. end;
  1923. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1924. var
  1925. hp2,hp3 : tai;
  1926. begin
  1927. { some x86-64 issue a NOP before the real exit code }
  1928. if MatchInstruction(p,A_NOP,[]) then
  1929. GetNextInstruction(p,p);
  1930. result:=assigned(p) and (p.typ=ait_instruction) and
  1931. ((taicpu(p).opcode = A_RET) or
  1932. ((taicpu(p).opcode=A_LEAVE) and
  1933. GetNextInstruction(p,hp2) and
  1934. MatchInstruction(hp2,A_RET,[S_NO])
  1935. ) or
  1936. (((taicpu(p).opcode=A_LEA) and
  1937. MatchOpType(taicpu(p),top_ref,top_reg) and
  1938. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1939. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1940. ) and
  1941. GetNextInstruction(p,hp2) and
  1942. MatchInstruction(hp2,A_RET,[S_NO])
  1943. ) or
  1944. ((((taicpu(p).opcode=A_MOV) and
  1945. MatchOpType(taicpu(p),top_reg,top_reg) and
  1946. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1947. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1948. ((taicpu(p).opcode=A_LEA) and
  1949. MatchOpType(taicpu(p),top_ref,top_reg) and
  1950. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1951. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1952. )
  1953. ) and
  1954. GetNextInstruction(p,hp2) and
  1955. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1956. MatchOpType(taicpu(hp2),top_reg) and
  1957. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1958. GetNextInstruction(hp2,hp3) and
  1959. MatchInstruction(hp3,A_RET,[S_NO])
  1960. )
  1961. );
  1962. end;
  1963. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1964. begin
  1965. isFoldableArithOp := False;
  1966. case hp1.opcode of
  1967. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1968. isFoldableArithOp :=
  1969. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1970. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1971. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1972. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1973. (taicpu(hp1).oper[1]^.reg = reg);
  1974. A_INC,A_DEC,A_NEG,A_NOT:
  1975. isFoldableArithOp :=
  1976. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1977. (taicpu(hp1).oper[0]^.reg = reg);
  1978. else
  1979. ;
  1980. end;
  1981. end;
  1982. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1983. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1984. var
  1985. hp2: tai;
  1986. begin
  1987. hp2 := p;
  1988. repeat
  1989. hp2 := tai(hp2.previous);
  1990. if assigned(hp2) and
  1991. (hp2.typ = ait_regalloc) and
  1992. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1993. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1994. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1995. begin
  1996. RemoveInstruction(hp2);
  1997. break;
  1998. end;
  1999. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2000. end;
  2001. begin
  2002. case current_procinfo.procdef.returndef.typ of
  2003. arraydef,recorddef,pointerdef,
  2004. stringdef,enumdef,procdef,objectdef,errordef,
  2005. filedef,setdef,procvardef,
  2006. classrefdef,forwarddef:
  2007. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2008. orddef:
  2009. if current_procinfo.procdef.returndef.size <> 0 then
  2010. begin
  2011. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2012. { for int64/qword }
  2013. if current_procinfo.procdef.returndef.size = 8 then
  2014. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2015. end;
  2016. else
  2017. ;
  2018. end;
  2019. end;
  2020. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2021. var
  2022. hp1,hp2 : tai;
  2023. begin
  2024. result:=false;
  2025. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2026. begin
  2027. { vmova* reg1,reg1
  2028. =>
  2029. <nop> }
  2030. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2031. begin
  2032. RemoveCurrentP(p);
  2033. result:=true;
  2034. exit;
  2035. end;
  2036. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2037. begin
  2038. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2039. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2040. begin
  2041. { vmova* reg1,reg2
  2042. vmova* reg2,reg3
  2043. dealloc reg2
  2044. =>
  2045. vmova* reg1,reg3 }
  2046. TransferUsedRegs(TmpUsedRegs);
  2047. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2048. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2049. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2050. begin
  2051. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2052. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2053. RemoveInstruction(hp1);
  2054. result:=true;
  2055. exit;
  2056. end;
  2057. { special case:
  2058. vmova* reg1,<op>
  2059. vmova* <op>,reg1
  2060. =>
  2061. vmova* reg1,<op> }
  2062. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2063. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2064. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2065. ) then
  2066. begin
  2067. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2068. RemoveInstruction(hp1);
  2069. result:=true;
  2070. exit;
  2071. end
  2072. end
  2073. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2074. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2075. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2076. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2077. ) and
  2078. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2079. begin
  2080. { vmova* reg1,reg2
  2081. vmovs* reg2,<op>
  2082. dealloc reg2
  2083. =>
  2084. vmovs* reg1,reg3 }
  2085. TransferUsedRegs(TmpUsedRegs);
  2086. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2087. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2088. begin
  2089. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2090. taicpu(p).opcode:=taicpu(hp1).opcode;
  2091. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2092. RemoveInstruction(hp1);
  2093. result:=true;
  2094. exit;
  2095. end
  2096. end;
  2097. end;
  2098. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2099. begin
  2100. if MatchInstruction(hp1,[A_VFMADDPD,
  2101. A_VFMADD132PD,
  2102. A_VFMADD132PS,
  2103. A_VFMADD132SD,
  2104. A_VFMADD132SS,
  2105. A_VFMADD213PD,
  2106. A_VFMADD213PS,
  2107. A_VFMADD213SD,
  2108. A_VFMADD213SS,
  2109. A_VFMADD231PD,
  2110. A_VFMADD231PS,
  2111. A_VFMADD231SD,
  2112. A_VFMADD231SS,
  2113. A_VFMADDSUB132PD,
  2114. A_VFMADDSUB132PS,
  2115. A_VFMADDSUB213PD,
  2116. A_VFMADDSUB213PS,
  2117. A_VFMADDSUB231PD,
  2118. A_VFMADDSUB231PS,
  2119. A_VFMSUB132PD,
  2120. A_VFMSUB132PS,
  2121. A_VFMSUB132SD,
  2122. A_VFMSUB132SS,
  2123. A_VFMSUB213PD,
  2124. A_VFMSUB213PS,
  2125. A_VFMSUB213SD,
  2126. A_VFMSUB213SS,
  2127. A_VFMSUB231PD,
  2128. A_VFMSUB231PS,
  2129. A_VFMSUB231SD,
  2130. A_VFMSUB231SS,
  2131. A_VFMSUBADD132PD,
  2132. A_VFMSUBADD132PS,
  2133. A_VFMSUBADD213PD,
  2134. A_VFMSUBADD213PS,
  2135. A_VFMSUBADD231PD,
  2136. A_VFMSUBADD231PS,
  2137. A_VFNMADD132PD,
  2138. A_VFNMADD132PS,
  2139. A_VFNMADD132SD,
  2140. A_VFNMADD132SS,
  2141. A_VFNMADD213PD,
  2142. A_VFNMADD213PS,
  2143. A_VFNMADD213SD,
  2144. A_VFNMADD213SS,
  2145. A_VFNMADD231PD,
  2146. A_VFNMADD231PS,
  2147. A_VFNMADD231SD,
  2148. A_VFNMADD231SS,
  2149. A_VFNMSUB132PD,
  2150. A_VFNMSUB132PS,
  2151. A_VFNMSUB132SD,
  2152. A_VFNMSUB132SS,
  2153. A_VFNMSUB213PD,
  2154. A_VFNMSUB213PS,
  2155. A_VFNMSUB213SD,
  2156. A_VFNMSUB213SS,
  2157. A_VFNMSUB231PD,
  2158. A_VFNMSUB231PS,
  2159. A_VFNMSUB231SD,
  2160. A_VFNMSUB231SS],[S_NO]) and
  2161. { we mix single and double opperations here because we assume that the compiler
  2162. generates vmovapd only after double operations and vmovaps only after single operations }
  2163. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2164. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2165. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2166. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2167. begin
  2168. TransferUsedRegs(TmpUsedRegs);
  2169. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2170. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2171. begin
  2172. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2173. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2174. RemoveCurrentP(p)
  2175. else
  2176. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2177. RemoveInstruction(hp2);
  2178. end;
  2179. end
  2180. else if (hp1.typ = ait_instruction) and
  2181. (((taicpu(p).opcode=A_MOVAPS) and
  2182. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2183. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2184. ((taicpu(p).opcode=A_MOVAPD) and
  2185. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2186. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2187. ) and
  2188. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2189. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2190. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2191. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2192. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2193. { change
  2194. movapX reg,reg2
  2195. addsX/subsX/... reg3, reg2
  2196. movapX reg2,reg
  2197. to
  2198. addsX/subsX/... reg3,reg
  2199. }
  2200. begin
  2201. TransferUsedRegs(TmpUsedRegs);
  2202. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2203. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2204. begin
  2205. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2206. debug_op2str(taicpu(p).opcode)+' '+
  2207. debug_op2str(taicpu(hp1).opcode)+' '+
  2208. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2209. { we cannot eliminate the first move if
  2210. the operations uses the same register for source and dest }
  2211. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2212. { Remember that hp1 is not necessarily the immediate
  2213. next instruction }
  2214. RemoveCurrentP(p);
  2215. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2216. RemoveInstruction(hp2);
  2217. result:=true;
  2218. end;
  2219. end
  2220. else if (hp1.typ = ait_instruction) and
  2221. (((taicpu(p).opcode=A_VMOVAPD) and
  2222. (taicpu(hp1).opcode=A_VCOMISD)) or
  2223. ((taicpu(p).opcode=A_VMOVAPS) and
  2224. ((taicpu(hp1).opcode=A_VCOMISS))
  2225. )
  2226. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2227. { change
  2228. movapX reg,reg1
  2229. vcomisX reg1,reg1
  2230. to
  2231. vcomisX reg,reg
  2232. }
  2233. begin
  2234. TransferUsedRegs(TmpUsedRegs);
  2235. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2236. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2237. begin
  2238. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2239. debug_op2str(taicpu(p).opcode)+' '+
  2240. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2241. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2242. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2243. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2244. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2245. RemoveCurrentP(p);
  2246. result:=true;
  2247. exit;
  2248. end;
  2249. end
  2250. end;
  2251. end;
  2252. end;
  2253. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2254. var
  2255. hp1 : tai;
  2256. begin
  2257. result:=false;
  2258. { replace
  2259. V<Op>X %mreg1,%mreg2,%mreg3
  2260. VMovX %mreg3,%mreg4
  2261. dealloc %mreg3
  2262. by
  2263. V<Op>X %mreg1,%mreg2,%mreg4
  2264. ?
  2265. }
  2266. if GetNextInstruction(p,hp1) and
  2267. { we mix single and double operations here because we assume that the compiler
  2268. generates vmovapd only after double operations and vmovaps only after single operations }
  2269. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2270. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2271. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2272. begin
  2273. TransferUsedRegs(TmpUsedRegs);
  2274. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2275. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2276. begin
  2277. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2278. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2279. RemoveInstruction(hp1);
  2280. result:=true;
  2281. end;
  2282. end;
  2283. end;
  2284. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2285. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2286. begin
  2287. Result := False;
  2288. { For safety reasons, only check for exact register matches }
  2289. { Check base register }
  2290. if (ref.base = AOldReg) then
  2291. begin
  2292. ref.base := ANewReg;
  2293. Result := True;
  2294. end;
  2295. { Check index register }
  2296. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2297. begin
  2298. ref.index := ANewReg;
  2299. Result := True;
  2300. end;
  2301. end;
  2302. { Replaces all references to AOldReg in an operand to ANewReg }
  2303. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2304. var
  2305. OldSupReg, NewSupReg: TSuperRegister;
  2306. OldSubReg, NewSubReg: TSubRegister;
  2307. OldRegType: TRegisterType;
  2308. ThisOper: POper;
  2309. begin
  2310. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2311. Result := False;
  2312. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2313. InternalError(2020011801);
  2314. OldSupReg := getsupreg(AOldReg);
  2315. OldSubReg := getsubreg(AOldReg);
  2316. OldRegType := getregtype(AOldReg);
  2317. NewSupReg := getsupreg(ANewReg);
  2318. NewSubReg := getsubreg(ANewReg);
  2319. if OldRegType <> getregtype(ANewReg) then
  2320. InternalError(2020011802);
  2321. if OldSubReg <> NewSubReg then
  2322. InternalError(2020011803);
  2323. case ThisOper^.typ of
  2324. top_reg:
  2325. if (
  2326. (ThisOper^.reg = AOldReg) or
  2327. (
  2328. (OldRegType = R_INTREGISTER) and
  2329. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2330. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2331. (
  2332. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2333. {$ifndef x86_64}
  2334. and (
  2335. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2336. don't have an 8-bit representation }
  2337. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2338. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2339. )
  2340. {$endif x86_64}
  2341. )
  2342. )
  2343. ) then
  2344. begin
  2345. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2346. Result := True;
  2347. end;
  2348. top_ref:
  2349. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2350. Result := True;
  2351. else
  2352. ;
  2353. end;
  2354. end;
  2355. { Replaces all references to AOldReg in an instruction to ANewReg }
  2356. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2357. const
  2358. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2359. var
  2360. OperIdx: Integer;
  2361. begin
  2362. Result := False;
  2363. for OperIdx := 0 to p.ops - 1 do
  2364. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2365. begin
  2366. { The shift and rotate instructions can only use CL }
  2367. if not (
  2368. (OperIdx = 0) and
  2369. { This second condition just helps to avoid unnecessarily
  2370. calling MatchInstruction for 10 different opcodes }
  2371. (p.oper[0]^.reg = NR_CL) and
  2372. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2373. ) then
  2374. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2375. end
  2376. else if p.oper[OperIdx]^.typ = top_ref then
  2377. { It's okay to replace registers in references that get written to }
  2378. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2379. end;
  2380. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2381. begin
  2382. Result :=
  2383. (ref^.index = NR_NO) and
  2384. (
  2385. {$ifdef x86_64}
  2386. (
  2387. (ref^.base = NR_RIP) and
  2388. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2389. ) or
  2390. {$endif x86_64}
  2391. (ref^.refaddr = addr_full) or
  2392. (ref^.base = NR_STACK_POINTER_REG) or
  2393. (ref^.base = current_procinfo.framepointer)
  2394. );
  2395. end;
  2396. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2397. var
  2398. l: asizeint;
  2399. begin
  2400. Result := False;
  2401. { Should have been checked previously }
  2402. if p.opcode <> A_LEA then
  2403. InternalError(2020072501);
  2404. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2405. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2406. not(cs_opt_size in current_settings.optimizerswitches) then
  2407. exit;
  2408. with p.oper[0]^.ref^ do
  2409. begin
  2410. if (base <> p.oper[1]^.reg) or
  2411. (index <> NR_NO) or
  2412. assigned(symbol) then
  2413. exit;
  2414. l:=offset;
  2415. if (l=1) and UseIncDec then
  2416. begin
  2417. p.opcode:=A_INC;
  2418. p.loadreg(0,p.oper[1]^.reg);
  2419. p.ops:=1;
  2420. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2421. end
  2422. else if (l=-1) and UseIncDec then
  2423. begin
  2424. p.opcode:=A_DEC;
  2425. p.loadreg(0,p.oper[1]^.reg);
  2426. p.ops:=1;
  2427. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2428. end
  2429. else
  2430. begin
  2431. if (l<0) and (l<>-2147483648) then
  2432. begin
  2433. p.opcode:=A_SUB;
  2434. p.loadConst(0,-l);
  2435. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2436. end
  2437. else
  2438. begin
  2439. p.opcode:=A_ADD;
  2440. p.loadConst(0,l);
  2441. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2442. end;
  2443. end;
  2444. end;
  2445. Result := True;
  2446. end;
  2447. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2448. var
  2449. CurrentReg, ReplaceReg: TRegister;
  2450. begin
  2451. Result := False;
  2452. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2453. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2454. case hp.opcode of
  2455. A_FSTSW, A_FNSTSW,
  2456. A_IN, A_INS, A_OUT, A_OUTS,
  2457. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2458. { These routines have explicit operands, but they are restricted in
  2459. what they can be (e.g. IN and OUT can only read from AL, AX or
  2460. EAX. }
  2461. Exit;
  2462. A_IMUL:
  2463. begin
  2464. { The 1-operand version writes to implicit registers
  2465. The 2-operand version reads from the first operator, and reads
  2466. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2467. the 3-operand version reads from a register that it doesn't write to
  2468. }
  2469. case hp.ops of
  2470. 1:
  2471. if (
  2472. (
  2473. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2474. ) or
  2475. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2476. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2477. begin
  2478. Result := True;
  2479. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2480. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2481. end;
  2482. 2:
  2483. { Only modify the first parameter }
  2484. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2485. begin
  2486. Result := True;
  2487. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2488. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2489. end;
  2490. 3:
  2491. { Only modify the second parameter }
  2492. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2493. begin
  2494. Result := True;
  2495. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2496. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2497. end;
  2498. else
  2499. InternalError(2020012901);
  2500. end;
  2501. end;
  2502. else
  2503. if (hp.ops > 0) and
  2504. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2505. begin
  2506. Result := True;
  2507. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2508. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2509. end;
  2510. end;
  2511. end;
  2512. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2513. var
  2514. hp2: tai;
  2515. p_SourceReg, p_TargetReg: TRegister;
  2516. begin
  2517. Result := False;
  2518. { Backward optimisation. If we have:
  2519. func. %reg1,%reg2
  2520. mov %reg2,%reg3
  2521. (dealloc %reg2)
  2522. Change to:
  2523. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2524. Perform similar optimisations with 1, 3 and 4-operand instructions
  2525. that only have one output.
  2526. }
  2527. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2528. begin
  2529. p_SourceReg := taicpu(p).oper[0]^.reg;
  2530. p_TargetReg := taicpu(p).oper[1]^.reg;
  2531. TransferUsedRegs(TmpUsedRegs);
  2532. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2533. GetLastInstruction(p, hp2) and
  2534. (hp2.typ = ait_instruction) and
  2535. { Have to make sure it's an instruction that only reads from
  2536. the first operands and only writes (not reads or modifies) to
  2537. the last one; in essence, a pure function such as BSR, POPCNT
  2538. or ANDN }
  2539. (
  2540. (
  2541. (taicpu(hp2).ops = 1) and
  2542. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2543. ) or
  2544. (
  2545. (taicpu(hp2).ops = 2) and
  2546. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2547. ) or
  2548. (
  2549. (taicpu(hp2).ops = 3) and
  2550. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2551. ) or
  2552. (
  2553. (taicpu(hp2).ops = 4) and
  2554. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2555. )
  2556. ) and
  2557. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2558. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2559. begin
  2560. case taicpu(hp2).opcode of
  2561. A_FSTSW, A_FNSTSW,
  2562. A_IN, A_INS, A_OUT, A_OUTS,
  2563. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2564. { These routines have explicit operands, but they are restricted in
  2565. what they can be (e.g. IN and OUT can only read from AL, AX or
  2566. EAX. }
  2567. ;
  2568. else
  2569. begin
  2570. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2571. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2572. if not RegInInstruction(p_TargetReg, hp2) then
  2573. begin
  2574. { Since we're allocating from an earlier point, we
  2575. need to remove the register from the tracking }
  2576. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2577. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2578. end;
  2579. RemoveCurrentp(p, hp1);
  2580. { If the Func was another MOV instruction, we might get
  2581. "mov %reg,%reg" that doesn't get removed in Pass 2
  2582. otherwise, so deal with it here (also do something
  2583. similar with lea (%reg),%reg}
  2584. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2585. begin
  2586. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2587. if p = hp2 then
  2588. RemoveCurrentp(p)
  2589. else
  2590. RemoveInstruction(hp2);
  2591. end;
  2592. Result := True;
  2593. Exit;
  2594. end;
  2595. end;
  2596. end;
  2597. end;
  2598. end;
  2599. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2600. var
  2601. hp1, hp2, hp3: tai;
  2602. DoOptimisation, TempBool: Boolean;
  2603. {$ifdef x86_64}
  2604. NewConst: TCGInt;
  2605. {$endif x86_64}
  2606. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2607. begin
  2608. if taicpu(hp1).opcode = signed_movop then
  2609. begin
  2610. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2611. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2612. end
  2613. else
  2614. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2615. end;
  2616. function TryConstMerge(var p1, p2: tai): Boolean;
  2617. var
  2618. ThisRef: TReference;
  2619. begin
  2620. Result := False;
  2621. ThisRef := taicpu(p2).oper[1]^.ref^;
  2622. { Only permit writes to the stack, since we can guarantee alignment with that }
  2623. if (ThisRef.index = NR_NO) and
  2624. (
  2625. (ThisRef.base = NR_STACK_POINTER_REG) or
  2626. (ThisRef.base = current_procinfo.framepointer)
  2627. ) then
  2628. begin
  2629. case taicpu(p).opsize of
  2630. S_B:
  2631. begin
  2632. { Word writes must be on a 2-byte boundary }
  2633. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2634. begin
  2635. { Reduce offset of second reference to see if it is sequential with the first }
  2636. Dec(ThisRef.offset, 1);
  2637. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2638. begin
  2639. { Make sure the constants aren't represented as a
  2640. negative number, as these won't merge properly }
  2641. taicpu(p1).opsize := S_W;
  2642. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2643. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2644. RemoveInstruction(p2);
  2645. Result := True;
  2646. end;
  2647. end;
  2648. end;
  2649. S_W:
  2650. begin
  2651. { Longword writes must be on a 4-byte boundary }
  2652. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2653. begin
  2654. { Reduce offset of second reference to see if it is sequential with the first }
  2655. Dec(ThisRef.offset, 2);
  2656. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2657. begin
  2658. { Make sure the constants aren't represented as a
  2659. negative number, as these won't merge properly }
  2660. taicpu(p1).opsize := S_L;
  2661. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2662. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2663. RemoveInstruction(p2);
  2664. Result := True;
  2665. end;
  2666. end;
  2667. end;
  2668. {$ifdef x86_64}
  2669. S_L:
  2670. begin
  2671. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2672. see if the constants can be encoded this way. }
  2673. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2674. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2675. { Quadword writes must be on an 8-byte boundary }
  2676. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2677. begin
  2678. { Reduce offset of second reference to see if it is sequential with the first }
  2679. Dec(ThisRef.offset, 4);
  2680. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2681. begin
  2682. { Make sure the constants aren't represented as a
  2683. negative number, as these won't merge properly }
  2684. taicpu(p1).opsize := S_Q;
  2685. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2686. taicpu(p1).oper[0]^.val := NewConst;
  2687. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2688. RemoveInstruction(p2);
  2689. Result := True;
  2690. end;
  2691. end;
  2692. end;
  2693. {$endif x86_64}
  2694. else
  2695. ;
  2696. end;
  2697. end;
  2698. end;
  2699. var
  2700. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2701. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2702. NewSize: topsize; NewOffset: asizeint;
  2703. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2704. SourceRef, TargetRef: TReference;
  2705. MovAligned, MovUnaligned: TAsmOp;
  2706. ThisRef: TReference;
  2707. JumpTracking: TLinkedList;
  2708. begin
  2709. Result:=false;
  2710. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2711. { remove mov reg1,reg1? }
  2712. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2713. then
  2714. begin
  2715. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2716. { take care of the register (de)allocs following p }
  2717. RemoveCurrentP(p, hp1);
  2718. Result:=true;
  2719. exit;
  2720. end;
  2721. { All the next optimisations require a next instruction }
  2722. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2723. Exit;
  2724. { Prevent compiler warnings }
  2725. p_TargetReg := NR_NO;
  2726. if taicpu(p).oper[1]^.typ = top_reg then
  2727. begin
  2728. { Saves on a large number of dereferences }
  2729. p_TargetReg := taicpu(p).oper[1]^.reg;
  2730. { Look for:
  2731. mov %reg1,%reg2
  2732. ??? %reg2,r/m
  2733. Change to:
  2734. mov %reg1,%reg2
  2735. ??? %reg1,r/m
  2736. }
  2737. if taicpu(p).oper[0]^.typ = top_reg then
  2738. begin
  2739. if RegReadByInstruction(p_TargetReg, hp1) and
  2740. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2741. begin
  2742. { A change has occurred, just not in p }
  2743. Result := True;
  2744. TransferUsedRegs(TmpUsedRegs);
  2745. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2746. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2747. { Just in case something didn't get modified (e.g. an
  2748. implicit register) }
  2749. not RegReadByInstruction(p_TargetReg, hp1) then
  2750. begin
  2751. { We can remove the original MOV }
  2752. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2753. RemoveCurrentp(p, hp1);
  2754. { UsedRegs got updated by RemoveCurrentp }
  2755. Result := True;
  2756. Exit;
  2757. end;
  2758. { If we know a MOV instruction has become a null operation, we might as well
  2759. get rid of it now to save time. }
  2760. if (taicpu(hp1).opcode = A_MOV) and
  2761. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2762. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2763. { Just being a register is enough to confirm it's a null operation }
  2764. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2765. begin
  2766. Result := True;
  2767. { Speed-up to reduce a pipeline stall... if we had something like...
  2768. movl %eax,%edx
  2769. movw %dx,%ax
  2770. ... the second instruction would change to movw %ax,%ax, but
  2771. given that it is now %ax that's active rather than %eax,
  2772. penalties might occur due to a partial register write, so instead,
  2773. change it to a MOVZX instruction when optimising for speed.
  2774. }
  2775. if not (cs_opt_size in current_settings.optimizerswitches) and
  2776. IsMOVZXAcceptable and
  2777. (taicpu(hp1).opsize < taicpu(p).opsize)
  2778. {$ifdef x86_64}
  2779. { operations already implicitly set the upper 64 bits to zero }
  2780. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2781. {$endif x86_64}
  2782. then
  2783. begin
  2784. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2785. case taicpu(p).opsize of
  2786. S_W:
  2787. if taicpu(hp1).opsize = S_B then
  2788. taicpu(hp1).opsize := S_BL
  2789. else
  2790. InternalError(2020012911);
  2791. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2792. case taicpu(hp1).opsize of
  2793. S_B:
  2794. taicpu(hp1).opsize := S_BL;
  2795. S_W:
  2796. taicpu(hp1).opsize := S_WL;
  2797. else
  2798. InternalError(2020012912);
  2799. end;
  2800. else
  2801. InternalError(2020012910);
  2802. end;
  2803. taicpu(hp1).opcode := A_MOVZX;
  2804. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2805. end
  2806. else
  2807. begin
  2808. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2809. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2810. RemoveInstruction(hp1);
  2811. { The instruction after what was hp1 is now the immediate next instruction,
  2812. so we can continue to make optimisations if it's present }
  2813. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2814. Exit;
  2815. hp1 := hp2;
  2816. end;
  2817. end;
  2818. end;
  2819. end;
  2820. end;
  2821. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2822. overwrites the original destination register. e.g.
  2823. movl ###,%reg2d
  2824. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2825. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2826. }
  2827. if (taicpu(p).oper[1]^.typ = top_reg) and
  2828. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2829. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2830. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2831. begin
  2832. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2833. begin
  2834. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2835. case taicpu(p).oper[0]^.typ of
  2836. top_const:
  2837. { We have something like:
  2838. movb $x, %regb
  2839. movzbl %regb,%regd
  2840. Change to:
  2841. movl $x, %regd
  2842. }
  2843. begin
  2844. case taicpu(hp1).opsize of
  2845. S_BW:
  2846. begin
  2847. convert_mov_value(A_MOVSX, $FF);
  2848. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2849. taicpu(p).opsize := S_W;
  2850. end;
  2851. S_BL:
  2852. begin
  2853. convert_mov_value(A_MOVSX, $FF);
  2854. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2855. taicpu(p).opsize := S_L;
  2856. end;
  2857. S_WL:
  2858. begin
  2859. convert_mov_value(A_MOVSX, $FFFF);
  2860. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2861. taicpu(p).opsize := S_L;
  2862. end;
  2863. {$ifdef x86_64}
  2864. S_BQ:
  2865. begin
  2866. convert_mov_value(A_MOVSX, $FF);
  2867. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2868. taicpu(p).opsize := S_Q;
  2869. end;
  2870. S_WQ:
  2871. begin
  2872. convert_mov_value(A_MOVSX, $FFFF);
  2873. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2874. taicpu(p).opsize := S_Q;
  2875. end;
  2876. S_LQ:
  2877. begin
  2878. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2879. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2880. taicpu(p).opsize := S_Q;
  2881. end;
  2882. {$endif x86_64}
  2883. else
  2884. { If hp1 was a MOV instruction, it should have been
  2885. optimised already }
  2886. InternalError(2020021001);
  2887. end;
  2888. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2889. RemoveInstruction(hp1);
  2890. Result := True;
  2891. Exit;
  2892. end;
  2893. top_ref:
  2894. begin
  2895. { We have something like:
  2896. movb mem, %regb
  2897. movzbl %regb,%regd
  2898. Change to:
  2899. movzbl mem, %regd
  2900. }
  2901. ThisRef := taicpu(p).oper[0]^.ref^;
  2902. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2903. begin
  2904. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2905. taicpu(hp1).loadref(0, ThisRef);
  2906. { Make sure any registers in the references are properly tracked }
  2907. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2908. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2909. if (ThisRef.index <> NR_NO) then
  2910. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2911. RemoveCurrentP(p, hp1);
  2912. Result := True;
  2913. Exit;
  2914. end;
  2915. end;
  2916. else
  2917. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2918. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2919. Exit;
  2920. end;
  2921. end
  2922. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2923. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2924. optimised }
  2925. else
  2926. begin
  2927. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2928. RemoveCurrentP(p, hp1);
  2929. Result := True;
  2930. Exit;
  2931. end;
  2932. end;
  2933. if (taicpu(hp1).opcode = A_AND) and
  2934. (taicpu(p).oper[1]^.typ = top_reg) and
  2935. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2936. begin
  2937. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2938. begin
  2939. case taicpu(p).opsize of
  2940. S_L:
  2941. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2942. begin
  2943. { Optimize out:
  2944. mov x, %reg
  2945. and ffffffffh, %reg
  2946. }
  2947. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2948. RemoveInstruction(hp1);
  2949. Result:=true;
  2950. exit;
  2951. end;
  2952. S_Q: { TODO: Confirm if this is even possible }
  2953. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2954. begin
  2955. { Optimize out:
  2956. mov x, %reg
  2957. and ffffffffffffffffh, %reg
  2958. }
  2959. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2960. RemoveInstruction(hp1);
  2961. Result:=true;
  2962. exit;
  2963. end;
  2964. else
  2965. ;
  2966. end;
  2967. if (
  2968. (taicpu(p).oper[0]^.typ=top_reg) or
  2969. (
  2970. (taicpu(p).oper[0]^.typ=top_ref) and
  2971. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2972. )
  2973. ) and
  2974. GetNextInstruction(hp1,hp2) and
  2975. MatchInstruction(hp2,A_TEST,[]) and
  2976. (
  2977. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2978. (
  2979. { If the register being tested is smaller than the one
  2980. that received a bitwise AND, permit it if the constant
  2981. fits into the smaller size }
  2982. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2983. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2984. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2985. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2986. (
  2987. (
  2988. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2989. (taicpu(hp1).oper[0]^.val <= $FF)
  2990. ) or
  2991. (
  2992. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2993. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2994. {$ifdef x86_64}
  2995. ) or
  2996. (
  2997. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2998. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2999. {$endif x86_64}
  3000. )
  3001. )
  3002. )
  3003. ) and
  3004. (
  3005. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3006. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3007. ) and
  3008. GetNextInstruction(hp2,hp3) and
  3009. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3010. (taicpu(hp3).condition in [C_E,C_NE]) then
  3011. begin
  3012. TransferUsedRegs(TmpUsedRegs);
  3013. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3014. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3015. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3016. begin
  3017. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3018. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3019. taicpu(hp1).opcode:=A_TEST;
  3020. { Shrink the TEST instruction down to the smallest possible size }
  3021. case taicpu(hp1).oper[0]^.val of
  3022. 0..255:
  3023. if (taicpu(hp1).opsize <> S_B)
  3024. {$ifndef x86_64}
  3025. and (
  3026. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3027. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3028. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3029. )
  3030. {$endif x86_64}
  3031. then
  3032. begin
  3033. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3034. { Only print debug message if the TEST instruction
  3035. is a different size before and after }
  3036. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3037. taicpu(hp1).opsize := S_B;
  3038. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3039. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3040. end;
  3041. 256..65535:
  3042. if (taicpu(hp1).opsize <> S_W) then
  3043. begin
  3044. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3045. { Only print debug message if the TEST instruction
  3046. is a different size before and after }
  3047. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3048. taicpu(hp1).opsize := S_W;
  3049. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3050. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3051. end;
  3052. {$ifdef x86_64}
  3053. 65536..$7FFFFFFF:
  3054. if (taicpu(hp1).opsize <> S_L) then
  3055. begin
  3056. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3057. { Only print debug message if the TEST instruction
  3058. is a different size before and after }
  3059. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3060. taicpu(hp1).opsize := S_L;
  3061. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3062. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3063. end;
  3064. {$endif x86_64}
  3065. else
  3066. ;
  3067. end;
  3068. RemoveInstruction(hp2);
  3069. RemoveCurrentP(p, hp1);
  3070. Result:=true;
  3071. exit;
  3072. end;
  3073. end;
  3074. end
  3075. else if IsMOVZXAcceptable and
  3076. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3077. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3078. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3079. then
  3080. begin
  3081. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3082. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3083. case taicpu(p).opsize of
  3084. S_B:
  3085. if (taicpu(hp1).oper[0]^.val = $ff) then
  3086. begin
  3087. { Convert:
  3088. movb x, %regl movb x, %regl
  3089. andw ffh, %regw andl ffh, %regd
  3090. To:
  3091. movzbw x, %regd movzbl x, %regd
  3092. (Identical registers, just different sizes)
  3093. }
  3094. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3095. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3096. case taicpu(hp1).opsize of
  3097. S_W: NewSize := S_BW;
  3098. S_L: NewSize := S_BL;
  3099. {$ifdef x86_64}
  3100. S_Q: NewSize := S_BQ;
  3101. {$endif x86_64}
  3102. else
  3103. InternalError(2018011510);
  3104. end;
  3105. end
  3106. else
  3107. NewSize := S_NO;
  3108. S_W:
  3109. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3110. begin
  3111. { Convert:
  3112. movw x, %regw
  3113. andl ffffh, %regd
  3114. To:
  3115. movzwl x, %regd
  3116. (Identical registers, just different sizes)
  3117. }
  3118. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3119. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3120. case taicpu(hp1).opsize of
  3121. S_L: NewSize := S_WL;
  3122. {$ifdef x86_64}
  3123. S_Q: NewSize := S_WQ;
  3124. {$endif x86_64}
  3125. else
  3126. InternalError(2018011511);
  3127. end;
  3128. end
  3129. else
  3130. NewSize := S_NO;
  3131. else
  3132. NewSize := S_NO;
  3133. end;
  3134. if NewSize <> S_NO then
  3135. begin
  3136. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3137. { The actual optimization }
  3138. taicpu(p).opcode := A_MOVZX;
  3139. taicpu(p).changeopsize(NewSize);
  3140. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3141. { Safeguard if "and" is followed by a conditional command }
  3142. TransferUsedRegs(TmpUsedRegs);
  3143. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3144. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3145. begin
  3146. { At this point, the "and" command is effectively equivalent to
  3147. "test %reg,%reg". This will be handled separately by the
  3148. Peephole Optimizer. [Kit] }
  3149. DebugMsg(SPeepholeOptimization + PreMessage +
  3150. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3151. end
  3152. else
  3153. begin
  3154. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3155. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3156. RemoveInstruction(hp1);
  3157. end;
  3158. Result := True;
  3159. Exit;
  3160. end;
  3161. end;
  3162. end;
  3163. if (taicpu(hp1).opcode = A_OR) and
  3164. (taicpu(p).oper[1]^.typ = top_reg) and
  3165. MatchOperand(taicpu(p).oper[0]^, 0) and
  3166. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3167. begin
  3168. { mov 0, %reg
  3169. or ###,%reg
  3170. Change to (only if the flags are not used):
  3171. mov ###,%reg
  3172. }
  3173. TransferUsedRegs(TmpUsedRegs);
  3174. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3175. DoOptimisation := True;
  3176. { Even if the flags are used, we might be able to do the optimisation
  3177. if the conditions are predictable }
  3178. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3179. begin
  3180. { Only perform if ### = %reg (the same register) or equal to 0,
  3181. so %reg is guaranteed to still have a value of zero }
  3182. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3183. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3184. begin
  3185. hp2 := hp1;
  3186. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3187. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3188. GetNextInstruction(hp2, hp3) do
  3189. begin
  3190. { Don't continue modifying if the flags state is getting changed }
  3191. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3192. Break;
  3193. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3194. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3195. begin
  3196. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3197. begin
  3198. { Condition is always true }
  3199. case taicpu(hp3).opcode of
  3200. A_Jcc:
  3201. begin
  3202. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3203. { Check for jump shortcuts before we destroy the condition }
  3204. DoJumpOptimizations(hp3, TempBool);
  3205. MakeUnconditional(taicpu(hp3));
  3206. Result := True;
  3207. end;
  3208. A_CMOVcc:
  3209. begin
  3210. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3211. taicpu(hp3).opcode := A_MOV;
  3212. taicpu(hp3).condition := C_None;
  3213. Result := True;
  3214. end;
  3215. A_SETcc:
  3216. begin
  3217. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3218. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3219. taicpu(hp3).opcode := A_MOV;
  3220. taicpu(hp3).ops := 2;
  3221. taicpu(hp3).condition := C_None;
  3222. taicpu(hp3).opsize := S_B;
  3223. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3224. taicpu(hp3).loadconst(0, 1);
  3225. Result := True;
  3226. end;
  3227. else
  3228. InternalError(2021090701);
  3229. end;
  3230. end
  3231. 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
  3232. begin
  3233. { Condition is always false }
  3234. case taicpu(hp3).opcode of
  3235. A_Jcc:
  3236. begin
  3237. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3238. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3239. RemoveInstruction(hp3);
  3240. Result := True;
  3241. { Since hp3 was deleted, hp2 must not be updated }
  3242. Continue;
  3243. end;
  3244. A_CMOVcc:
  3245. begin
  3246. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3247. RemoveInstruction(hp3);
  3248. Result := True;
  3249. { Since hp3 was deleted, hp2 must not be updated }
  3250. Continue;
  3251. end;
  3252. A_SETcc:
  3253. begin
  3254. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3255. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3256. taicpu(hp3).opcode := A_MOV;
  3257. taicpu(hp3).ops := 2;
  3258. taicpu(hp3).condition := C_None;
  3259. taicpu(hp3).opsize := S_B;
  3260. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3261. taicpu(hp3).loadconst(0, 0);
  3262. Result := True;
  3263. end;
  3264. else
  3265. InternalError(2021090702);
  3266. end;
  3267. end
  3268. else
  3269. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3270. DoOptimisation := False;
  3271. end;
  3272. hp2 := hp3;
  3273. end;
  3274. { Flags are still in use - don't optimise }
  3275. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3276. DoOptimisation := False;
  3277. end
  3278. else
  3279. DoOptimisation := False;
  3280. end;
  3281. if DoOptimisation then
  3282. begin
  3283. {$ifdef x86_64}
  3284. { OR only supports 32-bit sign-extended constants for 64-bit
  3285. instructions, so compensate for this if the constant is
  3286. encoded as a value greater than or equal to 2^31 }
  3287. if (taicpu(hp1).opsize = S_Q) and
  3288. (taicpu(hp1).oper[0]^.typ = top_const) and
  3289. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3290. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3291. {$endif x86_64}
  3292. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3293. taicpu(hp1).opcode := A_MOV;
  3294. RemoveCurrentP(p, hp1);
  3295. Result := True;
  3296. Exit;
  3297. end;
  3298. end;
  3299. { Next instruction is also a MOV ? }
  3300. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3301. begin
  3302. if MatchOpType(taicpu(p), top_const, top_ref) and
  3303. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3304. TryConstMerge(p, hp1) then
  3305. begin
  3306. Result := True;
  3307. { In case we have four byte writes in a row, check for 2 more
  3308. right now so we don't have to wait for another iteration of
  3309. pass 1
  3310. }
  3311. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3312. case taicpu(p).opsize of
  3313. S_W:
  3314. begin
  3315. if GetNextInstruction(p, hp1) and
  3316. MatchInstruction(hp1, A_MOV, [S_B]) and
  3317. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3318. GetNextInstruction(hp1, hp2) and
  3319. MatchInstruction(hp2, A_MOV, [S_B]) and
  3320. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3321. { Try to merge the two bytes }
  3322. TryConstMerge(hp1, hp2) then
  3323. { Now try to merge the two words (hp2 will get deleted) }
  3324. TryConstMerge(p, hp1);
  3325. end;
  3326. S_L:
  3327. begin
  3328. { Though this only really benefits x86_64 and not i386, it
  3329. gets a potential optimisation done faster and hence
  3330. reduces the number of times OptPass1MOV is entered }
  3331. if GetNextInstruction(p, hp1) and
  3332. MatchInstruction(hp1, A_MOV, [S_W]) and
  3333. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3334. GetNextInstruction(hp1, hp2) and
  3335. MatchInstruction(hp2, A_MOV, [S_W]) and
  3336. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3337. { Try to merge the two words }
  3338. TryConstMerge(hp1, hp2) then
  3339. { This will always fail on i386, so don't bother
  3340. calling it unless we're doing x86_64 }
  3341. {$ifdef x86_64}
  3342. { Now try to merge the two longwords (hp2 will get deleted) }
  3343. TryConstMerge(p, hp1)
  3344. {$endif x86_64}
  3345. ;
  3346. end;
  3347. else
  3348. ;
  3349. end;
  3350. Exit;
  3351. end;
  3352. if (taicpu(p).oper[1]^.typ = top_reg) and
  3353. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3354. begin
  3355. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3356. TransferUsedRegs(TmpUsedRegs);
  3357. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3358. { we have
  3359. mov x, %treg
  3360. mov %treg, y
  3361. }
  3362. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3363. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3364. { we've got
  3365. mov x, %treg
  3366. mov %treg, y
  3367. with %treg is not used after }
  3368. case taicpu(p).oper[0]^.typ Of
  3369. { top_reg is covered by DeepMOVOpt }
  3370. top_const:
  3371. begin
  3372. { change
  3373. mov const, %treg
  3374. mov %treg, y
  3375. to
  3376. mov const, y
  3377. }
  3378. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3379. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3380. begin
  3381. if taicpu(hp1).oper[1]^.typ=top_reg then
  3382. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3383. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3384. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3385. RemoveInstruction(hp1);
  3386. Result:=true;
  3387. Exit;
  3388. end;
  3389. end;
  3390. top_ref:
  3391. case taicpu(hp1).oper[1]^.typ of
  3392. top_reg:
  3393. begin
  3394. { change
  3395. mov mem, %treg
  3396. mov %treg, %reg
  3397. to
  3398. mov mem, %reg"
  3399. }
  3400. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3401. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3402. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3403. RemoveInstruction(hp1);
  3404. Result:=true;
  3405. Exit;
  3406. end;
  3407. top_ref:
  3408. begin
  3409. {$ifdef x86_64}
  3410. { Look for the following to simplify:
  3411. mov x(mem1), %reg
  3412. mov %reg, y(mem2)
  3413. mov x+8(mem1), %reg
  3414. mov %reg, y+8(mem2)
  3415. Change to:
  3416. movdqu x(mem1), %xmmreg
  3417. movdqu %xmmreg, y(mem2)
  3418. ...but only as long as the memory blocks don't overlap
  3419. }
  3420. SourceRef := taicpu(p).oper[0]^.ref^;
  3421. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3422. if (taicpu(p).opsize = S_Q) and
  3423. GetNextInstruction(hp1, hp2) and
  3424. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3425. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3426. begin
  3427. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3428. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3429. Inc(SourceRef.offset, 8);
  3430. if UseAVX then
  3431. begin
  3432. MovAligned := A_VMOVDQA;
  3433. MovUnaligned := A_VMOVDQU;
  3434. end
  3435. else
  3436. begin
  3437. MovAligned := A_MOVDQA;
  3438. MovUnaligned := A_MOVDQU;
  3439. end;
  3440. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3441. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3442. begin
  3443. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3444. Inc(TargetRef.offset, 8);
  3445. if GetNextInstruction(hp2, hp3) and
  3446. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3447. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3448. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3449. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3450. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3451. begin
  3452. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3453. if NewMMReg <> NR_NO then
  3454. begin
  3455. { Remember that the offsets are 8 ahead }
  3456. if ((SourceRef.offset mod 16) = 8) and
  3457. (
  3458. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3459. (SourceRef.base = current_procinfo.framepointer) or
  3460. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3461. ) then
  3462. taicpu(p).opcode := MovAligned
  3463. else
  3464. taicpu(p).opcode := MovUnaligned;
  3465. taicpu(p).opsize := S_XMM;
  3466. taicpu(p).oper[1]^.reg := NewMMReg;
  3467. if ((TargetRef.offset mod 16) = 8) and
  3468. (
  3469. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3470. (TargetRef.base = current_procinfo.framepointer) or
  3471. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3472. ) then
  3473. taicpu(hp1).opcode := MovAligned
  3474. else
  3475. taicpu(hp1).opcode := MovUnaligned;
  3476. taicpu(hp1).opsize := S_XMM;
  3477. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3478. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3479. RemoveInstruction(hp2);
  3480. RemoveInstruction(hp3);
  3481. Result := True;
  3482. Exit;
  3483. end;
  3484. end;
  3485. end
  3486. else
  3487. begin
  3488. { See if the next references are 8 less rather than 8 greater }
  3489. Dec(SourceRef.offset, 16); { -8 the other way }
  3490. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3491. begin
  3492. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3493. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3494. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3495. GetNextInstruction(hp2, hp3) and
  3496. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3497. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3498. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3499. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3500. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3501. begin
  3502. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3503. if NewMMReg <> NR_NO then
  3504. begin
  3505. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3506. if ((SourceRef.offset mod 16) = 0) and
  3507. (
  3508. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3509. (SourceRef.base = current_procinfo.framepointer) or
  3510. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3511. ) then
  3512. taicpu(hp2).opcode := MovAligned
  3513. else
  3514. taicpu(hp2).opcode := MovUnaligned;
  3515. taicpu(hp2).opsize := S_XMM;
  3516. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3517. if ((TargetRef.offset mod 16) = 0) and
  3518. (
  3519. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3520. (TargetRef.base = current_procinfo.framepointer) or
  3521. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3522. ) then
  3523. taicpu(hp3).opcode := MovAligned
  3524. else
  3525. taicpu(hp3).opcode := MovUnaligned;
  3526. taicpu(hp3).opsize := S_XMM;
  3527. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3528. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3529. RemoveInstruction(hp1);
  3530. RemoveCurrentP(p, hp2);
  3531. Result := True;
  3532. Exit;
  3533. end;
  3534. end;
  3535. end;
  3536. end;
  3537. end;
  3538. {$endif x86_64}
  3539. end;
  3540. else
  3541. { The write target should be a reg or a ref }
  3542. InternalError(2021091601);
  3543. end;
  3544. else
  3545. ;
  3546. end
  3547. else
  3548. { %treg is used afterwards, but all eventualities
  3549. other than the first MOV instruction being a constant
  3550. are covered by DeepMOVOpt, so only check for that }
  3551. if (taicpu(p).oper[0]^.typ = top_const) and
  3552. (
  3553. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3554. not (cs_opt_size in current_settings.optimizerswitches) or
  3555. (taicpu(hp1).opsize = S_B)
  3556. ) and
  3557. (
  3558. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3559. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3560. ) then
  3561. begin
  3562. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3563. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3564. end;
  3565. end;
  3566. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3567. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3568. { mov reg1, mem1 or mov mem1, reg1
  3569. mov mem2, reg2 mov reg2, mem2}
  3570. begin
  3571. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3572. { mov reg1, mem1 or mov mem1, reg1
  3573. mov mem2, reg1 mov reg2, mem1}
  3574. begin
  3575. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3576. { Removes the second statement from
  3577. mov reg1, mem1/reg2
  3578. mov mem1/reg2, reg1 }
  3579. begin
  3580. if taicpu(p).oper[0]^.typ=top_reg then
  3581. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3582. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3583. RemoveInstruction(hp1);
  3584. Result:=true;
  3585. exit;
  3586. end
  3587. else
  3588. begin
  3589. TransferUsedRegs(TmpUsedRegs);
  3590. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3591. if (taicpu(p).oper[1]^.typ = top_ref) and
  3592. { mov reg1, mem1
  3593. mov mem2, reg1 }
  3594. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3595. GetNextInstruction(hp1, hp2) and
  3596. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3597. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3598. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3599. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3600. { change to
  3601. mov reg1, mem1 mov reg1, mem1
  3602. mov mem2, reg1 cmp reg1, mem2
  3603. cmp mem1, reg1
  3604. }
  3605. begin
  3606. RemoveInstruction(hp2);
  3607. taicpu(hp1).opcode := A_CMP;
  3608. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3609. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3610. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3611. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3612. end;
  3613. end;
  3614. end
  3615. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3616. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3617. begin
  3618. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3619. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3620. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3621. end
  3622. else
  3623. begin
  3624. TransferUsedRegs(TmpUsedRegs);
  3625. if GetNextInstruction(hp1, hp2) and
  3626. MatchOpType(taicpu(p),top_ref,top_reg) and
  3627. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3628. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3629. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3630. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3631. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3632. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3633. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3634. { mov mem1, %reg1
  3635. mov %reg1, mem2
  3636. mov mem2, reg2
  3637. to:
  3638. mov mem1, reg2
  3639. mov reg2, mem2}
  3640. begin
  3641. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3642. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3643. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3644. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3645. RemoveInstruction(hp2);
  3646. Result := True;
  3647. end
  3648. {$ifdef i386}
  3649. { this is enabled for i386 only, as the rules to create the reg sets below
  3650. are too complicated for x86-64, so this makes this code too error prone
  3651. on x86-64
  3652. }
  3653. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3654. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3655. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3656. { mov mem1, reg1 mov mem1, reg1
  3657. mov reg1, mem2 mov reg1, mem2
  3658. mov mem2, reg2 mov mem2, reg1
  3659. to: to:
  3660. mov mem1, reg1 mov mem1, reg1
  3661. mov mem1, reg2 mov reg1, mem2
  3662. mov reg1, mem2
  3663. or (if mem1 depends on reg1
  3664. and/or if mem2 depends on reg2)
  3665. to:
  3666. mov mem1, reg1
  3667. mov reg1, mem2
  3668. mov reg1, reg2
  3669. }
  3670. begin
  3671. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3672. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3673. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3674. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3675. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3676. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3677. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3678. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3679. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3680. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3681. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3682. end
  3683. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3684. begin
  3685. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3686. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3687. end
  3688. else
  3689. begin
  3690. RemoveInstruction(hp2);
  3691. end
  3692. {$endif i386}
  3693. ;
  3694. end;
  3695. end
  3696. { movl [mem1],reg1
  3697. movl [mem1],reg2
  3698. to
  3699. movl [mem1],reg1
  3700. movl reg1,reg2
  3701. }
  3702. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3703. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3704. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3705. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3706. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3707. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3708. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3709. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3710. begin
  3711. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3712. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3713. end;
  3714. { movl const1,[mem1]
  3715. movl [mem1],reg1
  3716. to
  3717. movl const1,reg1
  3718. movl reg1,[mem1]
  3719. }
  3720. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3721. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3722. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3723. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3724. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3725. begin
  3726. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3727. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3728. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3729. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3730. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3731. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3732. Result:=true;
  3733. exit;
  3734. end;
  3735. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3736. { Change:
  3737. movl %reg1,%reg2
  3738. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3739. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3740. To:
  3741. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3742. movl x(%reg1),%reg1
  3743. movl %reg1,%regX
  3744. }
  3745. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3746. begin
  3747. p_SourceReg := taicpu(p).oper[0]^.reg;
  3748. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3749. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3750. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3751. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3752. GetNextInstruction(hp1, hp2) and
  3753. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3754. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3755. begin
  3756. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3757. if RegInRef(p_TargetReg, SourceRef) and
  3758. { If %reg1 also appears in the second reference, then it will
  3759. not refer to the same memory block as the first reference }
  3760. not RegInRef(p_SourceReg, SourceRef) then
  3761. begin
  3762. { Check to see if the references match if %reg2 is changed to %reg1 }
  3763. if SourceRef.base = p_TargetReg then
  3764. SourceRef.base := p_SourceReg;
  3765. if SourceRef.index = p_TargetReg then
  3766. SourceRef.index := p_SourceReg;
  3767. { RefsEqual also checks to ensure both references are non-volatile }
  3768. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3769. begin
  3770. taicpu(hp2).loadreg(0, p_SourceReg);
  3771. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3772. Result := True;
  3773. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3774. begin
  3775. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3776. RemoveCurrentP(p, hp1);
  3777. Exit;
  3778. end
  3779. else
  3780. begin
  3781. { Check to see if %reg2 is no longer in use }
  3782. TransferUsedRegs(TmpUsedRegs);
  3783. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3784. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3785. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3786. begin
  3787. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3788. RemoveCurrentP(p, hp1);
  3789. Exit;
  3790. end;
  3791. end;
  3792. { If we reach this point, p and hp1 weren't actually modified,
  3793. so we can do a bit more work on this pass }
  3794. end;
  3795. end;
  3796. end;
  3797. end;
  3798. end;
  3799. {$ifdef x86_64}
  3800. { Change:
  3801. movl %reg1l,%reg2l
  3802. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3803. To:
  3804. movl %reg1l,%reg2l
  3805. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3806. If %reg1 = %reg3, convert to:
  3807. movl %reg1l,%reg2l
  3808. andl %reg1l,%reg1l
  3809. }
  3810. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3811. MatchOpType(taicpu(p), top_reg, top_reg) and
  3812. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3813. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3814. begin
  3815. TransferUsedRegs(TmpUsedRegs);
  3816. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3817. taicpu(hp1).opsize := S_L;
  3818. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3819. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3820. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3821. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3822. begin
  3823. { %reg1 = %reg3 }
  3824. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3825. taicpu(hp1).opcode := A_AND;
  3826. end
  3827. else
  3828. begin
  3829. { %reg1 <> %reg3 }
  3830. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3831. end;
  3832. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3833. begin
  3834. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3835. RemoveCurrentP(p, hp1);
  3836. Result := True;
  3837. Exit;
  3838. end
  3839. else
  3840. begin
  3841. { Initial instruction wasn't actually changed }
  3842. Include(OptsToCheck, aoc_ForceNewIteration);
  3843. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3844. appears below since %reg1 has technically changed }
  3845. if taicpu(hp1).opcode = A_AND then
  3846. Exit;
  3847. end;
  3848. end;
  3849. {$endif x86_64}
  3850. { search further than the next instruction for a mov (as long as it's not a jump) }
  3851. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3852. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3853. (taicpu(p).oper[1]^.typ = top_reg) and
  3854. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3855. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3856. begin
  3857. { we work with hp2 here, so hp1 can be still used later on when
  3858. checking for GetNextInstruction_p }
  3859. hp3 := hp1;
  3860. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3861. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3862. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3863. TransferUsedRegs(TmpUsedRegs);
  3864. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3865. if NotFirstIteration then
  3866. JumpTracking := TLinkedList.Create
  3867. else
  3868. JumpTracking := nil;
  3869. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3870. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3871. (hp2.typ=ait_instruction) do
  3872. begin
  3873. case taicpu(hp2).opcode of
  3874. A_POP:
  3875. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3876. begin
  3877. if not CrossJump and
  3878. not RegUsedBetween(p_TargetReg, p, hp2) then
  3879. begin
  3880. { We can remove the original MOV since the register
  3881. wasn't used between it and its popping from the stack }
  3882. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3883. RemoveCurrentp(p, hp1);
  3884. Result := True;
  3885. JumpTracking.Free;
  3886. Exit;
  3887. end;
  3888. { Can't go any further }
  3889. Break;
  3890. end;
  3891. A_MOV:
  3892. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3893. ((taicpu(p).oper[0]^.typ=top_const) or
  3894. ((taicpu(p).oper[0]^.typ=top_reg) and
  3895. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3896. )
  3897. ) then
  3898. begin
  3899. { we have
  3900. mov x, %treg
  3901. mov %treg, y
  3902. }
  3903. { We don't need to call UpdateUsedRegs for every instruction between
  3904. p and hp2 because the register we're concerned about will not
  3905. become deallocated (otherwise GetNextInstructionUsingReg would
  3906. have stopped at an earlier instruction). [Kit] }
  3907. TempRegUsed :=
  3908. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3909. RegReadByInstruction(p_TargetReg, hp3) or
  3910. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3911. case taicpu(p).oper[0]^.typ Of
  3912. top_reg:
  3913. begin
  3914. { change
  3915. mov %reg, %treg
  3916. mov %treg, y
  3917. to
  3918. mov %reg, y
  3919. }
  3920. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3921. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3922. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3923. begin
  3924. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3925. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3926. if TempRegUsed then
  3927. begin
  3928. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3929. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3930. { Set the start of the next GetNextInstructionUsingRegCond search
  3931. to start at the entry right before hp2 (which is about to be removed) }
  3932. hp3 := tai(hp2.Previous);
  3933. RemoveInstruction(hp2);
  3934. Include(OptsToCheck, aoc_ForceNewIteration);
  3935. { See if there's more we can optimise }
  3936. Continue;
  3937. end
  3938. else
  3939. begin
  3940. RemoveInstruction(hp2);
  3941. { We can remove the original MOV too }
  3942. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3943. RemoveCurrentP(p, hp1);
  3944. Result:=true;
  3945. JumpTracking.Free;
  3946. Exit;
  3947. end;
  3948. end
  3949. else
  3950. begin
  3951. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3952. taicpu(hp2).loadReg(0, p_SourceReg);
  3953. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3954. { Check to see if the register also appears in the reference }
  3955. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3956. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3957. { Don't remove the first instruction if the temporary register is in use }
  3958. if not TempRegUsed and
  3959. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3960. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3961. begin
  3962. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3963. RemoveCurrentP(p, hp1);
  3964. Result:=true;
  3965. JumpTracking.Free;
  3966. Exit;
  3967. end;
  3968. { No need to set Result to True here. If there's another instruction later
  3969. on that can be optimised, it will be detected when the main Pass 1 loop
  3970. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3971. end;
  3972. end;
  3973. top_const:
  3974. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3975. begin
  3976. { change
  3977. mov const, %treg
  3978. mov %treg, y
  3979. to
  3980. mov const, y
  3981. }
  3982. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3983. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3984. begin
  3985. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3986. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3987. if TempRegUsed then
  3988. begin
  3989. { Don't remove the first instruction if the temporary register is in use }
  3990. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3991. { No need to set Result to True. If there's another instruction later on
  3992. that can be optimised, it will be detected when the main Pass 1 loop
  3993. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3994. end
  3995. else
  3996. begin
  3997. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3998. RemoveCurrentP(p, hp1);
  3999. Result:=true;
  4000. Exit;
  4001. end;
  4002. end;
  4003. end;
  4004. else
  4005. Internalerror(2019103001);
  4006. end;
  4007. end
  4008. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4009. begin
  4010. if not CrossJump and
  4011. not RegUsedBetween(p_TargetReg, p, hp2) and
  4012. not RegReadByInstruction(p_TargetReg, hp2) then
  4013. begin
  4014. { Register is not used before it is overwritten }
  4015. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4016. RemoveCurrentp(p, hp1);
  4017. Result := True;
  4018. Exit;
  4019. end;
  4020. if (taicpu(p).oper[0]^.typ = top_const) and
  4021. (taicpu(hp2).oper[0]^.typ = top_const) then
  4022. begin
  4023. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4024. begin
  4025. { Same value - register hasn't changed }
  4026. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4027. RemoveInstruction(hp2);
  4028. Include(OptsToCheck, aoc_ForceNewIteration);
  4029. { See if there's more we can optimise }
  4030. Continue;
  4031. end;
  4032. end;
  4033. {$ifdef x86_64}
  4034. end
  4035. { Change:
  4036. movl %reg1l,%reg2l
  4037. ...
  4038. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4039. To:
  4040. movl %reg1l,%reg2l
  4041. ...
  4042. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4043. If %reg1 = %reg3, convert to:
  4044. movl %reg1l,%reg2l
  4045. ...
  4046. andl %reg1l,%reg1l
  4047. }
  4048. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4049. (taicpu(p).oper[0]^.typ = top_reg) and
  4050. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4051. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4052. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4053. begin
  4054. TempRegUsed :=
  4055. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4056. RegReadByInstruction(p_TargetReg, hp3) or
  4057. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4058. taicpu(hp2).opsize := S_L;
  4059. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4060. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4061. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4062. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4063. begin
  4064. { %reg1 = %reg3 }
  4065. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4066. taicpu(hp2).opcode := A_AND;
  4067. end
  4068. else
  4069. begin
  4070. { %reg1 <> %reg3 }
  4071. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4072. end;
  4073. if not TempRegUsed then
  4074. begin
  4075. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4076. RemoveCurrentP(p, hp1);
  4077. Result := True;
  4078. Exit;
  4079. end
  4080. else
  4081. begin
  4082. { Initial instruction wasn't actually changed }
  4083. Include(OptsToCheck, aoc_ForceNewIteration);
  4084. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4085. appears below since %reg1 has technically changed }
  4086. if taicpu(hp2).opcode = A_AND then
  4087. Break;
  4088. end;
  4089. {$endif x86_64}
  4090. end;
  4091. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4092. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4093. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4094. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4095. begin
  4096. {
  4097. Change from:
  4098. mov ###, %reg
  4099. ...
  4100. movs/z %reg,%reg (Same register, just different sizes)
  4101. To:
  4102. movs/z ###, %reg (Longer version)
  4103. ...
  4104. (remove)
  4105. }
  4106. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4107. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4108. { Keep the first instruction as mov if ### is a constant }
  4109. if taicpu(p).oper[0]^.typ = top_const then
  4110. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4111. else
  4112. begin
  4113. taicpu(p).opcode := taicpu(hp2).opcode;
  4114. taicpu(p).opsize := taicpu(hp2).opsize;
  4115. end;
  4116. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4117. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4118. RemoveInstruction(hp2);
  4119. Result := True;
  4120. JumpTracking.Free;
  4121. Exit;
  4122. end;
  4123. else
  4124. { Move down to the if-block below };
  4125. end;
  4126. { Also catches MOV/S/Z instructions that aren't modified }
  4127. if taicpu(p).oper[0]^.typ = top_reg then
  4128. begin
  4129. p_SourceReg := taicpu(p).oper[0]^.reg;
  4130. if
  4131. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4132. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4133. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4134. begin
  4135. Result := True;
  4136. { Just in case something didn't get modified (e.g. an
  4137. implicit register). Also, if it does read from this
  4138. register, then there's no longer an advantage to
  4139. changing the register on subsequent instructions.}
  4140. if not RegReadByInstruction(p_TargetReg, hp2) then
  4141. begin
  4142. { If a conditional jump was crossed, do not delete
  4143. the original MOV no matter what }
  4144. if not CrossJump and
  4145. { RegEndOfLife returns True if the register is
  4146. deallocated before the next instruction or has
  4147. been loaded with a new value }
  4148. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4149. begin
  4150. { We can remove the original MOV }
  4151. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4152. RemoveCurrentp(p, hp1);
  4153. JumpTracking.Free;
  4154. Result := True;
  4155. Exit;
  4156. end;
  4157. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4158. begin
  4159. { See if there's more we can optimise }
  4160. hp3 := hp2;
  4161. Continue;
  4162. end;
  4163. end;
  4164. end;
  4165. end;
  4166. { Break out of the while loop under normal circumstances }
  4167. Break;
  4168. end;
  4169. JumpTracking.Free;
  4170. end;
  4171. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4172. (taicpu(p).oper[1]^.typ = top_reg) and
  4173. (taicpu(p).opsize = S_L) and
  4174. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4175. (hp2.typ = ait_instruction) and
  4176. (taicpu(hp2).opcode = A_AND) and
  4177. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4178. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4179. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4180. ) then
  4181. begin
  4182. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4183. begin
  4184. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4185. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4186. begin
  4187. { Optimize out:
  4188. mov x, %reg
  4189. and ffffffffh, %reg
  4190. }
  4191. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4192. RemoveInstruction(hp2);
  4193. Result:=true;
  4194. exit;
  4195. end;
  4196. end;
  4197. end;
  4198. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4199. x >= RetOffset) as it doesn't do anything (it writes either to a
  4200. parameter or to the temporary storage room for the function
  4201. result)
  4202. }
  4203. if IsExitCode(hp1) and
  4204. (taicpu(p).oper[1]^.typ = top_ref) and
  4205. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4206. (
  4207. (
  4208. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4209. not (
  4210. assigned(current_procinfo.procdef.funcretsym) and
  4211. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4212. )
  4213. ) or
  4214. { Also discard writes to the stack that are below the base pointer,
  4215. as this is temporary storage rather than a function result on the
  4216. stack, say. }
  4217. (
  4218. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4219. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4220. )
  4221. ) then
  4222. begin
  4223. RemoveCurrentp(p, hp1);
  4224. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4225. RemoveLastDeallocForFuncRes(p);
  4226. Result:=true;
  4227. exit;
  4228. end;
  4229. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4230. begin
  4231. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4232. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4233. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4234. begin
  4235. { change
  4236. mov reg1, mem1
  4237. test/cmp x, mem1
  4238. to
  4239. mov reg1, mem1
  4240. test/cmp x, reg1
  4241. }
  4242. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4243. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4244. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4245. Result := True;
  4246. Exit;
  4247. end;
  4248. if DoMovCmpMemOpt(p, hp1) then
  4249. begin
  4250. Result := True;
  4251. Exit;
  4252. end;
  4253. end;
  4254. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4255. { If the flags register is in use, don't change the instruction to an
  4256. ADD otherwise this will scramble the flags. [Kit] }
  4257. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4258. begin
  4259. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4260. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4261. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4262. ) or
  4263. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4264. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4265. )
  4266. ) then
  4267. { mov reg1,ref
  4268. lea reg2,[reg1,reg2]
  4269. to
  4270. add reg2,ref}
  4271. begin
  4272. TransferUsedRegs(TmpUsedRegs);
  4273. { reg1 may not be used afterwards }
  4274. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4275. begin
  4276. Taicpu(hp1).opcode:=A_ADD;
  4277. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4278. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4279. RemoveCurrentp(p, hp1);
  4280. result:=true;
  4281. exit;
  4282. end;
  4283. end;
  4284. { If the LEA instruction can be converted into an arithmetic instruction,
  4285. it may be possible to then fold it in the next optimisation, otherwise
  4286. there's nothing more that can be optimised here. }
  4287. if not ConvertLEA(taicpu(hp1)) then
  4288. Exit;
  4289. end;
  4290. if (taicpu(p).oper[1]^.typ = top_reg) and
  4291. (hp1.typ = ait_instruction) and
  4292. GetNextInstruction(hp1, hp2) and
  4293. MatchInstruction(hp2,A_MOV,[]) and
  4294. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4295. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4296. (
  4297. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4298. {$ifdef x86_64}
  4299. or
  4300. (
  4301. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4302. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4303. )
  4304. {$endif x86_64}
  4305. ) then
  4306. begin
  4307. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4308. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4309. { change movsX/movzX reg/ref, reg2
  4310. add/sub/or/... reg3/$const, reg2
  4311. mov reg2 reg/ref
  4312. dealloc reg2
  4313. to
  4314. add/sub/or/... reg3/$const, reg/ref }
  4315. begin
  4316. TransferUsedRegs(TmpUsedRegs);
  4317. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4318. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4319. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4320. begin
  4321. { by example:
  4322. movswl %si,%eax movswl %si,%eax p
  4323. decl %eax addl %edx,%eax hp1
  4324. movw %ax,%si movw %ax,%si hp2
  4325. ->
  4326. movswl %si,%eax movswl %si,%eax p
  4327. decw %eax addw %edx,%eax hp1
  4328. movw %ax,%si movw %ax,%si hp2
  4329. }
  4330. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4331. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4332. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4333. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4334. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4335. {
  4336. ->
  4337. movswl %si,%eax movswl %si,%eax p
  4338. decw %si addw %dx,%si hp1
  4339. movw %ax,%si movw %ax,%si hp2
  4340. }
  4341. case taicpu(hp1).ops of
  4342. 1:
  4343. begin
  4344. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4345. if taicpu(hp1).oper[0]^.typ=top_reg then
  4346. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4347. end;
  4348. 2:
  4349. begin
  4350. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4351. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4352. (taicpu(hp1).opcode<>A_SHL) and
  4353. (taicpu(hp1).opcode<>A_SHR) and
  4354. (taicpu(hp1).opcode<>A_SAR) then
  4355. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4356. end;
  4357. else
  4358. internalerror(2008042701);
  4359. end;
  4360. {
  4361. ->
  4362. decw %si addw %dx,%si p
  4363. }
  4364. RemoveInstruction(hp2);
  4365. RemoveCurrentP(p, hp1);
  4366. Result:=True;
  4367. Exit;
  4368. end;
  4369. end;
  4370. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4371. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4372. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4373. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4374. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4375. )
  4376. {$ifdef i386}
  4377. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4378. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4379. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4380. {$endif i386}
  4381. then
  4382. { change movsX/movzX reg/ref, reg2
  4383. add/sub/or/... regX/$const, reg2
  4384. mov reg2, reg3
  4385. dealloc reg2
  4386. to
  4387. movsX/movzX reg/ref, reg3
  4388. add/sub/or/... reg3/$const, reg3
  4389. }
  4390. begin
  4391. TransferUsedRegs(TmpUsedRegs);
  4392. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4393. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4394. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4395. begin
  4396. { by example:
  4397. movswl %si,%eax movswl %si,%eax p
  4398. decl %eax addl %edx,%eax hp1
  4399. movw %ax,%si movw %ax,%si hp2
  4400. ->
  4401. movswl %si,%eax movswl %si,%eax p
  4402. decw %eax addw %edx,%eax hp1
  4403. movw %ax,%si movw %ax,%si hp2
  4404. }
  4405. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4406. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4407. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4408. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4409. { limit size of constants as well to avoid assembler errors, but
  4410. check opsize to avoid overflow when left shifting the 1 }
  4411. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4412. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4413. {$ifdef x86_64}
  4414. { Be careful of, for example:
  4415. movl %reg1,%reg2
  4416. addl %reg3,%reg2
  4417. movq %reg2,%reg4
  4418. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4419. }
  4420. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4421. begin
  4422. taicpu(hp2).changeopsize(S_L);
  4423. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4424. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4425. end;
  4426. {$endif x86_64}
  4427. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4428. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4429. if taicpu(p).oper[0]^.typ=top_reg then
  4430. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4431. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4432. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4433. {
  4434. ->
  4435. movswl %si,%eax movswl %si,%eax p
  4436. decw %si addw %dx,%si hp1
  4437. movw %ax,%si movw %ax,%si hp2
  4438. }
  4439. case taicpu(hp1).ops of
  4440. 1:
  4441. begin
  4442. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4443. if taicpu(hp1).oper[0]^.typ=top_reg then
  4444. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4445. end;
  4446. 2:
  4447. begin
  4448. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4449. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4450. (taicpu(hp1).opcode<>A_SHL) and
  4451. (taicpu(hp1).opcode<>A_SHR) and
  4452. (taicpu(hp1).opcode<>A_SAR) then
  4453. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4454. end;
  4455. else
  4456. internalerror(2018111801);
  4457. end;
  4458. {
  4459. ->
  4460. decw %si addw %dx,%si p
  4461. }
  4462. RemoveInstruction(hp2);
  4463. end;
  4464. end;
  4465. end;
  4466. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4467. GetNextInstruction(hp1, hp2) and
  4468. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4469. MatchOperand(Taicpu(p).oper[0]^,0) and
  4470. (Taicpu(p).oper[1]^.typ = top_reg) and
  4471. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4472. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4473. { mov reg1,0
  4474. bts reg1,operand1 --> mov reg1,operand2
  4475. or reg1,operand2 bts reg1,operand1}
  4476. begin
  4477. Taicpu(hp2).opcode:=A_MOV;
  4478. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4479. asml.remove(hp1);
  4480. insertllitem(hp2,hp2.next,hp1);
  4481. RemoveCurrentp(p, hp1);
  4482. Result:=true;
  4483. exit;
  4484. end;
  4485. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4486. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4487. GetNextInstruction(hp1, hp2) and
  4488. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4489. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4490. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4491. { change
  4492. mov reg1,reg2
  4493. sub reg3,reg2
  4494. cmp reg3,reg1
  4495. into
  4496. mov reg1,reg2
  4497. sub reg3,reg2
  4498. }
  4499. begin
  4500. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4501. RemoveInstruction(hp2);
  4502. Result:=true;
  4503. exit;
  4504. end;
  4505. {
  4506. mov ref,reg0
  4507. <op> reg0,reg1
  4508. dealloc reg0
  4509. to
  4510. <op> ref,reg1
  4511. }
  4512. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4513. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4514. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4515. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4516. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4517. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4518. begin
  4519. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4520. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4521. RemoveCurrentp(p, hp1);
  4522. Result:=true;
  4523. exit;
  4524. end;
  4525. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4526. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4527. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4528. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4529. begin
  4530. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4531. {$ifdef x86_64}
  4532. { Convert:
  4533. movq x(ref),%reg64
  4534. shrq y,%reg64
  4535. To:
  4536. movl x+4(ref),%reg32
  4537. shrl y-32,%reg32 (Remove if y = 32)
  4538. }
  4539. if (taicpu(p).opsize = S_Q) and
  4540. (taicpu(hp1).opcode = A_SHR) and
  4541. (taicpu(hp1).oper[0]^.val >= 32) then
  4542. begin
  4543. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4544. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4545. { Convert to 32-bit }
  4546. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4547. taicpu(p).opsize := S_L;
  4548. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4549. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4550. if (taicpu(hp1).oper[0]^.val = 32) then
  4551. begin
  4552. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4553. RemoveInstruction(hp1);
  4554. end
  4555. else
  4556. begin
  4557. { This will potentially open up more arithmetic operations since
  4558. the peephole optimizer now has a big hint that only the lower
  4559. 32 bits are currently in use (and opcodes are smaller in size) }
  4560. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4561. taicpu(hp1).opsize := S_L;
  4562. Dec(taicpu(hp1).oper[0]^.val, 32);
  4563. DebugMsg(SPeepholeOptimization + PreMessage +
  4564. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4565. end;
  4566. Result := True;
  4567. Exit;
  4568. end;
  4569. {$endif x86_64}
  4570. { Convert:
  4571. movl x(ref),%reg
  4572. shrl $24,%reg
  4573. To:
  4574. movzbl x+3(ref),%reg
  4575. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4576. Also accept sar instead of shr, but convert to movsx instead of movzx
  4577. }
  4578. if taicpu(hp1).opcode = A_SHR then
  4579. MovUnaligned := A_MOVZX
  4580. else
  4581. MovUnaligned := A_MOVSX;
  4582. NewSize := S_NO;
  4583. NewOffset := 0;
  4584. case taicpu(p).opsize of
  4585. S_B:
  4586. { No valid combinations };
  4587. S_W:
  4588. if (taicpu(hp1).oper[0]^.val = 8) then
  4589. begin
  4590. NewSize := S_BW;
  4591. NewOffset := 1;
  4592. end;
  4593. S_L:
  4594. case taicpu(hp1).oper[0]^.val of
  4595. 16:
  4596. begin
  4597. NewSize := S_WL;
  4598. NewOffset := 2;
  4599. end;
  4600. 24:
  4601. begin
  4602. NewSize := S_BL;
  4603. NewOffset := 3;
  4604. end;
  4605. else
  4606. ;
  4607. end;
  4608. {$ifdef x86_64}
  4609. S_Q:
  4610. case taicpu(hp1).oper[0]^.val of
  4611. 32:
  4612. begin
  4613. if taicpu(hp1).opcode = A_SAR then
  4614. begin
  4615. { 32-bit to 64-bit is a distinct instruction }
  4616. MovUnaligned := A_MOVSXD;
  4617. NewSize := S_LQ;
  4618. NewOffset := 4;
  4619. end
  4620. else
  4621. { Should have been handled by MovShr2Mov above }
  4622. InternalError(2022081811);
  4623. end;
  4624. 48:
  4625. begin
  4626. NewSize := S_WQ;
  4627. NewOffset := 6;
  4628. end;
  4629. 56:
  4630. begin
  4631. NewSize := S_BQ;
  4632. NewOffset := 7;
  4633. end;
  4634. else
  4635. ;
  4636. end;
  4637. {$endif x86_64}
  4638. else
  4639. InternalError(2022081810);
  4640. end;
  4641. if (NewSize <> S_NO) and
  4642. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4643. begin
  4644. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4645. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4646. debug_op2str(MovUnaligned);
  4647. {$ifdef x86_64}
  4648. if MovUnaligned <> A_MOVSXD then
  4649. { Don't add size suffix for MOVSXD }
  4650. {$endif x86_64}
  4651. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4652. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4653. taicpu(p).opcode := MovUnaligned;
  4654. taicpu(p).opsize := NewSize;
  4655. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4656. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4657. RemoveInstruction(hp1);
  4658. Result := True;
  4659. Exit;
  4660. end;
  4661. end;
  4662. { Backward optimisation shared with OptPass2MOV }
  4663. if FuncMov2Func(p, hp1) then
  4664. begin
  4665. Result := True;
  4666. Exit;
  4667. end;
  4668. end;
  4669. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4670. var
  4671. hp1 : tai;
  4672. begin
  4673. Result:=false;
  4674. if taicpu(p).ops <> 2 then
  4675. exit;
  4676. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4677. GetNextInstruction(p,hp1) then
  4678. begin
  4679. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4680. (taicpu(hp1).ops = 2) then
  4681. begin
  4682. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4683. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4684. { movXX reg1, mem1 or movXX mem1, reg1
  4685. movXX mem2, reg2 movXX reg2, mem2}
  4686. begin
  4687. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4688. { movXX reg1, mem1 or movXX mem1, reg1
  4689. movXX mem2, reg1 movXX reg2, mem1}
  4690. begin
  4691. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4692. begin
  4693. { Removes the second statement from
  4694. movXX reg1, mem1/reg2
  4695. movXX mem1/reg2, reg1
  4696. }
  4697. if taicpu(p).oper[0]^.typ=top_reg then
  4698. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4699. { Removes the second statement from
  4700. movXX mem1/reg1, reg2
  4701. movXX reg2, mem1/reg1
  4702. }
  4703. if (taicpu(p).oper[1]^.typ=top_reg) and
  4704. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4705. begin
  4706. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4707. RemoveInstruction(hp1);
  4708. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4709. Result:=true;
  4710. exit;
  4711. end
  4712. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4713. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4714. begin
  4715. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4716. RemoveInstruction(hp1);
  4717. Result:=true;
  4718. exit;
  4719. end;
  4720. end
  4721. end;
  4722. end;
  4723. end;
  4724. end;
  4725. end;
  4726. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4727. var
  4728. hp1 : tai;
  4729. begin
  4730. result:=false;
  4731. { replace
  4732. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4733. MovX %mreg2,%mreg1
  4734. dealloc %mreg2
  4735. by
  4736. <Op>X %mreg2,%mreg1
  4737. ?
  4738. }
  4739. if GetNextInstruction(p,hp1) and
  4740. { we mix single and double opperations here because we assume that the compiler
  4741. generates vmovapd only after double operations and vmovaps only after single operations }
  4742. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4743. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4744. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4745. (taicpu(p).oper[0]^.typ=top_reg) then
  4746. begin
  4747. TransferUsedRegs(TmpUsedRegs);
  4748. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4749. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4750. begin
  4751. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4752. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4753. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4754. RemoveInstruction(hp1);
  4755. result:=true;
  4756. end;
  4757. end;
  4758. end;
  4759. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4760. var
  4761. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4762. JumpLabel, JumpLabel_dist: TAsmLabel;
  4763. FirstValue, SecondValue: TCGInt;
  4764. TempBool: Boolean;
  4765. begin
  4766. Result := False;
  4767. if (taicpu(p).oper[0]^.typ = top_const) and
  4768. (taicpu(p).oper[0]^.val <> -1) then
  4769. begin
  4770. { Convert unsigned maximum constants to -1 to aid optimisation }
  4771. case taicpu(p).opsize of
  4772. S_B:
  4773. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4774. begin
  4775. taicpu(p).oper[0]^.val := -1;
  4776. Result := True;
  4777. Exit;
  4778. end;
  4779. S_W:
  4780. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4781. begin
  4782. taicpu(p).oper[0]^.val := -1;
  4783. Result := True;
  4784. Exit;
  4785. end;
  4786. S_L:
  4787. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4788. begin
  4789. taicpu(p).oper[0]^.val := -1;
  4790. Result := True;
  4791. Exit;
  4792. end;
  4793. {$ifdef x86_64}
  4794. S_Q:
  4795. { Storing anything greater than $7FFFFFFF is not possible so do
  4796. nothing };
  4797. {$endif x86_64}
  4798. else
  4799. InternalError(2021121001);
  4800. end;
  4801. end;
  4802. if GetNextInstruction(p, hp1) and
  4803. TrySwapMovCmp(p, hp1) then
  4804. begin
  4805. Result := True;
  4806. Exit;
  4807. end;
  4808. if MatchInstruction(hp1, A_Jcc, []) then
  4809. begin
  4810. TempBool := True;
  4811. if DoJumpOptimizations(hp1, TempBool) or
  4812. not TempBool then
  4813. begin
  4814. Result := True;
  4815. if Assigned(hp1) then
  4816. begin
  4817. if (hp1.typ in [ait_align]) then
  4818. SkipAligns(hp1, hp1);
  4819. { CollapseZeroDistJump will be set to the label after the
  4820. jump if it optimises, whether or not it's live or dead }
  4821. if (hp1.typ in [ait_label]) and
  4822. not (tai_label(hp1).labsym.is_used) then
  4823. GetNextInstruction(hp1, hp1);
  4824. end;
  4825. TransferUsedRegs(TmpUsedRegs);
  4826. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4827. if not Assigned(hp1) or
  4828. (
  4829. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4830. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4831. ) then
  4832. begin
  4833. { No more conditional jumps; conditional statement is no longer required }
  4834. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4835. RemoveCurrentP(p);
  4836. end;
  4837. Exit;
  4838. end;
  4839. end;
  4840. { Search for:
  4841. test $x,(reg/ref)
  4842. jne @lbl1
  4843. ...
  4844. test $y,(reg/ref) (same register or reference)
  4845. jne @lbl1
  4846. Change to:
  4847. test $(x or y),(reg/ref)
  4848. jne @lbl1
  4849. (Note, this doesn't work with je instead of jne)
  4850. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4851. Also search for:
  4852. test $x,(reg/ref)
  4853. je @lbl1
  4854. ...
  4855. test $y,(reg/ref)
  4856. je/jne @lbl2
  4857. If (x or y) = x, then the second jump is deterministic
  4858. }
  4859. if (
  4860. (
  4861. (taicpu(p).oper[0]^.typ = top_const) or
  4862. (
  4863. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4864. (taicpu(p).oper[0]^.typ = top_reg) and
  4865. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4866. )
  4867. ) and
  4868. MatchInstruction(hp1, A_JCC, [])
  4869. ) then
  4870. begin
  4871. if (taicpu(p).oper[0]^.typ = top_reg) and
  4872. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4873. FirstValue := -1
  4874. else
  4875. FirstValue := taicpu(p).oper[0]^.val;
  4876. { If we have several test/jne's in a row, it might be the case that
  4877. the second label doesn't go to the same location, but the one
  4878. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4879. so accommodate for this with a while loop.
  4880. }
  4881. hp1_last := hp1;
  4882. while (
  4883. (
  4884. (taicpu(p).oper[1]^.typ = top_reg) and
  4885. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  4886. ) or GetNextInstruction(hp1_last, p_dist)
  4887. ) and (p_dist.typ = ait_instruction) do
  4888. begin
  4889. if (
  4890. (
  4891. (taicpu(p_dist).opcode = A_TEST) and
  4892. (
  4893. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4894. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4895. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4896. )
  4897. ) or
  4898. (
  4899. { cmp 0,%reg = test %reg,%reg }
  4900. (taicpu(p_dist).opcode = A_CMP) and
  4901. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4902. )
  4903. ) and
  4904. { Make sure the destination operands are actually the same }
  4905. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4906. GetNextInstruction(p_dist, hp1_dist) and
  4907. MatchInstruction(hp1_dist, A_JCC, []) then
  4908. begin
  4909. if
  4910. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4911. (
  4912. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4913. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4914. ) then
  4915. SecondValue := -1
  4916. else
  4917. SecondValue := taicpu(p_dist).oper[0]^.val;
  4918. { If both of the TEST constants are identical, delete the
  4919. second TEST that is unnecessary (be careful though, just
  4920. in case the flags are modified in between) }
  4921. if (FirstValue = SecondValue) then
  4922. begin
  4923. { We have to check the entire range }
  4924. TempBool := not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist);
  4925. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4926. begin
  4927. { Since the second jump's condition is a subset of the first, we
  4928. know it will never branch because the first jump dominates it.
  4929. Get it out of the way now rather than wait for the jump
  4930. optimisations for a speed boost. }
  4931. if IsJumpToLabel(taicpu(hp1_dist)) then
  4932. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4933. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4934. RemoveInstruction(hp1_dist);
  4935. Result := True;
  4936. end
  4937. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4938. begin
  4939. { If the inverse of the first condition is a subset of the second,
  4940. the second one will definitely branch if the first one doesn't }
  4941. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4942. { We can remove the TEST instruction too }
  4943. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4944. RemoveInstruction(p_dist);
  4945. MakeUnconditional(taicpu(hp1_dist));
  4946. RemoveDeadCodeAfterJump(hp1_dist);
  4947. { Since the jump is now unconditional, we can't
  4948. continue any further with this particular
  4949. optimisation. The original TEST is still intact
  4950. though, so there might be something else we can
  4951. do }
  4952. Include(OptsToCheck, aoc_ForceNewIteration);
  4953. Break;
  4954. end;
  4955. if Result or
  4956. { If a jump wasn't removed or made unconditional, only
  4957. remove the identical TEST instruction if the flags
  4958. weren't modified }
  4959. TempBool then
  4960. begin
  4961. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4962. RemoveInstruction(p_dist);
  4963. { If the jump was removed or made unconditional, we
  4964. don't need to allocate NR_DEFAULTFLAGS over the
  4965. entire range }
  4966. if not Result then
  4967. begin
  4968. { Mark the flags as 'in use' over the entire range }
  4969. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4970. { Speed gain - continue search from the Jcc instruction }
  4971. hp1_last := hp1_dist;
  4972. { Only the TEST instruction was removed, and the
  4973. original was unchanged, so we can safely do
  4974. another iteration of the while loop }
  4975. Include(OptsToCheck, aoc_ForceNewIteration);
  4976. Continue;
  4977. end;
  4978. Exit;
  4979. end;
  4980. end;
  4981. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4982. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4983. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4984. then the second jump will never branch, so it can also be
  4985. removed regardless of where it goes }
  4986. (
  4987. (FirstValue = -1) or
  4988. (SecondValue = -1) or
  4989. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4990. ) then
  4991. begin
  4992. { Same jump location... can be a register since nothing's changed }
  4993. { If any of the entries are equivalent to test %reg,%reg, then the
  4994. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4995. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4996. if IsJumpToLabel(taicpu(hp1_dist)) then
  4997. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4998. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4999. RemoveInstruction(hp1_dist);
  5000. { Only remove the second test if no jumps or other conditional instructions follow }
  5001. TransferUsedRegs(TmpUsedRegs);
  5002. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5003. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5004. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  5005. RemoveInstruction(p_dist);
  5006. Result := True;
  5007. Exit;
  5008. end;
  5009. end;
  5010. if { If -O2 and under, it may stop on any old instruction }
  5011. (cs_opt_level3 in current_settings.optimizerswitches) and
  5012. (taicpu(p).oper[1]^.typ = top_reg) and
  5013. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5014. begin
  5015. hp1_last := p_dist;
  5016. Continue;
  5017. end;
  5018. Break;
  5019. end;
  5020. end;
  5021. { Search for:
  5022. test %reg,%reg
  5023. j(c1) @lbl1
  5024. ...
  5025. @lbl:
  5026. test %reg,%reg (same register)
  5027. j(c2) @lbl2
  5028. If c2 is a subset of c1, change to:
  5029. test %reg,%reg
  5030. j(c1) @lbl2
  5031. (@lbl1 may become a dead label as a result)
  5032. }
  5033. if (taicpu(p).oper[1]^.typ = top_reg) and
  5034. (taicpu(p).oper[0]^.typ = top_reg) and
  5035. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5036. MatchInstruction(hp1, A_JCC, []) and
  5037. IsJumpToLabel(taicpu(hp1)) then
  5038. begin
  5039. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5040. p_label := nil;
  5041. if Assigned(JumpLabel) then
  5042. p_label := getlabelwithsym(JumpLabel);
  5043. if Assigned(p_label) and
  5044. GetNextInstruction(p_label, p_dist) and
  5045. MatchInstruction(p_dist, A_TEST, []) and
  5046. { It's fine if the second test uses smaller sub-registers }
  5047. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5048. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5049. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5050. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5051. GetNextInstruction(p_dist, hp1_dist) and
  5052. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5053. begin
  5054. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5055. if JumpLabel = JumpLabel_dist then
  5056. { This is an infinite loop }
  5057. Exit;
  5058. { Best optimisation when the first condition is a subset (or equal) of the second }
  5059. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5060. begin
  5061. { Any registers used here will already be allocated }
  5062. if Assigned(JumpLabel) then
  5063. JumpLabel.DecRefs;
  5064. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5065. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5066. Result := True;
  5067. Exit;
  5068. end;
  5069. end;
  5070. end;
  5071. end;
  5072. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5073. var
  5074. hp1, hp2: tai;
  5075. ActiveReg: TRegister;
  5076. OldOffset: asizeint;
  5077. ThisConst: TCGInt;
  5078. function RegDeallocated: Boolean;
  5079. begin
  5080. TransferUsedRegs(TmpUsedRegs);
  5081. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5082. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5083. end;
  5084. begin
  5085. result:=false;
  5086. hp1 := nil;
  5087. { replace
  5088. addX const,%reg1
  5089. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5090. dealloc %reg1
  5091. by
  5092. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5093. }
  5094. if MatchOpType(taicpu(p),top_const,top_reg) then
  5095. begin
  5096. ActiveReg := taicpu(p).oper[1]^.reg;
  5097. { Ensures the entire register was updated }
  5098. if (taicpu(p).opsize >= S_L) and
  5099. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5100. MatchInstruction(hp1,A_LEA,[]) and
  5101. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5102. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5103. (
  5104. { Cover the case where the register in the reference is also the destination register }
  5105. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5106. (
  5107. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5108. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5109. RegDeallocated
  5110. )
  5111. ) then
  5112. begin
  5113. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5114. {$push}
  5115. {$R-}{$Q-}
  5116. { Explicitly disable overflow checking for these offset calculation
  5117. as those do not matter for the final result }
  5118. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5119. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5120. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5121. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5122. {$pop}
  5123. {$ifdef x86_64}
  5124. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5125. begin
  5126. { Overflow; abort }
  5127. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5128. end
  5129. else
  5130. {$endif x86_64}
  5131. begin
  5132. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5133. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5134. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5135. RemoveCurrentP(p, hp1)
  5136. else
  5137. RemoveCurrentP(p);
  5138. result:=true;
  5139. Exit;
  5140. end;
  5141. end;
  5142. if (
  5143. { Save calling GetNextInstructionUsingReg again }
  5144. Assigned(hp1) or
  5145. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5146. ) and
  5147. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5148. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5149. begin
  5150. if taicpu(hp1).oper[0]^.typ = top_const then
  5151. begin
  5152. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5153. if taicpu(hp1).opcode = A_ADD then
  5154. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5155. else
  5156. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5157. Result := True;
  5158. { Handle any overflows }
  5159. case taicpu(p).opsize of
  5160. S_B:
  5161. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5162. S_W:
  5163. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5164. S_L:
  5165. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5166. {$ifdef x86_64}
  5167. S_Q:
  5168. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5169. { Overflow; abort }
  5170. Result := False
  5171. else
  5172. taicpu(p).oper[0]^.val := ThisConst;
  5173. {$endif x86_64}
  5174. else
  5175. InternalError(2021102610);
  5176. end;
  5177. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5178. if Result then
  5179. begin
  5180. if (taicpu(p).oper[0]^.val < 0) and
  5181. (
  5182. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5183. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5184. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5185. ) then
  5186. begin
  5187. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5188. taicpu(p).opcode := A_SUB;
  5189. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5190. end
  5191. else
  5192. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5193. RemoveInstruction(hp1);
  5194. end;
  5195. end
  5196. else
  5197. begin
  5198. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5199. TransferUsedRegs(TmpUsedRegs);
  5200. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5201. hp2 := p;
  5202. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5203. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5204. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5205. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5206. begin
  5207. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5208. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5209. Asml.Remove(p);
  5210. Asml.InsertAfter(p, hp1);
  5211. p := hp1;
  5212. Result := True;
  5213. Exit;
  5214. end;
  5215. end;
  5216. end;
  5217. if DoArithCombineOpt(p) then
  5218. Result:=true;
  5219. end;
  5220. end;
  5221. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5222. var
  5223. hp1, hp2: tai;
  5224. ref: Integer;
  5225. saveref: treference;
  5226. offsetcalc: Int64;
  5227. TempReg: TRegister;
  5228. Multiple: TCGInt;
  5229. Adjacent, IntermediateRegDiscarded: Boolean;
  5230. begin
  5231. Result:=false;
  5232. { play save and throw an error if LEA uses a seg register prefix,
  5233. this is most likely an error somewhere else }
  5234. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5235. internalerror(2022022001);
  5236. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5237. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5238. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5239. (
  5240. { do not mess with leas accessing the stack pointer
  5241. unless it's a null operation }
  5242. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5243. (
  5244. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5245. (taicpu(p).oper[0]^.ref^.offset = 0)
  5246. )
  5247. ) and
  5248. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5249. begin
  5250. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5251. begin
  5252. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5253. begin
  5254. taicpu(p).opcode := A_MOV;
  5255. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5256. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5257. end
  5258. else
  5259. begin
  5260. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5261. RemoveCurrentP(p);
  5262. end;
  5263. Result:=true;
  5264. exit;
  5265. end
  5266. else if (
  5267. { continue to use lea to adjust the stack pointer,
  5268. it is the recommended way, but only if not optimizing for size }
  5269. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5270. (cs_opt_size in current_settings.optimizerswitches)
  5271. ) and
  5272. { If the flags register is in use, don't change the instruction
  5273. to an ADD otherwise this will scramble the flags. [Kit] }
  5274. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5275. ConvertLEA(taicpu(p)) then
  5276. begin
  5277. Result:=true;
  5278. exit;
  5279. end;
  5280. end;
  5281. { Don't optimise if the stack or frame pointer is the destination register }
  5282. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5283. Exit;
  5284. if GetNextInstruction(p,hp1) and
  5285. (hp1.typ=ait_instruction) then
  5286. begin
  5287. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5288. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5289. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5290. begin
  5291. TransferUsedRegs(TmpUsedRegs);
  5292. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5293. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5294. begin
  5295. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5296. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5297. RemoveInstruction(hp1);
  5298. result:=true;
  5299. exit;
  5300. end;
  5301. end;
  5302. { changes
  5303. lea <ref1>, reg1
  5304. <op> ...,<ref. with reg1>,...
  5305. to
  5306. <op> ...,<ref1>,... }
  5307. { find a reference which uses reg1 }
  5308. 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
  5309. ref:=0
  5310. 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
  5311. ref:=1
  5312. else
  5313. ref:=-1;
  5314. if (ref<>-1) and
  5315. { reg1 must be either the base or the index }
  5316. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5317. begin
  5318. { reg1 can be removed from the reference }
  5319. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5320. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5321. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5322. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5323. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5324. else
  5325. Internalerror(2019111201);
  5326. { check if the can insert all data of the lea into the second instruction }
  5327. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5328. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5329. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5330. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5331. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5332. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5333. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5334. {$ifdef x86_64}
  5335. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5336. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5337. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5338. )
  5339. {$endif x86_64}
  5340. then
  5341. begin
  5342. { reg1 might not used by the second instruction after it is remove from the reference }
  5343. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5344. begin
  5345. TransferUsedRegs(TmpUsedRegs);
  5346. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5347. { reg1 is not updated so it might not be used afterwards }
  5348. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5349. begin
  5350. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5351. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5352. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5353. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5354. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5355. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5356. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5357. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5358. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5359. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5360. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5361. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5362. RemoveCurrentP(p, hp1);
  5363. result:=true;
  5364. exit;
  5365. end
  5366. end;
  5367. end;
  5368. { recover }
  5369. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5370. end;
  5371. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5372. if Adjacent or
  5373. { Check further ahead (up to 2 instructions ahead for -O2) }
  5374. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5375. begin
  5376. { Check common LEA/LEA conditions }
  5377. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5378. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5379. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5380. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5381. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5382. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5383. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5384. (
  5385. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5386. calling it (since it calls GetNextInstruction) }
  5387. Adjacent or
  5388. (
  5389. (
  5390. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5391. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5392. ) and (
  5393. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5394. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5395. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5396. )
  5397. )
  5398. ) then
  5399. begin
  5400. TransferUsedRegs(TmpUsedRegs);
  5401. hp2 := p;
  5402. repeat
  5403. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5404. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5405. IntermediateRegDiscarded :=
  5406. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5407. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5408. { changes
  5409. lea offset1(regX,scale), reg1
  5410. lea offset2(reg1,reg1), reg2
  5411. to
  5412. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5413. and
  5414. lea offset1(regX,scale1), reg1
  5415. lea offset2(reg1,scale2), reg2
  5416. to
  5417. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5418. and
  5419. lea offset1(regX,scale1), reg1
  5420. lea offset2(reg3,reg1,scale2), reg2
  5421. to
  5422. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5423. ... so long as the final scale does not exceed 8
  5424. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5425. }
  5426. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5427. (
  5428. { Don't optimise if size is a concern and the intermediate register remains in use }
  5429. IntermediateRegDiscarded or
  5430. not (cs_opt_size in current_settings.optimizerswitches)
  5431. ) and
  5432. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5433. (
  5434. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5435. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5436. ) and (
  5437. (
  5438. { lea (reg1,scale2), reg2 variant }
  5439. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5440. (
  5441. Adjacent or
  5442. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5443. ) and
  5444. (
  5445. (
  5446. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5447. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5448. ) or (
  5449. { lea (regX,regX), reg1 variant }
  5450. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5451. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5452. )
  5453. )
  5454. ) or (
  5455. { lea (reg1,reg1), reg1 variant }
  5456. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5457. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5458. )
  5459. ) then
  5460. begin
  5461. { Make everything homogeneous to make calculations easier }
  5462. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5463. begin
  5464. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5465. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5466. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5467. else
  5468. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5469. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5470. end;
  5471. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5472. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5473. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5474. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5475. begin
  5476. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5477. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5478. begin
  5479. { Put the register to change in the index register }
  5480. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5481. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5482. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5483. end;
  5484. if (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5485. begin
  5486. { Just to prevent miscalculations }
  5487. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5488. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5489. else
  5490. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5491. end
  5492. else
  5493. begin
  5494. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5495. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5496. end;
  5497. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5498. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(p).oper[0]^.ref^.scalefactor, 1));
  5499. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5500. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5501. if IntermediateRegDiscarded then
  5502. begin
  5503. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5504. RemoveCurrentP(p);
  5505. end
  5506. else
  5507. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5508. result:=true;
  5509. exit;
  5510. end;
  5511. end;
  5512. { changes
  5513. lea offset1(regX), reg1
  5514. lea offset2(reg1), reg2
  5515. to
  5516. lea offset1+offset2(regX), reg2 }
  5517. if (
  5518. { Don't optimise if size is a concern and the intermediate register remains in use }
  5519. IntermediateRegDiscarded or
  5520. not (cs_opt_size in current_settings.optimizerswitches)
  5521. ) and
  5522. (
  5523. (
  5524. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5525. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5526. ) or (
  5527. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5528. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5529. (
  5530. (
  5531. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5532. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5533. ) or (
  5534. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5535. (
  5536. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5537. (
  5538. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5539. (
  5540. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5541. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5542. )
  5543. )
  5544. )
  5545. )
  5546. )
  5547. )
  5548. ) then
  5549. begin
  5550. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5551. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5552. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5553. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5554. begin
  5555. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5556. begin
  5557. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5558. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5559. { if the register is used as index and base, we have to increase for base as well
  5560. and adapt base }
  5561. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5562. begin
  5563. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5564. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5565. end;
  5566. end
  5567. else
  5568. begin
  5569. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5570. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5571. end;
  5572. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5573. begin
  5574. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5575. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5576. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5577. end;
  5578. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5579. if IntermediateRegDiscarded then
  5580. begin
  5581. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5582. RemoveCurrentP(p);
  5583. end
  5584. else
  5585. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5586. result:=true;
  5587. exit;
  5588. end;
  5589. end;
  5590. end;
  5591. { Change:
  5592. leal/q $x(%reg1),%reg2
  5593. ...
  5594. shll/q $y,%reg2
  5595. To:
  5596. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5597. }
  5598. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5599. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5600. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5601. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5602. (taicpu(hp1).oper[0]^.val <= 3) then
  5603. begin
  5604. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5605. TransferUsedRegs(TmpUsedRegs);
  5606. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5607. if
  5608. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5609. (this works even if scalefactor is zero) }
  5610. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5611. { Ensure offset doesn't go out of bounds }
  5612. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5613. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5614. (
  5615. (
  5616. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5617. (
  5618. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5619. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5620. (
  5621. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5622. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5623. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5624. )
  5625. )
  5626. ) or (
  5627. (
  5628. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5629. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5630. ) and
  5631. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5632. )
  5633. ) then
  5634. begin
  5635. repeat
  5636. with taicpu(p).oper[0]^.ref^ do
  5637. begin
  5638. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5639. if index = base then
  5640. begin
  5641. if Multiple > 4 then
  5642. { Optimisation will no longer work because resultant
  5643. scale factor will exceed 8 }
  5644. Break;
  5645. base := NR_NO;
  5646. scalefactor := 2;
  5647. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5648. end
  5649. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5650. begin
  5651. { Scale factor only works on the index register }
  5652. index := base;
  5653. base := NR_NO;
  5654. end;
  5655. { For safety }
  5656. if scalefactor <= 1 then
  5657. begin
  5658. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5659. scalefactor := Multiple;
  5660. end
  5661. else
  5662. begin
  5663. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5664. scalefactor := scalefactor * Multiple;
  5665. end;
  5666. offset := offset * Multiple;
  5667. end;
  5668. RemoveInstruction(hp1);
  5669. Result := True;
  5670. Exit;
  5671. { This repeat..until loop exists for the benefit of Break }
  5672. until True;
  5673. end;
  5674. end;
  5675. end;
  5676. end;
  5677. end;
  5678. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5679. var
  5680. hp1 : tai;
  5681. SubInstr: Boolean;
  5682. ThisConst: TCGInt;
  5683. const
  5684. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5685. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5686. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5687. begin
  5688. Result := False;
  5689. if taicpu(p).oper[0]^.typ <> top_const then
  5690. { Should have been confirmed before calling }
  5691. InternalError(2021102601);
  5692. SubInstr := (taicpu(p).opcode = A_SUB);
  5693. if GetLastInstruction(p, hp1) and
  5694. (hp1.typ = ait_instruction) and
  5695. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5696. begin
  5697. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5698. { Bad size }
  5699. InternalError(2022042001);
  5700. case taicpu(hp1).opcode Of
  5701. A_INC:
  5702. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5703. begin
  5704. if SubInstr then
  5705. ThisConst := taicpu(p).oper[0]^.val - 1
  5706. else
  5707. ThisConst := taicpu(p).oper[0]^.val + 1;
  5708. end
  5709. else
  5710. Exit;
  5711. A_DEC:
  5712. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5713. begin
  5714. if SubInstr then
  5715. ThisConst := taicpu(p).oper[0]^.val + 1
  5716. else
  5717. ThisConst := taicpu(p).oper[0]^.val - 1;
  5718. end
  5719. else
  5720. Exit;
  5721. A_SUB:
  5722. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5723. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5724. begin
  5725. if SubInstr then
  5726. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5727. else
  5728. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5729. end
  5730. else
  5731. Exit;
  5732. A_ADD:
  5733. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5734. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5735. begin
  5736. if SubInstr then
  5737. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5738. else
  5739. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5740. end
  5741. else
  5742. Exit;
  5743. else
  5744. Exit;
  5745. end;
  5746. { Check that the values are in range }
  5747. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5748. { Overflow; abort }
  5749. Exit;
  5750. if (ThisConst = 0) then
  5751. begin
  5752. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5753. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5754. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5755. RemoveInstruction(hp1);
  5756. hp1 := tai(p.next);
  5757. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5758. if not GetLastInstruction(hp1, p) then
  5759. p := hp1;
  5760. end
  5761. else
  5762. begin
  5763. if taicpu(hp1).opercnt=1 then
  5764. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5765. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5766. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5767. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5768. else
  5769. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5770. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5771. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5772. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5773. RemoveInstruction(hp1);
  5774. taicpu(p).loadconst(0, ThisConst);
  5775. end;
  5776. Result := True;
  5777. end;
  5778. end;
  5779. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5780. begin
  5781. Result := False;
  5782. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5783. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5784. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5785. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5786. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5787. (
  5788. (
  5789. (taicpu(hp1).opcode = A_TEST)
  5790. ) or (
  5791. (taicpu(hp1).opcode = A_CMP) and
  5792. { A sanity check more than anything }
  5793. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5794. )
  5795. ) then
  5796. begin
  5797. { change
  5798. mov mem, %reg
  5799. ...
  5800. cmp/test x, %reg / test %reg,%reg
  5801. (reg deallocated)
  5802. to
  5803. cmp/test x, mem / cmp 0, mem
  5804. }
  5805. TransferUsedRegs(TmpUsedRegs);
  5806. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5807. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5808. begin
  5809. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5810. if (taicpu(hp1).opcode = A_TEST) and
  5811. (
  5812. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5813. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5814. ) then
  5815. begin
  5816. taicpu(hp1).opcode := A_CMP;
  5817. taicpu(hp1).loadconst(0, 0);
  5818. end;
  5819. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5820. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5821. RemoveCurrentP(p);
  5822. if (p <> hp1) then
  5823. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  5824. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  5825. { Make sure the flags are allocated across the CMP instruction }
  5826. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5827. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  5828. Result := True;
  5829. Exit;
  5830. end;
  5831. end;
  5832. end;
  5833. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5834. var
  5835. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5836. ThisReg, SecondReg: TRegister;
  5837. JumpLoc: TAsmLabel;
  5838. NewSize: TOpSize;
  5839. begin
  5840. Result := False;
  5841. {
  5842. Convert:
  5843. j<c> .L1
  5844. .L2:
  5845. mov 1,reg
  5846. jmp .L3 (or ret, although it might not be a RET yet)
  5847. .L1:
  5848. mov 0,reg
  5849. jmp .L3 (or ret)
  5850. ( As long as .L3 <> .L1 or .L2)
  5851. To:
  5852. mov 0,reg
  5853. set<not(c)> reg
  5854. jmp .L3 (or ret)
  5855. .L2:
  5856. mov 1,reg
  5857. jmp .L3 (or ret)
  5858. .L1:
  5859. mov 0,reg
  5860. jmp .L3 (or ret)
  5861. }
  5862. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5863. Exit;
  5864. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5865. if GetNextInstruction(hp_label, hp2) and
  5866. MatchInstruction(hp2,A_MOV,[]) and
  5867. (taicpu(hp2).oper[0]^.typ = top_const) and
  5868. (
  5869. (
  5870. (taicpu(hp2).oper[1]^.typ = top_reg)
  5871. {$ifdef i386}
  5872. { Under i386, ESI, EDI, EBP and ESP
  5873. don't have an 8-bit representation }
  5874. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5875. {$endif i386}
  5876. ) or (
  5877. {$ifdef i386}
  5878. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5879. {$endif i386}
  5880. (taicpu(hp2).opsize = S_B)
  5881. )
  5882. ) and
  5883. GetNextInstruction(hp2, hp3) and
  5884. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5885. (
  5886. (taicpu(hp3).opcode=A_RET) or
  5887. (
  5888. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5889. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5890. )
  5891. ) and
  5892. GetNextInstruction(hp3, hp4) and
  5893. SkipAligns(hp4, hp4) and
  5894. (hp4.typ=ait_label) and
  5895. (tai_label(hp4).labsym=JumpLoc) and
  5896. (
  5897. not (cs_opt_size in current_settings.optimizerswitches) or
  5898. { If the initial jump is the label's only reference, then it will
  5899. become a dead label if the other conditions are met and hence
  5900. remove at least 2 instructions, including a jump }
  5901. (JumpLoc.getrefs = 1)
  5902. ) and
  5903. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5904. that will be optimised out }
  5905. GetNextInstruction(hp4, hp5) and
  5906. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5907. (taicpu(hp5).oper[0]^.typ = top_const) and
  5908. (
  5909. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5910. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5911. ) and
  5912. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5913. GetNextInstruction(hp5,hp6) and
  5914. (
  5915. (hp6.typ<>ait_label) or
  5916. SkipLabels(hp6, hp6)
  5917. ) and
  5918. (hp6.typ=ait_instruction) then
  5919. begin
  5920. { First, let's look at the two jumps that are hp3 and hp6 }
  5921. if not
  5922. (
  5923. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5924. (
  5925. (taicpu(hp6).opcode=A_RET) or
  5926. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5927. )
  5928. ) then
  5929. { If condition is False, then the JMP/RET instructions matched conventionally }
  5930. begin
  5931. { See if one of the jumps can be instantly converted into a RET }
  5932. if (taicpu(hp3).opcode=A_JMP) then
  5933. begin
  5934. { Reuse hp5 }
  5935. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5936. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5937. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5938. Exit;
  5939. if MatchInstruction(hp5, A_RET, []) then
  5940. begin
  5941. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5942. ConvertJumpToRET(hp3, hp5);
  5943. Result := True;
  5944. end
  5945. else
  5946. Exit;
  5947. end;
  5948. if (taicpu(hp6).opcode=A_JMP) then
  5949. begin
  5950. { Reuse hp5 }
  5951. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5952. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5953. Exit;
  5954. if MatchInstruction(hp5, A_RET, []) then
  5955. begin
  5956. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5957. ConvertJumpToRET(hp6, hp5);
  5958. Result := True;
  5959. end
  5960. else
  5961. Exit;
  5962. end;
  5963. if not
  5964. (
  5965. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5966. (
  5967. (taicpu(hp6).opcode=A_RET) or
  5968. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5969. )
  5970. ) then
  5971. { Still doesn't match }
  5972. Exit;
  5973. end;
  5974. if (taicpu(hp2).oper[0]^.val = 1) then
  5975. begin
  5976. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5977. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5978. end
  5979. else
  5980. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5981. if taicpu(hp2).opsize=S_B then
  5982. begin
  5983. if taicpu(hp2).oper[1]^.typ = top_reg then
  5984. begin
  5985. SecondReg := taicpu(hp2).oper[1]^.reg;
  5986. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  5987. end
  5988. else
  5989. begin
  5990. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5991. SecondReg := NR_NO;
  5992. end;
  5993. hp_pos := p;
  5994. hp_allocstart := hp4;
  5995. end
  5996. else
  5997. begin
  5998. { Will be a register because the size can't be S_B otherwise }
  5999. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6000. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6001. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6002. if (cs_opt_size in current_settings.optimizerswitches) then
  6003. begin
  6004. { Favour using MOVZX when optimising for size }
  6005. case taicpu(hp2).opsize of
  6006. S_W:
  6007. NewSize := S_BW;
  6008. S_L:
  6009. NewSize := S_BL;
  6010. {$ifdef x86_64}
  6011. S_Q:
  6012. begin
  6013. NewSize := S_BL;
  6014. { Will implicitly zero-extend to 64-bit }
  6015. setsubreg(SecondReg, R_SUBD);
  6016. end;
  6017. {$endif x86_64}
  6018. else
  6019. InternalError(2022101301);
  6020. end;
  6021. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6022. { Inserting it right before p will guarantee that the flags are also tracked }
  6023. Asml.InsertBefore(hp5, p);
  6024. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6025. hp_pos := hp5;
  6026. hp_allocstart := hp4;
  6027. end
  6028. else
  6029. begin
  6030. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6031. { Inserting it right before p will guarantee that the flags are also tracked }
  6032. Asml.InsertBefore(hp5, p);
  6033. hp_pos := p;
  6034. hp_allocstart := hp5;
  6035. end;
  6036. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6037. end;
  6038. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6039. taicpu(hp4).condition := taicpu(p).condition;
  6040. asml.InsertBefore(hp4, hp_pos);
  6041. if taicpu(hp3).is_jmp then
  6042. begin
  6043. JumpLoc.decrefs;
  6044. MakeUnconditional(taicpu(p));
  6045. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6046. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6047. end
  6048. else
  6049. ConvertJumpToRET(p, hp3);
  6050. if SecondReg <> NR_NO then
  6051. { Ensure the destination register is allocated over this region }
  6052. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6053. if (JumpLoc.getrefs = 0) then
  6054. RemoveDeadCodeAfterJump(hp3);
  6055. Result:=true;
  6056. exit;
  6057. end;
  6058. end;
  6059. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6060. var
  6061. hp1, hp2: tai;
  6062. ActiveReg: TRegister;
  6063. OldOffset: asizeint;
  6064. ThisConst: TCGInt;
  6065. function RegDeallocated: Boolean;
  6066. begin
  6067. TransferUsedRegs(TmpUsedRegs);
  6068. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6069. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6070. end;
  6071. begin
  6072. Result:=false;
  6073. hp1 := nil;
  6074. { replace
  6075. subX const,%reg1
  6076. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6077. dealloc %reg1
  6078. by
  6079. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6080. }
  6081. if MatchOpType(taicpu(p),top_const,top_reg) then
  6082. begin
  6083. ActiveReg := taicpu(p).oper[1]^.reg;
  6084. { Ensures the entire register was updated }
  6085. if (taicpu(p).opsize >= S_L) and
  6086. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6087. MatchInstruction(hp1,A_LEA,[]) and
  6088. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6089. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6090. (
  6091. { Cover the case where the register in the reference is also the destination register }
  6092. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6093. (
  6094. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6095. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6096. RegDeallocated
  6097. )
  6098. ) then
  6099. begin
  6100. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6101. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6102. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6103. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6104. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6105. {$ifdef x86_64}
  6106. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6107. begin
  6108. { Overflow; abort }
  6109. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6110. end
  6111. else
  6112. {$endif x86_64}
  6113. begin
  6114. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6115. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6116. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6117. RemoveCurrentP(p, hp1)
  6118. else
  6119. RemoveCurrentP(p);
  6120. result:=true;
  6121. Exit;
  6122. end;
  6123. end;
  6124. if (
  6125. { Save calling GetNextInstructionUsingReg again }
  6126. Assigned(hp1) or
  6127. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6128. ) and
  6129. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6130. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6131. begin
  6132. if taicpu(hp1).oper[0]^.typ = top_const then
  6133. begin
  6134. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6135. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6136. Result := True;
  6137. { Handle any overflows }
  6138. case taicpu(p).opsize of
  6139. S_B:
  6140. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6141. S_W:
  6142. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6143. S_L:
  6144. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6145. {$ifdef x86_64}
  6146. S_Q:
  6147. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6148. { Overflow; abort }
  6149. Result := False
  6150. else
  6151. taicpu(p).oper[0]^.val := ThisConst;
  6152. {$endif x86_64}
  6153. else
  6154. InternalError(2021102611);
  6155. end;
  6156. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6157. if Result then
  6158. begin
  6159. if (taicpu(p).oper[0]^.val < 0) and
  6160. (
  6161. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6162. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6163. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6164. ) then
  6165. begin
  6166. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6167. taicpu(p).opcode := A_SUB;
  6168. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6169. end
  6170. else
  6171. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6172. RemoveInstruction(hp1);
  6173. end;
  6174. end
  6175. else
  6176. begin
  6177. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6178. TransferUsedRegs(TmpUsedRegs);
  6179. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6180. hp2 := p;
  6181. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6182. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6183. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6184. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6185. begin
  6186. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6187. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6188. Asml.Remove(p);
  6189. Asml.InsertAfter(p, hp1);
  6190. p := hp1;
  6191. Result := True;
  6192. Exit;
  6193. end;
  6194. end;
  6195. end;
  6196. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6197. { * change "sub/add const1, reg" or "dec reg" followed by
  6198. "sub const2, reg" to one "sub ..., reg" }
  6199. {$ifdef i386}
  6200. if (taicpu(p).oper[0]^.val = 2) and
  6201. (ActiveReg = NR_ESP) and
  6202. { Don't do the sub/push optimization if the sub }
  6203. { comes from setting up the stack frame (JM) }
  6204. (not(GetLastInstruction(p,hp1)) or
  6205. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6206. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6207. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6208. begin
  6209. hp1 := tai(p.next);
  6210. while Assigned(hp1) and
  6211. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6212. not RegReadByInstruction(NR_ESP,hp1) and
  6213. not RegModifiedByInstruction(NR_ESP,hp1) do
  6214. hp1 := tai(hp1.next);
  6215. if Assigned(hp1) and
  6216. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6217. begin
  6218. taicpu(hp1).changeopsize(S_L);
  6219. if taicpu(hp1).oper[0]^.typ=top_reg then
  6220. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6221. hp1 := tai(p.next);
  6222. RemoveCurrentp(p, hp1);
  6223. Result:=true;
  6224. exit;
  6225. end;
  6226. end;
  6227. {$endif i386}
  6228. if DoArithCombineOpt(p) then
  6229. Result:=true;
  6230. end;
  6231. end;
  6232. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6233. var
  6234. TmpBool1,TmpBool2 : Boolean;
  6235. tmpref : treference;
  6236. hp1,hp2: tai;
  6237. mask, shiftval: tcgint;
  6238. begin
  6239. Result:=false;
  6240. { All these optimisations work on "shl/sal const,%reg" }
  6241. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6242. Exit;
  6243. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6244. (taicpu(p).oper[0]^.val <= 3) then
  6245. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6246. begin
  6247. { should we check the next instruction? }
  6248. TmpBool1 := True;
  6249. { have we found an add/sub which could be
  6250. integrated in the lea? }
  6251. TmpBool2 := False;
  6252. reference_reset(tmpref,2,[]);
  6253. TmpRef.index := taicpu(p).oper[1]^.reg;
  6254. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6255. while TmpBool1 and
  6256. GetNextInstruction(p, hp1) and
  6257. (tai(hp1).typ = ait_instruction) and
  6258. ((((taicpu(hp1).opcode = A_ADD) or
  6259. (taicpu(hp1).opcode = A_SUB)) and
  6260. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6261. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6262. (((taicpu(hp1).opcode = A_INC) or
  6263. (taicpu(hp1).opcode = A_DEC)) and
  6264. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6265. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6266. ((taicpu(hp1).opcode = A_LEA) and
  6267. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6268. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6269. (not GetNextInstruction(hp1,hp2) or
  6270. not instrReadsFlags(hp2)) Do
  6271. begin
  6272. TmpBool1 := False;
  6273. if taicpu(hp1).opcode=A_LEA then
  6274. begin
  6275. if (TmpRef.base = NR_NO) and
  6276. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6277. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6278. { Segment register isn't a concern here }
  6279. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6280. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6281. begin
  6282. TmpBool1 := True;
  6283. TmpBool2 := True;
  6284. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6285. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6286. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6287. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6288. RemoveInstruction(hp1);
  6289. end
  6290. end
  6291. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6292. begin
  6293. TmpBool1 := True;
  6294. TmpBool2 := True;
  6295. case taicpu(hp1).opcode of
  6296. A_ADD:
  6297. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6298. A_SUB:
  6299. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6300. else
  6301. internalerror(2019050536);
  6302. end;
  6303. RemoveInstruction(hp1);
  6304. end
  6305. else
  6306. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6307. (((taicpu(hp1).opcode = A_ADD) and
  6308. (TmpRef.base = NR_NO)) or
  6309. (taicpu(hp1).opcode = A_INC) or
  6310. (taicpu(hp1).opcode = A_DEC)) then
  6311. begin
  6312. TmpBool1 := True;
  6313. TmpBool2 := True;
  6314. case taicpu(hp1).opcode of
  6315. A_ADD:
  6316. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6317. A_INC:
  6318. inc(TmpRef.offset);
  6319. A_DEC:
  6320. dec(TmpRef.offset);
  6321. else
  6322. internalerror(2019050535);
  6323. end;
  6324. RemoveInstruction(hp1);
  6325. end;
  6326. end;
  6327. if TmpBool2
  6328. {$ifndef x86_64}
  6329. or
  6330. ((current_settings.optimizecputype < cpu_Pentium2) and
  6331. (taicpu(p).oper[0]^.val <= 3) and
  6332. not(cs_opt_size in current_settings.optimizerswitches))
  6333. {$endif x86_64}
  6334. then
  6335. begin
  6336. if not(TmpBool2) and
  6337. (taicpu(p).oper[0]^.val=1) then
  6338. begin
  6339. taicpu(p).opcode := A_ADD;
  6340. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6341. end
  6342. else
  6343. begin
  6344. taicpu(p).opcode := A_LEA;
  6345. taicpu(p).loadref(0, TmpRef);
  6346. end;
  6347. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6348. Result := True;
  6349. end;
  6350. end
  6351. {$ifndef x86_64}
  6352. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6353. begin
  6354. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6355. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6356. (unlike shl, which is only Tairable in the U pipe) }
  6357. if taicpu(p).oper[0]^.val=1 then
  6358. begin
  6359. taicpu(p).opcode := A_ADD;
  6360. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6361. Result := True;
  6362. end
  6363. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6364. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6365. else if (taicpu(p).opsize = S_L) and
  6366. (taicpu(p).oper[0]^.val<= 3) then
  6367. begin
  6368. reference_reset(tmpref,2,[]);
  6369. TmpRef.index := taicpu(p).oper[1]^.reg;
  6370. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6371. taicpu(p).opcode := A_LEA;
  6372. taicpu(p).loadref(0, TmpRef);
  6373. Result := True;
  6374. end;
  6375. end
  6376. {$endif x86_64}
  6377. else if
  6378. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6379. (
  6380. (
  6381. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6382. SetAndTest(hp1, hp2)
  6383. {$ifdef x86_64}
  6384. ) or
  6385. (
  6386. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6387. GetNextInstruction(hp1, hp2) and
  6388. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6389. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6390. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6391. {$endif x86_64}
  6392. )
  6393. ) and
  6394. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6395. begin
  6396. { Change:
  6397. shl x, %reg1
  6398. mov -(1<<x), %reg2
  6399. and %reg2, %reg1
  6400. Or:
  6401. shl x, %reg1
  6402. and -(1<<x), %reg1
  6403. To just:
  6404. shl x, %reg1
  6405. Since the and operation only zeroes bits that are already zero from the shl operation
  6406. }
  6407. case taicpu(p).oper[0]^.val of
  6408. 8:
  6409. mask:=$FFFFFFFFFFFFFF00;
  6410. 16:
  6411. mask:=$FFFFFFFFFFFF0000;
  6412. 32:
  6413. mask:=$FFFFFFFF00000000;
  6414. 63:
  6415. { Constant pre-calculated to prevent overflow errors with Int64 }
  6416. mask:=$8000000000000000;
  6417. else
  6418. begin
  6419. if taicpu(p).oper[0]^.val >= 64 then
  6420. { Shouldn't happen realistically, since the register
  6421. is guaranteed to be set to zero at this point }
  6422. mask := 0
  6423. else
  6424. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6425. end;
  6426. end;
  6427. if taicpu(hp1).oper[0]^.val = mask then
  6428. begin
  6429. { Everything checks out, perform the optimisation, as long as
  6430. the FLAGS register isn't being used}
  6431. TransferUsedRegs(TmpUsedRegs);
  6432. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6433. {$ifdef x86_64}
  6434. if (hp1 <> hp2) then
  6435. begin
  6436. { "shl/mov/and" version }
  6437. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6438. { Don't do the optimisation if the FLAGS register is in use }
  6439. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6440. begin
  6441. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6442. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6443. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6444. begin
  6445. RemoveInstruction(hp1);
  6446. Result := True;
  6447. end;
  6448. { Only set Result to True if the 'mov' instruction was removed }
  6449. RemoveInstruction(hp2);
  6450. end;
  6451. end
  6452. else
  6453. {$endif x86_64}
  6454. begin
  6455. { "shl/and" version }
  6456. { Don't do the optimisation if the FLAGS register is in use }
  6457. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6458. begin
  6459. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6460. RemoveInstruction(hp1);
  6461. Result := True;
  6462. end;
  6463. end;
  6464. Exit;
  6465. end
  6466. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6467. begin
  6468. { Even if the mask doesn't allow for its removal, we might be
  6469. able to optimise the mask for the "shl/and" version, which
  6470. may permit other peephole optimisations }
  6471. {$ifdef DEBUG_AOPTCPU}
  6472. mask := taicpu(hp1).oper[0]^.val and mask;
  6473. if taicpu(hp1).oper[0]^.val <> mask then
  6474. begin
  6475. DebugMsg(
  6476. SPeepholeOptimization +
  6477. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6478. ' to $' + debug_tostr(mask) +
  6479. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6480. taicpu(hp1).oper[0]^.val := mask;
  6481. end;
  6482. {$else DEBUG_AOPTCPU}
  6483. { If debugging is off, just set the operand even if it's the same }
  6484. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6485. {$endif DEBUG_AOPTCPU}
  6486. end;
  6487. end;
  6488. {
  6489. change
  6490. shl/sal const,reg
  6491. <op> ...(...,reg,1),...
  6492. into
  6493. <op> ...(...,reg,1 shl const),...
  6494. if const in 1..3
  6495. }
  6496. if MatchOpType(taicpu(p), top_const, top_reg) and
  6497. (taicpu(p).oper[0]^.val in [1..3]) and
  6498. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6499. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6500. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6501. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6502. MatchOpType(taicpu(hp1),top_ref))
  6503. ) and
  6504. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6505. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6506. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6507. begin
  6508. TransferUsedRegs(TmpUsedRegs);
  6509. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6510. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6511. begin
  6512. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6513. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6514. RemoveCurrentP(p);
  6515. Result:=true;
  6516. exit;
  6517. end;
  6518. end;
  6519. if MatchOpType(taicpu(p), top_const, top_reg) and
  6520. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6521. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6522. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6523. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6524. begin
  6525. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6526. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6527. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6528. {$ifdef x86_64}
  6529. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6530. {$endif x86_64}
  6531. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6532. begin
  6533. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6534. taicpu(hp1).opcode:=A_MOV;
  6535. taicpu(hp1).oper[0]^.val:=0;
  6536. end
  6537. else
  6538. begin
  6539. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6540. taicpu(hp1).oper[0]^.val:=shiftval;
  6541. end;
  6542. RemoveCurrentP(p);
  6543. Result:=true;
  6544. exit;
  6545. end;
  6546. end;
  6547. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6548. begin
  6549. case shr_size of
  6550. S_B:
  6551. { No valid combinations }
  6552. Result := False;
  6553. S_W:
  6554. Result := (Shift >= 8) and (movz_size = S_BW);
  6555. S_L:
  6556. Result :=
  6557. (Shift >= 24) { Any opsize is valid for this shift } or
  6558. ((Shift >= 16) and (movz_size = S_WL));
  6559. {$ifdef x86_64}
  6560. S_Q:
  6561. Result :=
  6562. (Shift >= 56) { Any opsize is valid for this shift } or
  6563. ((Shift >= 48) and (movz_size = S_WL));
  6564. {$endif x86_64}
  6565. else
  6566. InternalError(2022081510);
  6567. end;
  6568. end;
  6569. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6570. var
  6571. hp1, hp2: tai;
  6572. Shift: TCGInt;
  6573. LimitSize: Topsize;
  6574. DoNotMerge: Boolean;
  6575. begin
  6576. Result := False;
  6577. { All these optimisations work on "shr const,%reg" }
  6578. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6579. Exit;
  6580. DoNotMerge := False;
  6581. Shift := taicpu(p).oper[0]^.val;
  6582. LimitSize := taicpu(p).opsize;
  6583. hp1 := p;
  6584. repeat
  6585. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6586. Exit;
  6587. case taicpu(hp1).opcode of
  6588. A_TEST, A_CMP, A_Jcc:
  6589. { Skip over conditional jumps and relevant comparisons }
  6590. Continue;
  6591. A_MOVZX:
  6592. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6593. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6594. begin
  6595. { Since the original register is being read as is, subsequent
  6596. SHRs must not be merged at this point }
  6597. DoNotMerge := True;
  6598. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6599. begin
  6600. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6601. begin
  6602. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6603. taicpu(hp1).opcode := A_MOV;
  6604. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6605. case taicpu(hp1).opsize of
  6606. S_BW:
  6607. taicpu(hp1).opsize := S_W;
  6608. S_BL, S_WL:
  6609. taicpu(hp1).opsize := S_L;
  6610. else
  6611. InternalError(2022081503);
  6612. end;
  6613. { p itself hasn't changed, so no need to set Result to True }
  6614. Include(OptsToCheck, aoc_ForceNewIteration);
  6615. { See if there's anything afterwards that can be
  6616. optimised, since the input register hasn't changed }
  6617. Continue;
  6618. end;
  6619. { NOTE: If the MOVZX instruction reads and writes the same
  6620. register, defer this to the post-peephole optimisation stage }
  6621. Exit;
  6622. end;
  6623. end;
  6624. A_SHL, A_SAL, A_SHR:
  6625. if (taicpu(hp1).opsize <= LimitSize) and
  6626. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6627. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6628. begin
  6629. { Make sure the sizes don't exceed the register size limit
  6630. (measured by the shift value falling below the limit) }
  6631. if taicpu(hp1).opsize < LimitSize then
  6632. LimitSize := taicpu(hp1).opsize;
  6633. if taicpu(hp1).opcode = A_SHR then
  6634. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6635. else
  6636. begin
  6637. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6638. DoNotMerge := True;
  6639. end;
  6640. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6641. Exit;
  6642. { Since we've established that the combined shift is within
  6643. limits, we can actually combine the adjacent SHR
  6644. instructions even if they're different sizes }
  6645. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6646. begin
  6647. hp2 := tai(hp1.Previous);
  6648. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6649. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6650. RemoveInstruction(hp1);
  6651. hp1 := hp2;
  6652. { Though p has changed, only the constant has, and its
  6653. effects can still be detected on the next iteration of
  6654. the repeat..until loop }
  6655. Include(OptsToCheck, aoc_ForceNewIteration);
  6656. end;
  6657. { Move onto the next instruction }
  6658. Continue;
  6659. end;
  6660. else
  6661. ;
  6662. end;
  6663. Break;
  6664. until False;
  6665. end;
  6666. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6667. var
  6668. CurrentRef: TReference;
  6669. FullReg: TRegister;
  6670. hp1, hp2: tai;
  6671. begin
  6672. Result := False;
  6673. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6674. Exit;
  6675. { We assume you've checked if the operand is actually a reference by
  6676. this point. If it isn't, you'll most likely get an access violation }
  6677. CurrentRef := first_mov.oper[1]^.ref^;
  6678. { Memory must be aligned }
  6679. if (CurrentRef.offset mod 4) <> 0 then
  6680. Exit;
  6681. Inc(CurrentRef.offset);
  6682. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6683. if MatchOperand(second_mov.oper[0]^, 0) and
  6684. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6685. GetNextInstruction(second_mov, hp1) and
  6686. (hp1.typ = ait_instruction) and
  6687. (taicpu(hp1).opcode = A_MOV) and
  6688. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6689. (taicpu(hp1).oper[0]^.val = 0) then
  6690. begin
  6691. Inc(CurrentRef.offset);
  6692. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6693. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6694. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6695. begin
  6696. case taicpu(hp1).opsize of
  6697. S_B:
  6698. if GetNextInstruction(hp1, hp2) and
  6699. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6700. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6701. (taicpu(hp2).oper[0]^.val = 0) then
  6702. begin
  6703. Inc(CurrentRef.offset);
  6704. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6705. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6706. (taicpu(hp2).opsize = S_B) then
  6707. begin
  6708. RemoveInstruction(hp1);
  6709. RemoveInstruction(hp2);
  6710. first_mov.opsize := S_L;
  6711. if first_mov.oper[0]^.typ = top_reg then
  6712. begin
  6713. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6714. { Reuse second_mov as a MOVZX instruction }
  6715. second_mov.opcode := A_MOVZX;
  6716. second_mov.opsize := S_BL;
  6717. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6718. second_mov.loadreg(1, FullReg);
  6719. first_mov.oper[0]^.reg := FullReg;
  6720. asml.Remove(second_mov);
  6721. asml.InsertBefore(second_mov, first_mov);
  6722. end
  6723. else
  6724. { It's a value }
  6725. begin
  6726. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6727. RemoveInstruction(second_mov);
  6728. end;
  6729. Result := True;
  6730. Exit;
  6731. end;
  6732. end;
  6733. S_W:
  6734. begin
  6735. RemoveInstruction(hp1);
  6736. first_mov.opsize := S_L;
  6737. if first_mov.oper[0]^.typ = top_reg then
  6738. begin
  6739. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6740. { Reuse second_mov as a MOVZX instruction }
  6741. second_mov.opcode := A_MOVZX;
  6742. second_mov.opsize := S_BL;
  6743. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6744. second_mov.loadreg(1, FullReg);
  6745. first_mov.oper[0]^.reg := FullReg;
  6746. asml.Remove(second_mov);
  6747. asml.InsertBefore(second_mov, first_mov);
  6748. end
  6749. else
  6750. { It's a value }
  6751. begin
  6752. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6753. RemoveInstruction(second_mov);
  6754. end;
  6755. Result := True;
  6756. Exit;
  6757. end;
  6758. else
  6759. ;
  6760. end;
  6761. end;
  6762. end;
  6763. end;
  6764. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6765. { returns true if a "continue" should be done after this optimization }
  6766. var
  6767. hp1, hp2, hp3: tai;
  6768. begin
  6769. Result := false;
  6770. hp3 := nil;
  6771. if MatchOpType(taicpu(p),top_ref) and
  6772. GetNextInstruction(p, hp1) and
  6773. (hp1.typ = ait_instruction) and
  6774. (((taicpu(hp1).opcode = A_FLD) and
  6775. (taicpu(p).opcode = A_FSTP)) or
  6776. ((taicpu(p).opcode = A_FISTP) and
  6777. (taicpu(hp1).opcode = A_FILD))) and
  6778. MatchOpType(taicpu(hp1),top_ref) and
  6779. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6780. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6781. begin
  6782. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6783. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6784. GetNextInstruction(hp1, hp2) and
  6785. (((hp2.typ = ait_instruction) and
  6786. IsExitCode(hp2) and
  6787. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6788. not(assigned(current_procinfo.procdef.funcretsym) and
  6789. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6790. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6791. { fstp <temp>
  6792. fld <temp>
  6793. <dealloc> <temp>
  6794. }
  6795. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6796. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6797. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6798. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6799. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6800. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6801. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6802. )
  6803. )
  6804. ) then
  6805. begin
  6806. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6807. RemoveInstruction(hp1);
  6808. RemoveCurrentP(p, hp2);
  6809. { first case: exit code }
  6810. if hp2.typ = ait_instruction then
  6811. RemoveLastDeallocForFuncRes(p);
  6812. Result := true;
  6813. end
  6814. else
  6815. { we can do this only in fast math mode as fstp is rounding ...
  6816. ... still disabled as it breaks the compiler and/or rtl }
  6817. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6818. { ... or if another fstp equal to the first one follows }
  6819. GetNextInstruction(hp1,hp2) and
  6820. (hp2.typ = ait_instruction) and
  6821. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6822. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6823. begin
  6824. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6825. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6826. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6827. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6828. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6829. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6830. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6831. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6832. ) then
  6833. begin
  6834. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6835. RemoveCurrentP(p,hp2);
  6836. RemoveInstruction(hp1);
  6837. Result := true;
  6838. end
  6839. else if { fst can't store an extended/comp value }
  6840. (taicpu(p).opsize <> S_FX) and
  6841. (taicpu(p).opsize <> S_IQ) then
  6842. begin
  6843. if (taicpu(p).opcode = A_FSTP) then
  6844. taicpu(p).opcode := A_FST
  6845. else
  6846. taicpu(p).opcode := A_FIST;
  6847. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6848. RemoveInstruction(hp1);
  6849. Result := true;
  6850. end;
  6851. end;
  6852. end;
  6853. end;
  6854. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6855. var
  6856. hp1, hp2, hp3: tai;
  6857. begin
  6858. result:=false;
  6859. if MatchOpType(taicpu(p),top_reg) and
  6860. GetNextInstruction(p, hp1) and
  6861. (hp1.typ = Ait_Instruction) and
  6862. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6863. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6864. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6865. { change to
  6866. fld reg fxxx reg,st
  6867. fxxxp st, st1 (hp1)
  6868. Remark: non commutative operations must be reversed!
  6869. }
  6870. begin
  6871. case taicpu(hp1).opcode Of
  6872. A_FMULP,A_FADDP,
  6873. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6874. begin
  6875. case taicpu(hp1).opcode Of
  6876. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6877. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6878. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6879. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6880. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6881. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6882. else
  6883. internalerror(2019050534);
  6884. end;
  6885. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6886. taicpu(hp1).oper[1]^.reg := NR_ST;
  6887. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6888. RemoveCurrentP(p, hp1);
  6889. Result:=true;
  6890. exit;
  6891. end;
  6892. else
  6893. ;
  6894. end;
  6895. end
  6896. else
  6897. if MatchOpType(taicpu(p),top_ref) and
  6898. GetNextInstruction(p, hp2) and
  6899. (hp2.typ = Ait_Instruction) and
  6900. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6901. (taicpu(p).opsize in [S_FS, S_FL]) and
  6902. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6903. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6904. if GetLastInstruction(p, hp1) and
  6905. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6906. MatchOpType(taicpu(hp1),top_ref) and
  6907. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6908. if ((taicpu(hp2).opcode = A_FMULP) or
  6909. (taicpu(hp2).opcode = A_FADDP)) then
  6910. { change to
  6911. fld/fst mem1 (hp1) fld/fst mem1
  6912. fld mem1 (p) fadd/
  6913. faddp/ fmul st, st
  6914. fmulp st, st1 (hp2) }
  6915. begin
  6916. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6917. RemoveCurrentP(p, hp1);
  6918. if (taicpu(hp2).opcode = A_FADDP) then
  6919. taicpu(hp2).opcode := A_FADD
  6920. else
  6921. taicpu(hp2).opcode := A_FMUL;
  6922. taicpu(hp2).oper[1]^.reg := NR_ST;
  6923. end
  6924. else
  6925. { change to
  6926. fld/fst mem1 (hp1) fld/fst mem1
  6927. fld mem1 (p) fld st
  6928. }
  6929. begin
  6930. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6931. taicpu(p).changeopsize(S_FL);
  6932. taicpu(p).loadreg(0,NR_ST);
  6933. end
  6934. else
  6935. begin
  6936. case taicpu(hp2).opcode Of
  6937. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6938. { change to
  6939. fld/fst mem1 (hp1) fld/fst mem1
  6940. fld mem2 (p) fxxx mem2
  6941. fxxxp st, st1 (hp2) }
  6942. begin
  6943. case taicpu(hp2).opcode Of
  6944. A_FADDP: taicpu(p).opcode := A_FADD;
  6945. A_FMULP: taicpu(p).opcode := A_FMUL;
  6946. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6947. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6948. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6949. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6950. else
  6951. internalerror(2019050533);
  6952. end;
  6953. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6954. RemoveInstruction(hp2);
  6955. end
  6956. else
  6957. ;
  6958. end
  6959. end
  6960. end;
  6961. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6962. begin
  6963. Result := condition_in(cond1, cond2) or
  6964. { Not strictly subsets due to the actual flags checked, but because we're
  6965. comparing integers, E is a subset of AE and GE and their aliases }
  6966. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6967. end;
  6968. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6969. var
  6970. v: TCGInt;
  6971. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6972. FirstMatch, TempBool: Boolean;
  6973. NewReg: TRegister;
  6974. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6975. begin
  6976. Result:=false;
  6977. { All these optimisations need a next instruction }
  6978. if not GetNextInstruction(p, hp1) then
  6979. Exit;
  6980. { Search for:
  6981. cmp ###,###
  6982. j(c1) @lbl1
  6983. ...
  6984. @lbl:
  6985. cmp ###,### (same comparison as above)
  6986. j(c2) @lbl2
  6987. If c1 is a subset of c2, change to:
  6988. cmp ###,###
  6989. j(c1) @lbl2
  6990. (@lbl1 may become a dead label as a result)
  6991. }
  6992. { Also handle cases where there are multiple jumps in a row }
  6993. p_jump := hp1;
  6994. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6995. begin
  6996. if IsJumpToLabel(taicpu(p_jump)) then
  6997. begin
  6998. { Do jump optimisations first in case the condition becomes
  6999. unnecessary }
  7000. TempBool := True;
  7001. if DoJumpOptimizations(p_jump, TempBool) or
  7002. not TempBool then
  7003. begin
  7004. if Assigned(p_jump) then
  7005. begin
  7006. hp1 := p_jump;
  7007. if (p_jump.typ in [ait_align]) then
  7008. SkipAligns(p_jump, p_jump);
  7009. { CollapseZeroDistJump will be set to the label after the
  7010. jump if it optimises, whether or not it's live or dead }
  7011. if (p_jump.typ in [ait_label]) and
  7012. not (tai_label(p_jump).labsym.is_used) then
  7013. GetNextInstruction(p_jump, p_jump);
  7014. end;
  7015. TransferUsedRegs(TmpUsedRegs);
  7016. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7017. if not Assigned(p_jump) or
  7018. (
  7019. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7020. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7021. ) then
  7022. begin
  7023. { No more conditional jumps; conditional statement is no longer required }
  7024. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7025. RemoveCurrentP(p);
  7026. Result := True;
  7027. Exit;
  7028. end;
  7029. hp1 := p_jump;
  7030. Include(OptsToCheck, aoc_ForceNewIteration);
  7031. Continue;
  7032. end;
  7033. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7034. if GetNextInstruction(p_jump, hp2) and
  7035. (
  7036. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7037. not TempBool
  7038. ) then
  7039. begin
  7040. hp1 := p_jump;
  7041. Include(OptsToCheck, aoc_ForceNewIteration);
  7042. Continue;
  7043. end;
  7044. p_label := nil;
  7045. if Assigned(JumpLabel) then
  7046. p_label := getlabelwithsym(JumpLabel);
  7047. if Assigned(p_label) and
  7048. GetNextInstruction(p_label, p_dist) and
  7049. MatchInstruction(p_dist, A_CMP, []) and
  7050. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7051. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7052. GetNextInstruction(p_dist, hp1_dist) and
  7053. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7054. begin
  7055. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7056. if JumpLabel = JumpLabel_dist then
  7057. { This is an infinite loop }
  7058. Exit;
  7059. { Best optimisation when the first condition is a subset (or equal) of the second }
  7060. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7061. begin
  7062. { Any registers used here will already be allocated }
  7063. if Assigned(JumpLabel) then
  7064. JumpLabel.DecRefs;
  7065. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7066. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7067. Result := True;
  7068. { Don't exit yet. Since p and p_jump haven't actually been
  7069. removed, we can check for more on this iteration }
  7070. end
  7071. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7072. GetNextInstruction(hp1_dist, hp1_label) and
  7073. SkipAligns(hp1_label, hp1_label) and
  7074. (hp1_label.typ = ait_label) then
  7075. begin
  7076. JumpLabel_far := tai_label(hp1_label).labsym;
  7077. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7078. { This is an infinite loop }
  7079. Exit;
  7080. if Assigned(JumpLabel_far) then
  7081. begin
  7082. { In this situation, if the first jump branches, the second one will never,
  7083. branch so change the destination label to after the second jump }
  7084. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7085. if Assigned(JumpLabel) then
  7086. JumpLabel.DecRefs;
  7087. JumpLabel_far.IncRefs;
  7088. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7089. Result := True;
  7090. { Don't exit yet. Since p and p_jump haven't actually been
  7091. removed, we can check for more on this iteration }
  7092. Continue;
  7093. end;
  7094. end;
  7095. end;
  7096. end;
  7097. { Search for:
  7098. cmp ###,###
  7099. j(c1) @lbl1
  7100. cmp ###,### (same as first)
  7101. Remove second cmp
  7102. }
  7103. if GetNextInstruction(p_jump, hp2) and
  7104. (
  7105. (
  7106. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7107. (
  7108. (
  7109. MatchOpType(taicpu(p), top_const, top_reg) and
  7110. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7111. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7112. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7113. ) or (
  7114. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7115. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7116. )
  7117. )
  7118. ) or (
  7119. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7120. MatchOperand(taicpu(p).oper[0]^, 0) and
  7121. (taicpu(p).oper[1]^.typ = top_reg) and
  7122. MatchInstruction(hp2, A_TEST, []) and
  7123. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7124. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7125. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7126. )
  7127. ) then
  7128. begin
  7129. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7130. RemoveInstruction(hp2);
  7131. Result := True;
  7132. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7133. end;
  7134. GetNextInstruction(p_jump, p_jump);
  7135. end;
  7136. if (
  7137. { Don't call GetNextInstruction again if we already have it }
  7138. (hp1 = p_jump) or
  7139. GetNextInstruction(p, hp1)
  7140. ) and
  7141. MatchInstruction(hp1, A_Jcc, []) and
  7142. IsJumpToLabel(taicpu(hp1)) and
  7143. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7144. GetNextInstruction(hp1, hp2) then
  7145. begin
  7146. {
  7147. cmp x, y (or "cmp y, x")
  7148. je @lbl
  7149. mov x, y
  7150. @lbl:
  7151. (x and y can be constants, registers or references)
  7152. Change to:
  7153. mov x, y (x and y will always be equal in the end)
  7154. @lbl: (may beceome a dead label)
  7155. Also:
  7156. cmp x, y (or "cmp y, x")
  7157. jne @lbl
  7158. mov x, y
  7159. @lbl:
  7160. (x and y can be constants, registers or references)
  7161. Change to:
  7162. Absolutely nothing! (Except @lbl if it's still live)
  7163. }
  7164. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7165. (
  7166. (
  7167. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7168. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7169. ) or (
  7170. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7171. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7172. )
  7173. ) and
  7174. GetNextInstruction(hp2, hp1_label) and
  7175. SkipAligns(hp1_label, hp1_label) and
  7176. (hp1_label.typ = ait_label) and
  7177. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7178. begin
  7179. tai_label(hp1_label).labsym.DecRefs;
  7180. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7181. begin
  7182. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7183. RemoveInstruction(hp2);
  7184. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7185. end
  7186. else
  7187. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7188. RemoveInstruction(hp1);
  7189. RemoveCurrentp(p, hp2);
  7190. Result := True;
  7191. Exit;
  7192. end;
  7193. {
  7194. Try to optimise the following:
  7195. cmp $x,### ($x and $y can be registers or constants)
  7196. je @lbl1 (only reference)
  7197. cmp $y,### (### are identical)
  7198. @Lbl:
  7199. sete %reg1
  7200. Change to:
  7201. cmp $x,###
  7202. sete %reg2 (allocate new %reg2)
  7203. cmp $y,###
  7204. sete %reg1
  7205. orb %reg2,%reg1
  7206. (dealloc %reg2)
  7207. This adds an instruction (so don't perform under -Os), but it removes
  7208. a conditional branch.
  7209. }
  7210. if not (cs_opt_size in current_settings.optimizerswitches) and
  7211. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7212. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7213. { The first operand of CMP instructions can only be a register or
  7214. immediate anyway, so no need to check }
  7215. GetNextInstruction(hp2, p_label) and
  7216. (p_label.typ = ait_label) and
  7217. (tai_label(p_label).labsym.getrefs = 1) and
  7218. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7219. GetNextInstruction(p_label, p_dist) and
  7220. MatchInstruction(p_dist, A_SETcc, []) and
  7221. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7222. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7223. begin
  7224. TransferUsedRegs(TmpUsedRegs);
  7225. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7226. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7227. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7228. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7229. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7230. { Get the instruction after the SETcc instruction so we can
  7231. allocate a new register over the entire range }
  7232. GetNextInstruction(p_dist, hp1_dist) then
  7233. begin
  7234. { Register can appear in p if it's not used afterwards, so only
  7235. allocate between hp1 and hp1_dist }
  7236. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7237. if NewReg <> NR_NO then
  7238. begin
  7239. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7240. { Change the jump instruction into a SETcc instruction }
  7241. taicpu(hp1).opcode := A_SETcc;
  7242. taicpu(hp1).opsize := S_B;
  7243. taicpu(hp1).loadreg(0, NewReg);
  7244. { This is now a dead label }
  7245. tai_label(p_label).labsym.decrefs;
  7246. { Prefer adding before the next instruction so the FLAGS
  7247. register is deallicated first }
  7248. AsmL.InsertBefore(
  7249. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7250. hp1_dist
  7251. );
  7252. Result := True;
  7253. { Don't exit yet, as p wasn't changed and hp1, while
  7254. modified, is still intact and might be optimised by the
  7255. SETcc optimisation below }
  7256. end;
  7257. end;
  7258. end;
  7259. end;
  7260. if taicpu(p).oper[0]^.typ = top_const then
  7261. begin
  7262. if (taicpu(p).oper[0]^.val = 0) and
  7263. (taicpu(p).oper[1]^.typ = top_reg) and
  7264. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7265. begin
  7266. hp2 := p;
  7267. FirstMatch := True;
  7268. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7269. anything meaningful once it's converted to "test %reg,%reg";
  7270. additionally, some jumps will always (or never) branch, so
  7271. evaluate every jump immediately following the
  7272. comparison, optimising the conditions if possible.
  7273. Similarly with SETcc... those that are always set to 0 or 1
  7274. are changed to MOV instructions }
  7275. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7276. (
  7277. GetNextInstruction(hp2, hp1) and
  7278. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7279. ) do
  7280. begin
  7281. FirstMatch := False;
  7282. case taicpu(hp1).condition of
  7283. C_B, C_C, C_NAE, C_O:
  7284. { For B/NAE:
  7285. Will never branch since an unsigned integer can never be below zero
  7286. For C/O:
  7287. Result cannot overflow because 0 is being subtracted
  7288. }
  7289. begin
  7290. if taicpu(hp1).opcode = A_Jcc then
  7291. begin
  7292. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7293. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7294. RemoveInstruction(hp1);
  7295. { Since hp1 was deleted, hp2 must not be updated }
  7296. Continue;
  7297. end
  7298. else
  7299. begin
  7300. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7301. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7302. taicpu(hp1).opcode := A_MOV;
  7303. taicpu(hp1).ops := 2;
  7304. taicpu(hp1).condition := C_None;
  7305. taicpu(hp1).opsize := S_B;
  7306. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7307. taicpu(hp1).loadconst(0, 0);
  7308. end;
  7309. end;
  7310. C_BE, C_NA:
  7311. begin
  7312. { Will only branch if equal to zero }
  7313. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7314. taicpu(hp1).condition := C_E;
  7315. end;
  7316. C_A, C_NBE:
  7317. begin
  7318. { Will only branch if not equal to zero }
  7319. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7320. taicpu(hp1).condition := C_NE;
  7321. end;
  7322. C_AE, C_NB, C_NC, C_NO:
  7323. begin
  7324. { Will always branch }
  7325. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7326. if taicpu(hp1).opcode = A_Jcc then
  7327. begin
  7328. MakeUnconditional(taicpu(hp1));
  7329. { Any jumps/set that follow will now be dead code }
  7330. RemoveDeadCodeAfterJump(taicpu(hp1));
  7331. Break;
  7332. end
  7333. else
  7334. begin
  7335. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7336. taicpu(hp1).opcode := A_MOV;
  7337. taicpu(hp1).ops := 2;
  7338. taicpu(hp1).condition := C_None;
  7339. taicpu(hp1).opsize := S_B;
  7340. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7341. taicpu(hp1).loadconst(0, 1);
  7342. end;
  7343. end;
  7344. C_None:
  7345. InternalError(2020012201);
  7346. C_P, C_PE, C_NP, C_PO:
  7347. { We can't handle parity checks and they should never be generated
  7348. after a general-purpose CMP (it's used in some floating-point
  7349. comparisons that don't use CMP) }
  7350. InternalError(2020012202);
  7351. else
  7352. { Zero/Equality, Sign, their complements and all of the
  7353. signed comparisons do not need to be converted };
  7354. end;
  7355. hp2 := hp1;
  7356. end;
  7357. { Convert the instruction to a TEST }
  7358. taicpu(p).opcode := A_TEST;
  7359. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7360. Result := True;
  7361. Exit;
  7362. end
  7363. else if (taicpu(p).oper[0]^.val = 1) and
  7364. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7365. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7366. begin
  7367. { Convert; To:
  7368. cmp $1,r/m cmp $0,r/m
  7369. jl @lbl jle @lbl
  7370. (Also do inverted conditions)
  7371. }
  7372. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7373. taicpu(p).oper[0]^.val := 0;
  7374. if taicpu(hp1).condition in [C_L, C_NGE] then
  7375. taicpu(hp1).condition := C_LE
  7376. else
  7377. taicpu(hp1).condition := C_NLE;
  7378. { If the instruction is now "cmp $0,%reg", convert it to a
  7379. TEST (and effectively do the work of the "cmp $0,%reg" in
  7380. the block above)
  7381. }
  7382. if (taicpu(p).oper[1]^.typ = top_reg) then
  7383. begin
  7384. taicpu(p).opcode := A_TEST;
  7385. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7386. end;
  7387. Result := True;
  7388. Exit;
  7389. end
  7390. else if (taicpu(p).oper[1]^.typ = top_reg)
  7391. {$ifdef x86_64}
  7392. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7393. {$endif x86_64}
  7394. then
  7395. begin
  7396. { cmp register,$8000 neg register
  7397. je target --> jo target
  7398. .... only if register is deallocated before jump.}
  7399. case Taicpu(p).opsize of
  7400. S_B: v:=$80;
  7401. S_W: v:=$8000;
  7402. S_L: v:=qword($80000000);
  7403. else
  7404. internalerror(2013112905);
  7405. end;
  7406. if (taicpu(p).oper[0]^.val=v) and
  7407. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7408. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7409. begin
  7410. TransferUsedRegs(TmpUsedRegs);
  7411. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7412. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7413. begin
  7414. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7415. Taicpu(p).opcode:=A_NEG;
  7416. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7417. Taicpu(p).clearop(1);
  7418. Taicpu(p).ops:=1;
  7419. if Taicpu(hp1).condition=C_E then
  7420. Taicpu(hp1).condition:=C_O
  7421. else
  7422. Taicpu(hp1).condition:=C_NO;
  7423. Result:=true;
  7424. exit;
  7425. end;
  7426. end;
  7427. end;
  7428. end;
  7429. if TrySwapMovCmp(p, hp1) then
  7430. begin
  7431. Result := True;
  7432. Exit;
  7433. end;
  7434. end;
  7435. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7436. var
  7437. hp1: tai;
  7438. begin
  7439. {
  7440. remove the second (v)pxor from
  7441. pxor reg,reg
  7442. ...
  7443. pxor reg,reg
  7444. }
  7445. Result:=false;
  7446. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7447. MatchOpType(taicpu(p),top_reg,top_reg) and
  7448. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7449. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7450. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7451. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7452. begin
  7453. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7454. RemoveInstruction(hp1);
  7455. Result:=true;
  7456. Exit;
  7457. end
  7458. {
  7459. replace
  7460. pxor reg1,reg1
  7461. movapd/s reg1,reg2
  7462. dealloc reg1
  7463. by
  7464. pxor reg2,reg2
  7465. }
  7466. else if GetNextInstruction(p,hp1) and
  7467. { we mix single and double opperations here because we assume that the compiler
  7468. generates vmovapd only after double operations and vmovaps only after single operations }
  7469. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7470. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7471. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7472. (taicpu(p).oper[0]^.typ=top_reg) then
  7473. begin
  7474. TransferUsedRegs(TmpUsedRegs);
  7475. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7476. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7477. begin
  7478. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7479. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7480. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7481. RemoveInstruction(hp1);
  7482. result:=true;
  7483. end;
  7484. end;
  7485. end;
  7486. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7487. var
  7488. hp1: tai;
  7489. begin
  7490. {
  7491. remove the second (v)pxor from
  7492. (v)pxor reg,reg
  7493. ...
  7494. (v)pxor reg,reg
  7495. }
  7496. Result:=false;
  7497. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7498. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7499. begin
  7500. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7501. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7502. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7503. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7504. begin
  7505. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7506. RemoveInstruction(hp1);
  7507. Result:=true;
  7508. Exit;
  7509. end;
  7510. {$ifdef x86_64}
  7511. {
  7512. replace
  7513. vpxor reg1,reg1,reg1
  7514. vmov reg,mem
  7515. by
  7516. movq $0,mem
  7517. }
  7518. if GetNextInstruction(p,hp1) and
  7519. MatchInstruction(hp1,A_VMOVSD,[]) and
  7520. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7521. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7522. begin
  7523. TransferUsedRegs(TmpUsedRegs);
  7524. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7525. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7526. begin
  7527. taicpu(hp1).loadconst(0,0);
  7528. taicpu(hp1).opcode:=A_MOV;
  7529. taicpu(hp1).opsize:=S_Q;
  7530. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7531. RemoveCurrentP(p);
  7532. result:=true;
  7533. Exit;
  7534. end;
  7535. end;
  7536. {$endif x86_64}
  7537. end
  7538. {
  7539. replace
  7540. vpxor reg1,reg1,reg2
  7541. by
  7542. vpxor reg2,reg2,reg2
  7543. to avoid unncessary data dependencies
  7544. }
  7545. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7546. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7547. begin
  7548. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7549. { avoid unncessary data dependency }
  7550. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7551. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7552. result:=true;
  7553. exit;
  7554. end;
  7555. Result:=OptPass1VOP(p);
  7556. end;
  7557. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7558. var
  7559. hp1 : tai;
  7560. begin
  7561. result:=false;
  7562. { replace
  7563. IMul const,%mreg1,%mreg2
  7564. Mov %reg2,%mreg3
  7565. dealloc %mreg3
  7566. by
  7567. Imul const,%mreg1,%mreg23
  7568. }
  7569. if (taicpu(p).ops=3) and
  7570. GetNextInstruction(p,hp1) and
  7571. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7572. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7573. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7574. begin
  7575. TransferUsedRegs(TmpUsedRegs);
  7576. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7577. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7578. begin
  7579. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7580. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7581. RemoveInstruction(hp1);
  7582. result:=true;
  7583. end;
  7584. end;
  7585. end;
  7586. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7587. var
  7588. hp1 : tai;
  7589. begin
  7590. result:=false;
  7591. { replace
  7592. IMul %reg0,%reg1,%reg2
  7593. Mov %reg2,%reg3
  7594. dealloc %reg2
  7595. by
  7596. Imul %reg0,%reg1,%reg3
  7597. }
  7598. if GetNextInstruction(p,hp1) and
  7599. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7600. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7601. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7602. begin
  7603. TransferUsedRegs(TmpUsedRegs);
  7604. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7605. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7606. begin
  7607. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7608. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7609. RemoveInstruction(hp1);
  7610. result:=true;
  7611. end;
  7612. end;
  7613. end;
  7614. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7615. var
  7616. hp1: tai;
  7617. begin
  7618. Result:=false;
  7619. { get rid of
  7620. (v)cvtss2sd reg0,<reg1,>reg2
  7621. (v)cvtss2sd reg2,<reg2,>reg0
  7622. }
  7623. if GetNextInstruction(p,hp1) and
  7624. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7625. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7626. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7627. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7628. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7629. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7630. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7631. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7632. )
  7633. ) then
  7634. begin
  7635. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7636. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7637. begin
  7638. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7639. RemoveCurrentP(p);
  7640. RemoveInstruction(hp1);
  7641. end
  7642. else
  7643. begin
  7644. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7645. if taicpu(hp1).opcode=A_CVTSD2SS then
  7646. begin
  7647. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7648. taicpu(p).opcode:=A_MOVAPS;
  7649. end
  7650. else
  7651. begin
  7652. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7653. taicpu(p).opcode:=A_VMOVAPS;
  7654. end;
  7655. taicpu(p).ops:=2;
  7656. RemoveInstruction(hp1);
  7657. end;
  7658. Result:=true;
  7659. Exit;
  7660. end;
  7661. end;
  7662. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7663. var
  7664. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7665. ThisReg: TRegister;
  7666. begin
  7667. Result := False;
  7668. if not GetNextInstruction(p,hp1) then
  7669. Exit;
  7670. {
  7671. convert
  7672. j<c> .L1
  7673. mov 1,reg
  7674. jmp .L2
  7675. .L1
  7676. mov 0,reg
  7677. .L2
  7678. into
  7679. mov 0,reg
  7680. set<not(c)> reg
  7681. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7682. would destroy the flag contents
  7683. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7684. executed at the same time as a previous comparison.
  7685. set<not(c)> reg
  7686. movzx reg, reg
  7687. }
  7688. if MatchInstruction(hp1,A_MOV,[]) and
  7689. (taicpu(hp1).oper[0]^.typ = top_const) and
  7690. (
  7691. (
  7692. (taicpu(hp1).oper[1]^.typ = top_reg)
  7693. {$ifdef i386}
  7694. { Under i386, ESI, EDI, EBP and ESP
  7695. don't have an 8-bit representation }
  7696. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7697. {$endif i386}
  7698. ) or (
  7699. {$ifdef i386}
  7700. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7701. {$endif i386}
  7702. (taicpu(hp1).opsize = S_B)
  7703. )
  7704. ) and
  7705. GetNextInstruction(hp1,hp2) and
  7706. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7707. GetNextInstruction(hp2,hp3) and
  7708. SkipAligns(hp3, hp3) and
  7709. (hp3.typ=ait_label) and
  7710. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7711. GetNextInstruction(hp3,hp4) and
  7712. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7713. (taicpu(hp4).oper[0]^.typ = top_const) and
  7714. (
  7715. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7716. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7717. ) and
  7718. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7719. GetNextInstruction(hp4,hp5) and
  7720. SkipAligns(hp5, hp5) and
  7721. (hp5.typ=ait_label) and
  7722. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7723. begin
  7724. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7725. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7726. tai_label(hp3).labsym.DecRefs;
  7727. { If this isn't the only reference to the middle label, we can
  7728. still make a saving - only that the first jump and everything
  7729. that follows will remain. }
  7730. if (tai_label(hp3).labsym.getrefs = 0) then
  7731. begin
  7732. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7733. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7734. else
  7735. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7736. { remove jump, first label and second MOV (also catching any aligns) }
  7737. repeat
  7738. if not GetNextInstruction(hp2, hp3) then
  7739. InternalError(2021040810);
  7740. RemoveInstruction(hp2);
  7741. hp2 := hp3;
  7742. until hp2 = hp5;
  7743. { Don't decrement reference count before the removal loop
  7744. above, otherwise GetNextInstruction won't stop on the
  7745. the label }
  7746. tai_label(hp5).labsym.DecRefs;
  7747. end
  7748. else
  7749. begin
  7750. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7751. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7752. else
  7753. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7754. end;
  7755. taicpu(p).opcode:=A_SETcc;
  7756. taicpu(p).opsize:=S_B;
  7757. taicpu(p).is_jmp:=False;
  7758. if taicpu(hp1).opsize=S_B then
  7759. begin
  7760. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7761. if taicpu(hp1).oper[1]^.typ = top_reg then
  7762. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7763. RemoveInstruction(hp1);
  7764. end
  7765. else
  7766. begin
  7767. { Will be a register because the size can't be S_B otherwise }
  7768. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7769. taicpu(p).loadreg(0, ThisReg);
  7770. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7771. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7772. begin
  7773. case taicpu(hp1).opsize of
  7774. S_W:
  7775. taicpu(hp1).opsize := S_BW;
  7776. S_L:
  7777. taicpu(hp1).opsize := S_BL;
  7778. {$ifdef x86_64}
  7779. S_Q:
  7780. begin
  7781. taicpu(hp1).opsize := S_BL;
  7782. { Change the destination register to 32-bit }
  7783. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7784. end;
  7785. {$endif x86_64}
  7786. else
  7787. InternalError(2021040820);
  7788. end;
  7789. taicpu(hp1).opcode := A_MOVZX;
  7790. taicpu(hp1).loadreg(0, ThisReg);
  7791. end
  7792. else
  7793. begin
  7794. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7795. { hp1 is already a MOV instruction with the correct register }
  7796. taicpu(hp1).loadconst(0, 0);
  7797. { Inserting it right before p will guarantee that the flags are also tracked }
  7798. asml.Remove(hp1);
  7799. asml.InsertBefore(hp1, p);
  7800. end;
  7801. end;
  7802. Result:=true;
  7803. exit;
  7804. end
  7805. else if (hp1.typ = ait_label) then
  7806. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7807. end;
  7808. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7809. var
  7810. hp1, hp2, hp3: tai;
  7811. SourceRef, TargetRef: TReference;
  7812. CurrentReg: TRegister;
  7813. begin
  7814. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7815. if not UseAVX then
  7816. InternalError(2021100501);
  7817. Result := False;
  7818. { Look for the following to simplify:
  7819. vmovdqa/u x(mem1), %xmmreg
  7820. vmovdqa/u %xmmreg, y(mem2)
  7821. vmovdqa/u x+16(mem1), %xmmreg
  7822. vmovdqa/u %xmmreg, y+16(mem2)
  7823. Change to:
  7824. vmovdqa/u x(mem1), %ymmreg
  7825. vmovdqa/u %ymmreg, y(mem2)
  7826. vpxor %ymmreg, %ymmreg, %ymmreg
  7827. ( The VPXOR instruction is to zero the upper half, thus removing the
  7828. need to call the potentially expensive VZEROUPPER instruction. Other
  7829. peephole optimisations can remove VPXOR if it's unnecessary )
  7830. }
  7831. TransferUsedRegs(TmpUsedRegs);
  7832. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7833. { NOTE: In the optimisations below, if the references dictate that an
  7834. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7835. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7836. if (taicpu(p).opsize = S_XMM) and
  7837. MatchOpType(taicpu(p), top_ref, top_reg) and
  7838. GetNextInstruction(p, hp1) and
  7839. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7840. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7841. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7842. begin
  7843. SourceRef := taicpu(p).oper[0]^.ref^;
  7844. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7845. if GetNextInstruction(hp1, hp2) and
  7846. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7847. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7848. begin
  7849. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7850. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7851. Inc(SourceRef.offset, 16);
  7852. { Reuse the register in the first block move }
  7853. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7854. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7855. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7856. begin
  7857. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7858. Inc(TargetRef.offset, 16);
  7859. if GetNextInstruction(hp2, hp3) and
  7860. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7861. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7862. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7863. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7864. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7865. begin
  7866. { Update the register tracking to the new size }
  7867. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7868. { Remember that the offsets are 16 ahead }
  7869. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7870. if not (
  7871. ((SourceRef.offset mod 32) = 16) and
  7872. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7873. ) then
  7874. taicpu(p).opcode := A_VMOVDQU;
  7875. taicpu(p).opsize := S_YMM;
  7876. taicpu(p).oper[1]^.reg := CurrentReg;
  7877. if not (
  7878. ((TargetRef.offset mod 32) = 16) and
  7879. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7880. ) then
  7881. taicpu(hp1).opcode := A_VMOVDQU;
  7882. taicpu(hp1).opsize := S_YMM;
  7883. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7884. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7885. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7886. if (pi_uses_ymm in current_procinfo.flags) then
  7887. RemoveInstruction(hp2)
  7888. else
  7889. begin
  7890. taicpu(hp2).opcode := A_VPXOR;
  7891. taicpu(hp2).opsize := S_YMM;
  7892. taicpu(hp2).loadreg(0, CurrentReg);
  7893. taicpu(hp2).loadreg(1, CurrentReg);
  7894. taicpu(hp2).loadreg(2, CurrentReg);
  7895. taicpu(hp2).ops := 3;
  7896. end;
  7897. RemoveInstruction(hp3);
  7898. Result := True;
  7899. Exit;
  7900. end;
  7901. end
  7902. else
  7903. begin
  7904. { See if the next references are 16 less rather than 16 greater }
  7905. Dec(SourceRef.offset, 32); { -16 the other way }
  7906. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7907. begin
  7908. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7909. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7910. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7911. GetNextInstruction(hp2, hp3) and
  7912. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7913. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7914. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7915. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7916. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7917. begin
  7918. { Update the register tracking to the new size }
  7919. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7920. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7921. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7922. if not(
  7923. ((SourceRef.offset mod 32) = 0) and
  7924. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7925. ) then
  7926. taicpu(hp2).opcode := A_VMOVDQU;
  7927. taicpu(hp2).opsize := S_YMM;
  7928. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7929. if not (
  7930. ((TargetRef.offset mod 32) = 0) and
  7931. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7932. ) then
  7933. taicpu(hp3).opcode := A_VMOVDQU;
  7934. taicpu(hp3).opsize := S_YMM;
  7935. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7936. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7937. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7938. if (pi_uses_ymm in current_procinfo.flags) then
  7939. RemoveInstruction(hp1)
  7940. else
  7941. begin
  7942. taicpu(hp1).opcode := A_VPXOR;
  7943. taicpu(hp1).opsize := S_YMM;
  7944. taicpu(hp1).loadreg(0, CurrentReg);
  7945. taicpu(hp1).loadreg(1, CurrentReg);
  7946. taicpu(hp1).loadreg(2, CurrentReg);
  7947. taicpu(hp1).ops := 3;
  7948. Asml.Remove(hp1);
  7949. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7950. end;
  7951. RemoveCurrentP(p, hp2);
  7952. Result := True;
  7953. Exit;
  7954. end;
  7955. end;
  7956. end;
  7957. end;
  7958. end;
  7959. end;
  7960. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7961. var
  7962. hp2, hp3, first_assignment: tai;
  7963. IncCount, OperIdx: Integer;
  7964. OrigLabel: TAsmLabel;
  7965. begin
  7966. Count := 0;
  7967. Result := False;
  7968. first_assignment := nil;
  7969. if (LoopCount >= 20) then
  7970. begin
  7971. { Guard against infinite loops }
  7972. Exit;
  7973. end;
  7974. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7975. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7976. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7977. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7978. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7979. Exit;
  7980. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7981. {
  7982. change
  7983. jmp .L1
  7984. ...
  7985. .L1:
  7986. mov ##, ## ( multiple movs possible )
  7987. jmp/ret
  7988. into
  7989. mov ##, ##
  7990. jmp/ret
  7991. }
  7992. if not Assigned(hp1) then
  7993. begin
  7994. hp1 := GetLabelWithSym(OrigLabel);
  7995. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7996. Exit;
  7997. end;
  7998. hp2 := hp1;
  7999. while Assigned(hp2) do
  8000. begin
  8001. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  8002. SkipLabels(hp2,hp2);
  8003. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8004. Break;
  8005. case taicpu(hp2).opcode of
  8006. A_MOVSD:
  8007. begin
  8008. if taicpu(hp2).ops = 0 then
  8009. { Wrong MOVSD }
  8010. Break;
  8011. Inc(Count);
  8012. if Count >= 5 then
  8013. { Too many to be worthwhile }
  8014. Break;
  8015. GetNextInstruction(hp2, hp2);
  8016. Continue;
  8017. end;
  8018. A_MOV,
  8019. A_MOVD,
  8020. A_MOVQ,
  8021. A_MOVSX,
  8022. {$ifdef x86_64}
  8023. A_MOVSXD,
  8024. {$endif x86_64}
  8025. A_MOVZX,
  8026. A_MOVAPS,
  8027. A_MOVUPS,
  8028. A_MOVSS,
  8029. A_MOVAPD,
  8030. A_MOVUPD,
  8031. A_MOVDQA,
  8032. A_MOVDQU,
  8033. A_VMOVSS,
  8034. A_VMOVAPS,
  8035. A_VMOVUPS,
  8036. A_VMOVSD,
  8037. A_VMOVAPD,
  8038. A_VMOVUPD,
  8039. A_VMOVDQA,
  8040. A_VMOVDQU:
  8041. begin
  8042. Inc(Count);
  8043. if Count >= 5 then
  8044. { Too many to be worthwhile }
  8045. Break;
  8046. GetNextInstruction(hp2, hp2);
  8047. Continue;
  8048. end;
  8049. A_JMP:
  8050. begin
  8051. { Guard against infinite loops }
  8052. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8053. Exit;
  8054. { Analyse this jump first in case it also duplicates assignments }
  8055. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8056. begin
  8057. { Something did change! }
  8058. Result := True;
  8059. Inc(Count, IncCount);
  8060. if Count >= 5 then
  8061. begin
  8062. { Too many to be worthwhile }
  8063. Exit;
  8064. end;
  8065. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8066. Break;
  8067. end;
  8068. Result := True;
  8069. Break;
  8070. end;
  8071. A_RET:
  8072. begin
  8073. Result := True;
  8074. Break;
  8075. end;
  8076. else
  8077. Break;
  8078. end;
  8079. end;
  8080. if Result then
  8081. begin
  8082. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8083. if Count = 0 then
  8084. begin
  8085. Result := False;
  8086. Exit;
  8087. end;
  8088. hp3 := p;
  8089. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8090. while True do
  8091. begin
  8092. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  8093. SkipLabels(hp1,hp1);
  8094. if (hp1.typ <> ait_instruction) then
  8095. InternalError(2021040720);
  8096. case taicpu(hp1).opcode of
  8097. A_JMP:
  8098. begin
  8099. { Change the original jump to the new destination }
  8100. OrigLabel.decrefs;
  8101. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8102. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8103. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8104. if not Assigned(first_assignment) then
  8105. InternalError(2021040810)
  8106. else
  8107. p := first_assignment;
  8108. Exit;
  8109. end;
  8110. A_RET:
  8111. begin
  8112. { Now change the jump into a RET instruction }
  8113. ConvertJumpToRET(p, hp1);
  8114. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8115. if not Assigned(first_assignment) then
  8116. InternalError(2021040811)
  8117. else
  8118. p := first_assignment;
  8119. Exit;
  8120. end;
  8121. else
  8122. begin
  8123. { Duplicate the MOV instruction }
  8124. hp3:=tai(hp1.getcopy);
  8125. if first_assignment = nil then
  8126. first_assignment := hp3;
  8127. asml.InsertBefore(hp3, p);
  8128. { Make sure the compiler knows about any final registers written here }
  8129. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8130. with taicpu(hp3).oper[OperIdx]^ do
  8131. begin
  8132. case typ of
  8133. top_ref:
  8134. begin
  8135. if (ref^.base <> NR_NO) and
  8136. (getsupreg(ref^.base) <> RS_ESP) and
  8137. (getsupreg(ref^.base) <> RS_EBP)
  8138. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8139. then
  8140. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8141. if (ref^.index <> NR_NO) and
  8142. (getsupreg(ref^.index) <> RS_ESP) and
  8143. (getsupreg(ref^.index) <> RS_EBP)
  8144. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8145. (ref^.index <> ref^.base) then
  8146. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8147. end;
  8148. top_reg:
  8149. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8150. else
  8151. ;
  8152. end;
  8153. end;
  8154. end;
  8155. end;
  8156. if not GetNextInstruction(hp1, hp1) then
  8157. { Should have dropped out earlier }
  8158. InternalError(2021040710);
  8159. end;
  8160. end;
  8161. end;
  8162. const
  8163. WriteOp: array[0..3] of set of TInsChange = (
  8164. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8165. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8166. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8167. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8168. RegWriteFlags: array[0..7] of set of TInsChange = (
  8169. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8170. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8171. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8172. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8173. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8174. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8175. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8176. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8177. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8178. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8179. var
  8180. hp2: tai;
  8181. X: Integer;
  8182. begin
  8183. { If we have something like:
  8184. op ###,###
  8185. mov ###,###
  8186. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8187. interfere in regards to what they write to.
  8188. NOTE: p must be a 2-operand instruction
  8189. }
  8190. Result := False;
  8191. if (hp1.typ <> ait_instruction) or
  8192. taicpu(hp1).is_jmp or
  8193. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8194. Exit;
  8195. { NOP is a pipeline fence, likely marking the beginning of the function
  8196. epilogue, so drop out. Similarly, drop out if POP or RET are
  8197. encountered }
  8198. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8199. Exit;
  8200. if (taicpu(hp1).opcode = A_MOVSD) and
  8201. (taicpu(hp1).ops = 0) then
  8202. { Wrong MOVSD }
  8203. Exit;
  8204. { Check for writes to specific registers first }
  8205. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8206. for X := 0 to 7 do
  8207. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8208. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8209. Exit;
  8210. for X := 0 to taicpu(hp1).ops - 1 do
  8211. begin
  8212. { Check to see if this operand writes to something }
  8213. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8214. { And matches something in the CMP/TEST instruction }
  8215. (
  8216. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8217. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8218. (
  8219. { If it's a register, make sure the register written to doesn't
  8220. appear in the cmp instruction as part of a reference }
  8221. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8222. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8223. )
  8224. ) then
  8225. Exit;
  8226. end;
  8227. { Check p to make sure it doesn't write to something that affects hp1 }
  8228. { Check for writes to specific registers first }
  8229. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8230. for X := 0 to 7 do
  8231. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8232. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8233. Exit;
  8234. for X := 0 to taicpu(p).ops - 1 do
  8235. begin
  8236. { Check to see if this operand writes to something }
  8237. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8238. { And matches something in hp1 }
  8239. (taicpu(p).oper[X]^.typ = top_reg) and
  8240. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8241. Exit;
  8242. end;
  8243. { The instruction can be safely moved }
  8244. asml.Remove(hp1);
  8245. { Try to insert after the last instructions where the FLAGS register is not
  8246. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8247. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8248. asml.InsertBefore(hp1, hp2)
  8249. { Failing that, try to insert after the last instructions where the
  8250. FLAGS register is not yet in use }
  8251. else if GetLastInstruction(p, hp2) and
  8252. (
  8253. (hp2.typ <> ait_instruction) or
  8254. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8255. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8256. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8257. ) then
  8258. asml.InsertAfter(hp1, hp2)
  8259. else
  8260. { Note, if p.Previous is nil (even if it should logically never be the
  8261. case), FindRegAllocBackward immediately exits with False and so we
  8262. safely land here (we can't just pass p because FindRegAllocBackward
  8263. immediately exits on an instruction). [Kit] }
  8264. asml.InsertBefore(hp1, p);
  8265. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8266. { We can't trust UsedRegs because we're looking backwards, although we
  8267. know the registers are allocated after p at the very least, so manually
  8268. create tai_regalloc objects if needed }
  8269. for X := 0 to taicpu(hp1).ops - 1 do
  8270. case taicpu(hp1).oper[X]^.typ of
  8271. top_reg:
  8272. begin
  8273. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8274. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8275. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8276. end;
  8277. top_ref:
  8278. begin
  8279. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8280. begin
  8281. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8282. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8283. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8284. end;
  8285. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8286. begin
  8287. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8288. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8289. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8290. end;
  8291. end;
  8292. else
  8293. ;
  8294. end;
  8295. Result := True;
  8296. end;
  8297. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8298. var
  8299. hp2: tai;
  8300. X: Integer;
  8301. begin
  8302. { If we have something like:
  8303. cmp ###,%reg1
  8304. mov 0,%reg2
  8305. And no modified registers are shared, move the instruction to before
  8306. the comparison as this means it can be optimised without worrying
  8307. about the FLAGS register. (CMP/MOV is generated by
  8308. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8309. As long as the second instruction doesn't use the flags or one of the
  8310. registers used by CMP or TEST (also check any references that use the
  8311. registers), then it can be moved prior to the comparison.
  8312. }
  8313. Result := False;
  8314. if not TrySwapMovOp(p, hp1) then
  8315. Exit;
  8316. if taicpu(hp1).opcode = A_LEA then
  8317. { The flags will be overwritten by the CMP/TEST instruction }
  8318. ConvertLEA(taicpu(hp1));
  8319. Result := True;
  8320. { Can we move it one further back? }
  8321. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8322. { Check to see if CMP/TEST is a comparison against zero }
  8323. (
  8324. (
  8325. (taicpu(p).opcode = A_CMP) and
  8326. MatchOperand(taicpu(p).oper[0]^, 0)
  8327. ) or
  8328. (
  8329. (taicpu(p).opcode = A_TEST) and
  8330. (
  8331. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8332. MatchOperand(taicpu(p).oper[0]^, -1)
  8333. )
  8334. )
  8335. ) and
  8336. { These instructions set the zero flag if the result is zero }
  8337. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8338. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8339. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8340. TrySwapMovOp(hp2, hp1);
  8341. end;
  8342. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8343. function IsXCHGAcceptable: Boolean; inline;
  8344. begin
  8345. { Always accept if optimising for size }
  8346. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8347. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8348. than 3, so it becomes a saving compared to three MOVs with two of
  8349. them able to execute simultaneously. [Kit] }
  8350. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8351. end;
  8352. var
  8353. NewRef: TReference;
  8354. hp1, hp2, hp3, hp4: Tai;
  8355. {$ifndef x86_64}
  8356. OperIdx: Integer;
  8357. {$endif x86_64}
  8358. NewInstr : Taicpu;
  8359. NewAligh : Tai_align;
  8360. DestLabel: TAsmLabel;
  8361. TempTracking: TAllUsedRegs;
  8362. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8363. var
  8364. NextInstr: tai;
  8365. begin
  8366. Result := False;
  8367. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8368. if not GetNextInstruction(InputInstr, NextInstr) or
  8369. (
  8370. { The FLAGS register isn't always tracked properly, so do not
  8371. perform this optimisation if a conditional statement follows }
  8372. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8373. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8374. ) then
  8375. begin
  8376. reference_reset(NewRef, 1, []);
  8377. NewRef.base := taicpu(p).oper[0]^.reg;
  8378. NewRef.scalefactor := 1;
  8379. if taicpu(InputInstr).opcode = A_ADD then
  8380. begin
  8381. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8382. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8383. end
  8384. else
  8385. begin
  8386. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8387. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8388. end;
  8389. taicpu(p).opcode := A_LEA;
  8390. taicpu(p).loadref(0, NewRef);
  8391. RemoveInstruction(InputInstr);
  8392. Result := True;
  8393. end;
  8394. end;
  8395. begin
  8396. Result:=false;
  8397. { This optimisation adds an instruction, so only do it for speed }
  8398. if not (cs_opt_size in current_settings.optimizerswitches) and
  8399. MatchOpType(taicpu(p), top_const, top_reg) and
  8400. (taicpu(p).oper[0]^.val = 0) then
  8401. begin
  8402. { To avoid compiler warning }
  8403. DestLabel := nil;
  8404. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8405. InternalError(2021040750);
  8406. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8407. Exit;
  8408. case hp1.typ of
  8409. ait_align,
  8410. ait_label:
  8411. begin
  8412. { Change:
  8413. mov $0,%reg mov $0,%reg
  8414. @Lbl1: @Lbl1:
  8415. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8416. je @Lbl2 jne @Lbl2
  8417. To: To:
  8418. mov $0,%reg mov $0,%reg
  8419. jmp @Lbl2 jmp @Lbl3
  8420. (align) (align)
  8421. @Lbl1: @Lbl1:
  8422. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8423. je @Lbl2 je @Lbl2
  8424. @Lbl3: <-- Only if label exists
  8425. (Not if it's optimised for size)
  8426. }
  8427. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8428. Exit;
  8429. if (hp2.typ = ait_instruction) and
  8430. (
  8431. { Register sizes must exactly match }
  8432. (
  8433. (taicpu(hp2).opcode = A_CMP) and
  8434. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8435. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8436. ) or (
  8437. (taicpu(hp2).opcode = A_TEST) and
  8438. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8439. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8440. )
  8441. ) and GetNextInstruction(hp2, hp3) and
  8442. (hp3.typ = ait_instruction) and
  8443. (taicpu(hp3).opcode = A_JCC) and
  8444. (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
  8445. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8446. begin
  8447. { Check condition of jump }
  8448. { Always true? }
  8449. if condition_in(C_E, taicpu(hp3).condition) then
  8450. begin
  8451. { Copy label symbol and obtain matching label entry for the
  8452. conditional jump, as this will be our destination}
  8453. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8454. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8455. Result := True;
  8456. end
  8457. { Always false? }
  8458. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8459. begin
  8460. { This is only worth it if there's a jump to take }
  8461. case hp2.typ of
  8462. ait_instruction:
  8463. begin
  8464. if taicpu(hp2).opcode = A_JMP then
  8465. begin
  8466. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8467. { An unconditional jump follows the conditional jump which will always be false,
  8468. so use this jump's destination for the new jump }
  8469. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8470. Result := True;
  8471. end
  8472. else if taicpu(hp2).opcode = A_JCC then
  8473. begin
  8474. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8475. if condition_in(C_E, taicpu(hp2).condition) then
  8476. begin
  8477. { A second conditional jump follows the conditional jump which will always be false,
  8478. while the second jump is always True, so use this jump's destination for the new jump }
  8479. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8480. Result := True;
  8481. end;
  8482. { Don't risk it if the jump isn't always true (Result remains False) }
  8483. end;
  8484. end;
  8485. else
  8486. { If anything else don't optimise };
  8487. end;
  8488. end;
  8489. if Result then
  8490. begin
  8491. { Just so we have something to insert as a paremeter}
  8492. reference_reset(NewRef, 1, []);
  8493. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8494. { Now actually load the correct parameter (this also
  8495. increases the reference count) }
  8496. NewInstr.loadsymbol(0, DestLabel, 0);
  8497. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8498. begin
  8499. { Get instruction before original label (may not be p under -O3) }
  8500. if not GetLastInstruction(hp1, hp2) then
  8501. { Shouldn't fail here }
  8502. InternalError(2021040701);
  8503. { Before the aligns too }
  8504. while (hp2.typ = ait_align) do
  8505. if not GetLastInstruction(hp2, hp2) then
  8506. { Shouldn't fail here }
  8507. InternalError(2021040702);
  8508. end
  8509. else
  8510. hp2 := p;
  8511. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8512. AsmL.InsertAfter(NewInstr, hp2);
  8513. { Add new alignment field }
  8514. (* AsmL.InsertAfter(
  8515. cai_align.create_max(
  8516. current_settings.alignment.jumpalign,
  8517. current_settings.alignment.jumpalignskipmax
  8518. ),
  8519. NewInstr
  8520. ); *)
  8521. end;
  8522. Exit;
  8523. end;
  8524. end;
  8525. else
  8526. ;
  8527. end;
  8528. end;
  8529. if not GetNextInstruction(p, hp1) then
  8530. Exit;
  8531. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8532. and DoMovCmpMemOpt(p, hp1) then
  8533. begin
  8534. Result := True;
  8535. Exit;
  8536. end
  8537. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8538. begin
  8539. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8540. further, but we can't just put this jump optimisation in pass 1
  8541. because it tends to perform worse when conditional jumps are
  8542. nearby (e.g. when converting CMOV instructions). [Kit] }
  8543. CopyUsedRegs(TempTracking);
  8544. UpdateUsedRegs(tai(p.Next));
  8545. if OptPass2JMP(hp1) then
  8546. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8547. Result := OptPass1MOV(p);
  8548. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8549. returned True and the instruction is still a MOV, thus checking
  8550. the optimisations below }
  8551. { If OptPass2JMP returned False, no optimisations were done to
  8552. the jump and there are no further optimisations that can be done
  8553. to the MOV instruction on this pass }
  8554. { Restore register state }
  8555. RestoreUsedRegs(TempTracking);
  8556. ReleaseUsedRegs(TempTracking);
  8557. end
  8558. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8559. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8560. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8561. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8562. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8563. begin
  8564. { Change:
  8565. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8566. addl/q $x,%reg2 subl/q $x,%reg2
  8567. To:
  8568. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8569. }
  8570. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8571. { be lazy, checking separately for sub would be slightly better }
  8572. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8573. begin
  8574. TransferUsedRegs(TmpUsedRegs);
  8575. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8576. if TryMovArith2Lea(hp1) then
  8577. begin
  8578. Result := True;
  8579. Exit;
  8580. end
  8581. end
  8582. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8583. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8584. { Same as above, but also adds or subtracts to %reg2 in between.
  8585. It's still valid as long as the flags aren't in use }
  8586. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8587. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8588. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8589. { be lazy, checking separately for sub would be slightly better }
  8590. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8591. begin
  8592. TransferUsedRegs(TmpUsedRegs);
  8593. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8594. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8595. if TryMovArith2Lea(hp2) then
  8596. begin
  8597. Result := True;
  8598. Exit;
  8599. end;
  8600. end;
  8601. end
  8602. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8603. {$ifdef x86_64}
  8604. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8605. {$else x86_64}
  8606. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8607. {$endif x86_64}
  8608. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8609. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8610. { mov reg1, reg2 mov reg1, reg2
  8611. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8612. begin
  8613. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8614. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8615. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8616. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8617. TransferUsedRegs(TmpUsedRegs);
  8618. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8619. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8620. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8621. then
  8622. begin
  8623. RemoveCurrentP(p, hp1);
  8624. Result:=true;
  8625. end;
  8626. exit;
  8627. end
  8628. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8629. IsXCHGAcceptable and
  8630. { XCHG doesn't support 8-byte registers }
  8631. (taicpu(p).opsize <> S_B) and
  8632. MatchInstruction(hp1, A_MOV, []) and
  8633. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8634. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8635. GetNextInstruction(hp1, hp2) and
  8636. MatchInstruction(hp2, A_MOV, []) and
  8637. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8638. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8639. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8640. begin
  8641. { mov %reg1,%reg2
  8642. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8643. mov %reg2,%reg3
  8644. (%reg2 not used afterwards)
  8645. Note that xchg takes 3 cycles to execute, and generally mov's take
  8646. only one cycle apiece, but the first two mov's can be executed in
  8647. parallel, only taking 2 cycles overall. Older processors should
  8648. therefore only optimise for size. [Kit]
  8649. }
  8650. TransferUsedRegs(TmpUsedRegs);
  8651. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8652. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8653. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8654. begin
  8655. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8656. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8657. taicpu(hp1).opcode := A_XCHG;
  8658. RemoveCurrentP(p, hp1);
  8659. RemoveInstruction(hp2);
  8660. Result := True;
  8661. Exit;
  8662. end;
  8663. end
  8664. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8665. MatchInstruction(hp1, A_SAR, []) then
  8666. begin
  8667. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8668. begin
  8669. { the use of %edx also covers the opsize being S_L }
  8670. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8671. begin
  8672. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8673. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8674. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8675. begin
  8676. { Change:
  8677. movl %eax,%edx
  8678. sarl $31,%edx
  8679. To:
  8680. cltd
  8681. }
  8682. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8683. RemoveInstruction(hp1);
  8684. taicpu(p).opcode := A_CDQ;
  8685. taicpu(p).opsize := S_NO;
  8686. taicpu(p).clearop(1);
  8687. taicpu(p).clearop(0);
  8688. taicpu(p).ops:=0;
  8689. Result := True;
  8690. end
  8691. else if (cs_opt_size in current_settings.optimizerswitches) and
  8692. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8693. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8694. begin
  8695. { Change:
  8696. movl %edx,%eax
  8697. sarl $31,%edx
  8698. To:
  8699. movl %edx,%eax
  8700. cltd
  8701. Note that this creates a dependency between the two instructions,
  8702. so only perform if optimising for size.
  8703. }
  8704. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8705. taicpu(hp1).opcode := A_CDQ;
  8706. taicpu(hp1).opsize := S_NO;
  8707. taicpu(hp1).clearop(1);
  8708. taicpu(hp1).clearop(0);
  8709. taicpu(hp1).ops:=0;
  8710. end;
  8711. {$ifndef x86_64}
  8712. end
  8713. { Don't bother if CMOV is supported, because a more optimal
  8714. sequence would have been generated for the Abs() intrinsic }
  8715. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8716. { the use of %eax also covers the opsize being S_L }
  8717. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8718. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8719. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8720. GetNextInstruction(hp1, hp2) and
  8721. MatchInstruction(hp2, A_XOR, [S_L]) and
  8722. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8723. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8724. GetNextInstruction(hp2, hp3) and
  8725. MatchInstruction(hp3, A_SUB, [S_L]) and
  8726. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8727. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8728. begin
  8729. { Change:
  8730. movl %eax,%edx
  8731. sarl $31,%eax
  8732. xorl %eax,%edx
  8733. subl %eax,%edx
  8734. (Instruction that uses %edx)
  8735. (%eax deallocated)
  8736. (%edx deallocated)
  8737. To:
  8738. cltd
  8739. xorl %edx,%eax <-- Note the registers have swapped
  8740. subl %edx,%eax
  8741. (Instruction that uses %eax) <-- %eax rather than %edx
  8742. }
  8743. TransferUsedRegs(TmpUsedRegs);
  8744. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8745. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8746. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8747. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8748. begin
  8749. if GetNextInstruction(hp3, hp4) and
  8750. not RegModifiedByInstruction(NR_EDX, hp4) and
  8751. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8752. begin
  8753. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8754. taicpu(p).opcode := A_CDQ;
  8755. taicpu(p).clearop(1);
  8756. taicpu(p).clearop(0);
  8757. taicpu(p).ops:=0;
  8758. RemoveInstruction(hp1);
  8759. taicpu(hp2).loadreg(0, NR_EDX);
  8760. taicpu(hp2).loadreg(1, NR_EAX);
  8761. taicpu(hp3).loadreg(0, NR_EDX);
  8762. taicpu(hp3).loadreg(1, NR_EAX);
  8763. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8764. { Convert references in the following instruction (hp4) from %edx to %eax }
  8765. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8766. with taicpu(hp4).oper[OperIdx]^ do
  8767. case typ of
  8768. top_reg:
  8769. if getsupreg(reg) = RS_EDX then
  8770. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8771. top_ref:
  8772. begin
  8773. if getsupreg(reg) = RS_EDX then
  8774. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8775. if getsupreg(reg) = RS_EDX then
  8776. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8777. end;
  8778. else
  8779. ;
  8780. end;
  8781. end;
  8782. end;
  8783. {$else x86_64}
  8784. end;
  8785. end
  8786. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8787. { the use of %rdx also covers the opsize being S_Q }
  8788. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8789. begin
  8790. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8791. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8792. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8793. begin
  8794. { Change:
  8795. movq %rax,%rdx
  8796. sarq $63,%rdx
  8797. To:
  8798. cqto
  8799. }
  8800. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8801. RemoveInstruction(hp1);
  8802. taicpu(p).opcode := A_CQO;
  8803. taicpu(p).opsize := S_NO;
  8804. taicpu(p).clearop(1);
  8805. taicpu(p).clearop(0);
  8806. taicpu(p).ops:=0;
  8807. Result := True;
  8808. end
  8809. else if (cs_opt_size in current_settings.optimizerswitches) and
  8810. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8811. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8812. begin
  8813. { Change:
  8814. movq %rdx,%rax
  8815. sarq $63,%rdx
  8816. To:
  8817. movq %rdx,%rax
  8818. cqto
  8819. Note that this creates a dependency between the two instructions,
  8820. so only perform if optimising for size.
  8821. }
  8822. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8823. taicpu(hp1).opcode := A_CQO;
  8824. taicpu(hp1).opsize := S_NO;
  8825. taicpu(hp1).clearop(1);
  8826. taicpu(hp1).clearop(0);
  8827. taicpu(hp1).ops:=0;
  8828. {$endif x86_64}
  8829. end;
  8830. end;
  8831. end
  8832. else if MatchInstruction(hp1, A_MOV, []) and
  8833. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8834. { Though "GetNextInstruction" could be factored out, along with
  8835. the instructions that depend on hp2, it is an expensive call that
  8836. should be delayed for as long as possible, hence we do cheaper
  8837. checks first that are likely to be False. [Kit] }
  8838. begin
  8839. if (
  8840. (
  8841. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8842. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8843. (
  8844. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8845. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8846. )
  8847. ) or
  8848. (
  8849. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8850. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8851. (
  8852. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8853. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8854. )
  8855. )
  8856. ) and
  8857. GetNextInstruction(hp1, hp2) and
  8858. MatchInstruction(hp2, A_SAR, []) and
  8859. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8860. begin
  8861. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8862. begin
  8863. { Change:
  8864. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8865. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8866. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8867. To:
  8868. movl r/m,%eax <- Note the change in register
  8869. cltd
  8870. }
  8871. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8872. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8873. taicpu(p).loadreg(1, NR_EAX);
  8874. taicpu(hp1).opcode := A_CDQ;
  8875. taicpu(hp1).clearop(1);
  8876. taicpu(hp1).clearop(0);
  8877. taicpu(hp1).ops:=0;
  8878. RemoveInstruction(hp2);
  8879. (*
  8880. {$ifdef x86_64}
  8881. end
  8882. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8883. { This code sequence does not get generated - however it might become useful
  8884. if and when 128-bit signed integer types make an appearance, so the code
  8885. is kept here for when it is eventually needed. [Kit] }
  8886. (
  8887. (
  8888. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8889. (
  8890. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8891. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8892. )
  8893. ) or
  8894. (
  8895. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8896. (
  8897. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8898. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8899. )
  8900. )
  8901. ) and
  8902. GetNextInstruction(hp1, hp2) and
  8903. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8904. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8905. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8906. begin
  8907. { Change:
  8908. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8909. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8910. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8911. To:
  8912. movq r/m,%rax <- Note the change in register
  8913. cqto
  8914. }
  8915. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8916. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8917. taicpu(p).loadreg(1, NR_RAX);
  8918. taicpu(hp1).opcode := A_CQO;
  8919. taicpu(hp1).clearop(1);
  8920. taicpu(hp1).clearop(0);
  8921. taicpu(hp1).ops:=0;
  8922. RemoveInstruction(hp2);
  8923. {$endif x86_64}
  8924. *)
  8925. end;
  8926. end;
  8927. {$ifdef x86_64}
  8928. end
  8929. else if (taicpu(p).opsize = S_L) and
  8930. (taicpu(p).oper[1]^.typ = top_reg) and
  8931. (
  8932. MatchInstruction(hp1, A_MOV,[]) and
  8933. (taicpu(hp1).opsize = S_L) and
  8934. (taicpu(hp1).oper[1]^.typ = top_reg)
  8935. ) and (
  8936. GetNextInstruction(hp1, hp2) and
  8937. (tai(hp2).typ=ait_instruction) and
  8938. (taicpu(hp2).opsize = S_Q) and
  8939. (
  8940. (
  8941. MatchInstruction(hp2, A_ADD,[]) and
  8942. (taicpu(hp2).opsize = S_Q) and
  8943. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8944. (
  8945. (
  8946. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8947. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8948. ) or (
  8949. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8950. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8951. )
  8952. )
  8953. ) or (
  8954. MatchInstruction(hp2, A_LEA,[]) and
  8955. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8956. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8957. (
  8958. (
  8959. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8960. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8961. ) or (
  8962. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8963. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8964. )
  8965. ) and (
  8966. (
  8967. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8968. ) or (
  8969. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8970. )
  8971. )
  8972. )
  8973. )
  8974. ) and (
  8975. GetNextInstruction(hp2, hp3) and
  8976. MatchInstruction(hp3, A_SHR,[]) and
  8977. (taicpu(hp3).opsize = S_Q) and
  8978. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8979. (taicpu(hp3).oper[0]^.val = 1) and
  8980. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8981. ) then
  8982. begin
  8983. { Change movl x, reg1d movl x, reg1d
  8984. movl y, reg2d movl y, reg2d
  8985. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8986. shrq $1, reg1q shrq $1, reg1q
  8987. ( reg1d and reg2d can be switched around in the first two instructions )
  8988. To movl x, reg1d
  8989. addl y, reg1d
  8990. rcrl $1, reg1d
  8991. This corresponds to the common expression (x + y) shr 1, where
  8992. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  8993. smaller code, but won't account for x + y causing an overflow). [Kit]
  8994. }
  8995. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  8996. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8997. { Change first MOV command to have the same register as the final output }
  8998. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  8999. else
  9000. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9001. { Change second MOV command to an ADD command. This is easier than
  9002. converting the existing command because it means we don't have to
  9003. touch 'y', which might be a complicated reference, and also the
  9004. fact that the third command might either be ADD or LEA. [Kit] }
  9005. taicpu(hp1).opcode := A_ADD;
  9006. { Delete old ADD/LEA instruction }
  9007. RemoveInstruction(hp2);
  9008. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9009. taicpu(hp3).opcode := A_RCR;
  9010. taicpu(hp3).changeopsize(S_L);
  9011. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9012. {$endif x86_64}
  9013. end;
  9014. if FuncMov2Func(p, hp1) then
  9015. begin
  9016. Result := True;
  9017. Exit;
  9018. end;
  9019. end;
  9020. {$push}
  9021. {$q-}{$r-}
  9022. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9023. var
  9024. ThisReg: TRegister;
  9025. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9026. TargetSubReg: TSubRegister;
  9027. hp1, hp2: tai;
  9028. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9029. { Store list of found instructions so we don't have to call
  9030. GetNextInstructionUsingReg multiple times }
  9031. InstrList: array of taicpu;
  9032. InstrMax, Index: Integer;
  9033. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9034. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9035. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9036. WorkingValue: TCgInt;
  9037. PreMessage: string;
  9038. { Data flow analysis }
  9039. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9040. BitwiseOnly, OrXorUsed,
  9041. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9042. function CheckOverflowConditions: Boolean;
  9043. begin
  9044. Result := True;
  9045. if (TestValSignedMax > SignedUpperLimit) then
  9046. UpperSignedOverflow := True;
  9047. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9048. LowerSignedOverflow := True;
  9049. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9050. LowerUnsignedOverflow := True;
  9051. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9052. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9053. begin
  9054. { Absolute overflow }
  9055. Result := False;
  9056. Exit;
  9057. end;
  9058. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9059. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9060. ShiftDownOverflow := True;
  9061. if (TestValMin < 0) or (TestValMax < 0) then
  9062. begin
  9063. LowerUnsignedOverflow := True;
  9064. UpperUnsignedOverflow := True;
  9065. end;
  9066. end;
  9067. function AdjustInitialLoadAndSize: Boolean;
  9068. begin
  9069. Result := False;
  9070. if not p_removed then
  9071. begin
  9072. if TargetSize = MinSize then
  9073. begin
  9074. { Convert the input MOVZX to a MOV }
  9075. if (taicpu(p).oper[0]^.typ = top_reg) and
  9076. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9077. begin
  9078. { Or remove it completely! }
  9079. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9080. RemoveCurrentP(p);
  9081. p_removed := True;
  9082. end
  9083. else
  9084. begin
  9085. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9086. taicpu(p).opcode := A_MOV;
  9087. taicpu(p).oper[1]^.reg := ThisReg;
  9088. taicpu(p).opsize := TargetSize;
  9089. end;
  9090. Result := True;
  9091. end
  9092. else if TargetSize <> MaxSize then
  9093. begin
  9094. case MaxSize of
  9095. S_L:
  9096. if TargetSize = S_W then
  9097. begin
  9098. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9099. taicpu(p).opsize := S_BW;
  9100. taicpu(p).oper[1]^.reg := ThisReg;
  9101. Result := True;
  9102. end
  9103. else
  9104. InternalError(2020112341);
  9105. S_W:
  9106. if TargetSize = S_L then
  9107. begin
  9108. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9109. taicpu(p).opsize := S_BL;
  9110. taicpu(p).oper[1]^.reg := ThisReg;
  9111. Result := True;
  9112. end
  9113. else
  9114. InternalError(2020112342);
  9115. else
  9116. ;
  9117. end;
  9118. end
  9119. else if not hp1_removed and not RegInUse then
  9120. begin
  9121. { If we have something like:
  9122. movzbl (oper),%regd
  9123. add x, %regd
  9124. movzbl %regb, %regd
  9125. We can reduce the register size to the input of the final
  9126. movzbl instruction. Overflows won't have any effect.
  9127. }
  9128. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9129. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9130. begin
  9131. TargetSize := S_B;
  9132. setsubreg(ThisReg, R_SUBL);
  9133. Result := True;
  9134. end
  9135. else if (taicpu(p).opsize = S_WL) and
  9136. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9137. begin
  9138. TargetSize := S_W;
  9139. setsubreg(ThisReg, R_SUBW);
  9140. Result := True;
  9141. end;
  9142. if Result then
  9143. begin
  9144. { Convert the input MOVZX to a MOV }
  9145. if (taicpu(p).oper[0]^.typ = top_reg) and
  9146. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9147. begin
  9148. { Or remove it completely! }
  9149. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9150. RemoveCurrentP(p);
  9151. p_removed := True;
  9152. end
  9153. else
  9154. begin
  9155. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9156. taicpu(p).opcode := A_MOV;
  9157. taicpu(p).oper[1]^.reg := ThisReg;
  9158. taicpu(p).opsize := TargetSize;
  9159. end;
  9160. end;
  9161. end;
  9162. end;
  9163. end;
  9164. procedure AdjustFinalLoad;
  9165. begin
  9166. if not LowerUnsignedOverflow then
  9167. begin
  9168. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9169. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9170. begin
  9171. { Convert the output MOVZX to a MOV }
  9172. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9173. begin
  9174. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9175. if (MinSize = S_B) or
  9176. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9177. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9178. begin
  9179. { Remove it completely! }
  9180. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9181. { Be careful; if p = hp1 and p was also removed, p
  9182. will become a dangling pointer }
  9183. if p = hp1 then
  9184. begin
  9185. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9186. p_removed := True;
  9187. end
  9188. else
  9189. RemoveInstruction(hp1);
  9190. hp1_removed := True;
  9191. end;
  9192. end
  9193. else
  9194. begin
  9195. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9196. taicpu(hp1).opcode := A_MOV;
  9197. taicpu(hp1).oper[0]^.reg := ThisReg;
  9198. taicpu(hp1).opsize := TargetSize;
  9199. end;
  9200. end
  9201. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9202. begin
  9203. { Need to change the size of the output }
  9204. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9205. taicpu(hp1).oper[0]^.reg := ThisReg;
  9206. taicpu(hp1).opsize := S_BL;
  9207. end;
  9208. end;
  9209. end;
  9210. function CompressInstructions: Boolean;
  9211. var
  9212. LocalIndex: Integer;
  9213. begin
  9214. Result := False;
  9215. { The objective here is to try to find a combination that
  9216. removes one of the MOV/Z instructions. }
  9217. if (
  9218. (taicpu(p).oper[0]^.typ <> top_reg) or
  9219. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9220. ) and
  9221. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9222. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9223. begin
  9224. { Make a preference to remove the second MOVZX instruction }
  9225. case taicpu(hp1).opsize of
  9226. S_BL, S_WL:
  9227. begin
  9228. TargetSize := S_L;
  9229. TargetSubReg := R_SUBD;
  9230. end;
  9231. S_BW:
  9232. begin
  9233. TargetSize := S_W;
  9234. TargetSubReg := R_SUBW;
  9235. end;
  9236. else
  9237. InternalError(2020112302);
  9238. end;
  9239. end
  9240. else
  9241. begin
  9242. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9243. begin
  9244. { Exceeded lower bound but not upper bound }
  9245. TargetSize := MaxSize;
  9246. end
  9247. else if not LowerUnsignedOverflow then
  9248. begin
  9249. { Size didn't exceed lower bound }
  9250. TargetSize := MinSize;
  9251. end
  9252. else
  9253. Exit;
  9254. end;
  9255. case TargetSize of
  9256. S_B:
  9257. TargetSubReg := R_SUBL;
  9258. S_W:
  9259. TargetSubReg := R_SUBW;
  9260. S_L:
  9261. TargetSubReg := R_SUBD;
  9262. else
  9263. InternalError(2020112350);
  9264. end;
  9265. { Update the register to its new size }
  9266. setsubreg(ThisReg, TargetSubReg);
  9267. RegInUse := False;
  9268. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9269. begin
  9270. { Check to see if the active register is used afterwards;
  9271. if not, we can change it and make a saving. }
  9272. TransferUsedRegs(TmpUsedRegs);
  9273. { The target register may be marked as in use to cross
  9274. a jump to a distant label, so exclude it }
  9275. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9276. hp2 := p;
  9277. repeat
  9278. { Explicitly check for the excluded register (don't include the first
  9279. instruction as it may be reading from here }
  9280. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9281. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9282. begin
  9283. RegInUse := True;
  9284. Break;
  9285. end;
  9286. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9287. if not GetNextInstruction(hp2, hp2) then
  9288. InternalError(2020112340);
  9289. until (hp2 = hp1);
  9290. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9291. { We might still be able to get away with this }
  9292. RegInUse := not
  9293. (
  9294. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9295. (hp2.typ = ait_instruction) and
  9296. (
  9297. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9298. instruction that doesn't actually contain ThisReg }
  9299. (cs_opt_level3 in current_settings.optimizerswitches) or
  9300. RegInInstruction(ThisReg, hp2)
  9301. ) and
  9302. RegLoadedWithNewValue(ThisReg, hp2)
  9303. );
  9304. if not RegInUse then
  9305. begin
  9306. { Force the register size to the same as this instruction so it can be removed}
  9307. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9308. begin
  9309. TargetSize := S_L;
  9310. TargetSubReg := R_SUBD;
  9311. end
  9312. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9313. begin
  9314. TargetSize := S_W;
  9315. TargetSubReg := R_SUBW;
  9316. end;
  9317. ThisReg := taicpu(hp1).oper[1]^.reg;
  9318. setsubreg(ThisReg, TargetSubReg);
  9319. RegChanged := True;
  9320. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9321. TransferUsedRegs(TmpUsedRegs);
  9322. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9323. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9324. if p = hp1 then
  9325. begin
  9326. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9327. p_removed := True;
  9328. end
  9329. else
  9330. RemoveInstruction(hp1);
  9331. hp1_removed := True;
  9332. { Instruction will become "mov %reg,%reg" }
  9333. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9334. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9335. begin
  9336. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9337. RemoveCurrentP(p);
  9338. p_removed := True;
  9339. end
  9340. else
  9341. taicpu(p).oper[1]^.reg := ThisReg;
  9342. Result := True;
  9343. end
  9344. else
  9345. begin
  9346. if TargetSize <> MaxSize then
  9347. begin
  9348. { Since the register is in use, we have to force it to
  9349. MaxSize otherwise part of it may become undefined later on }
  9350. TargetSize := MaxSize;
  9351. case TargetSize of
  9352. S_B:
  9353. TargetSubReg := R_SUBL;
  9354. S_W:
  9355. TargetSubReg := R_SUBW;
  9356. S_L:
  9357. TargetSubReg := R_SUBD;
  9358. else
  9359. InternalError(2020112351);
  9360. end;
  9361. setsubreg(ThisReg, TargetSubReg);
  9362. end;
  9363. AdjustFinalLoad;
  9364. end;
  9365. end
  9366. else
  9367. AdjustFinalLoad;
  9368. Result := AdjustInitialLoadAndSize or Result;
  9369. { Now go through every instruction we found and change the
  9370. size. If TargetSize = MaxSize, then almost no changes are
  9371. needed and Result can remain False if it hasn't been set
  9372. yet.
  9373. If RegChanged is True, then the register requires changing
  9374. and so the point about TargetSize = MaxSize doesn't apply. }
  9375. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9376. begin
  9377. for LocalIndex := 0 to InstrMax do
  9378. begin
  9379. { If p_removed is true, then the original MOV/Z was removed
  9380. and removing the AND instruction may not be safe if it
  9381. appears first }
  9382. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9383. InternalError(2020112310);
  9384. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9385. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9386. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9387. InstrList[LocalIndex].opsize := TargetSize;
  9388. end;
  9389. Result := True;
  9390. end;
  9391. end;
  9392. begin
  9393. Result := False;
  9394. p_removed := False;
  9395. hp1_removed := False;
  9396. ThisReg := taicpu(p).oper[1]^.reg;
  9397. { Check for:
  9398. movs/z ###,%ecx (or %cx or %rcx)
  9399. ...
  9400. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9401. (dealloc %ecx)
  9402. Change to:
  9403. mov ###,%cl (if ### = %cl, then remove completely)
  9404. ...
  9405. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9406. }
  9407. if (getsupreg(ThisReg) = RS_ECX) and
  9408. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9409. (hp1.typ = ait_instruction) and
  9410. (
  9411. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9412. instruction that doesn't actually contain ECX }
  9413. (cs_opt_level3 in current_settings.optimizerswitches) or
  9414. RegInInstruction(NR_ECX, hp1) or
  9415. (
  9416. { It's common for the shift/rotate's read/write register to be
  9417. initialised in between, so under -O2 and under, search ahead
  9418. one more instruction
  9419. }
  9420. GetNextInstruction(hp1, hp1) and
  9421. (hp1.typ = ait_instruction) and
  9422. RegInInstruction(NR_ECX, hp1)
  9423. )
  9424. ) and
  9425. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9426. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9427. begin
  9428. TransferUsedRegs(TmpUsedRegs);
  9429. hp2 := p;
  9430. repeat
  9431. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9432. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9433. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9434. begin
  9435. case taicpu(p).opsize of
  9436. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9437. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9438. begin
  9439. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9440. RemoveCurrentP(p);
  9441. end
  9442. else
  9443. begin
  9444. taicpu(p).opcode := A_MOV;
  9445. taicpu(p).opsize := S_B;
  9446. taicpu(p).oper[1]^.reg := NR_CL;
  9447. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9448. end;
  9449. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9450. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9451. begin
  9452. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9453. RemoveCurrentP(p);
  9454. end
  9455. else
  9456. begin
  9457. taicpu(p).opcode := A_MOV;
  9458. taicpu(p).opsize := S_W;
  9459. taicpu(p).oper[1]^.reg := NR_CX;
  9460. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9461. end;
  9462. {$ifdef x86_64}
  9463. S_LQ:
  9464. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9465. begin
  9466. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9467. RemoveCurrentP(p);
  9468. end
  9469. else
  9470. begin
  9471. taicpu(p).opcode := A_MOV;
  9472. taicpu(p).opsize := S_L;
  9473. taicpu(p).oper[1]^.reg := NR_ECX;
  9474. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9475. end;
  9476. {$endif x86_64}
  9477. else
  9478. InternalError(2021120401);
  9479. end;
  9480. Result := True;
  9481. Exit;
  9482. end;
  9483. end;
  9484. { This is anything but quick! }
  9485. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9486. Exit;
  9487. SetLength(InstrList, 0);
  9488. InstrMax := -1;
  9489. case taicpu(p).opsize of
  9490. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9491. begin
  9492. {$if defined(i386) or defined(i8086)}
  9493. { If the target size is 8-bit, make sure we can actually encode it }
  9494. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9495. Exit;
  9496. {$endif i386 or i8086}
  9497. LowerLimit := $FF;
  9498. SignedLowerLimit := $7F;
  9499. SignedLowerLimitBottom := -128;
  9500. MinSize := S_B;
  9501. if taicpu(p).opsize = S_BW then
  9502. begin
  9503. MaxSize := S_W;
  9504. UpperLimit := $FFFF;
  9505. SignedUpperLimit := $7FFF;
  9506. SignedUpperLimitBottom := -32768;
  9507. end
  9508. else
  9509. begin
  9510. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9511. MaxSize := S_L;
  9512. UpperLimit := $FFFFFFFF;
  9513. SignedUpperLimit := $7FFFFFFF;
  9514. SignedUpperLimitBottom := -2147483648;
  9515. end;
  9516. end;
  9517. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9518. begin
  9519. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9520. LowerLimit := $FFFF;
  9521. SignedLowerLimit := $7FFF;
  9522. SignedLowerLimitBottom := -32768;
  9523. UpperLimit := $FFFFFFFF;
  9524. SignedUpperLimit := $7FFFFFFF;
  9525. SignedUpperLimitBottom := -2147483648;
  9526. MinSize := S_W;
  9527. MaxSize := S_L;
  9528. end;
  9529. {$ifdef x86_64}
  9530. S_LQ:
  9531. begin
  9532. { Both the lower and upper limits are set to 32-bit. If a limit
  9533. is breached, then optimisation is impossible }
  9534. LowerLimit := $FFFFFFFF;
  9535. SignedLowerLimit := $7FFFFFFF;
  9536. SignedLowerLimitBottom := -2147483648;
  9537. UpperLimit := $FFFFFFFF;
  9538. SignedUpperLimit := $7FFFFFFF;
  9539. SignedUpperLimitBottom := -2147483648;
  9540. MinSize := S_L;
  9541. MaxSize := S_L;
  9542. end;
  9543. {$endif x86_64}
  9544. else
  9545. InternalError(2020112301);
  9546. end;
  9547. TestValMin := 0;
  9548. TestValMax := LowerLimit;
  9549. TestValSignedMax := SignedLowerLimit;
  9550. TryShiftDownLimit := LowerLimit;
  9551. TryShiftDown := S_NO;
  9552. ShiftDownOverflow := False;
  9553. RegChanged := False;
  9554. BitwiseOnly := True;
  9555. OrXorUsed := False;
  9556. UpperSignedOverflow := False;
  9557. LowerSignedOverflow := False;
  9558. UpperUnsignedOverflow := False;
  9559. LowerUnsignedOverflow := False;
  9560. hp1 := p;
  9561. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9562. (hp1.typ = ait_instruction) and
  9563. (
  9564. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9565. instruction that doesn't actually contain ThisReg }
  9566. (cs_opt_level3 in current_settings.optimizerswitches) or
  9567. { This allows this Movx optimisation to work through the SETcc instructions
  9568. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9569. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9570. skip over these SETcc instructions). }
  9571. (taicpu(hp1).opcode = A_SETcc) or
  9572. RegInInstruction(ThisReg, hp1)
  9573. ) do
  9574. begin
  9575. case taicpu(hp1).opcode of
  9576. A_INC,A_DEC:
  9577. begin
  9578. { Has to be an exact match on the register }
  9579. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9580. Break;
  9581. if taicpu(hp1).opcode = A_INC then
  9582. begin
  9583. Inc(TestValMin);
  9584. Inc(TestValMax);
  9585. Inc(TestValSignedMax);
  9586. end
  9587. else
  9588. begin
  9589. Dec(TestValMin);
  9590. Dec(TestValMax);
  9591. Dec(TestValSignedMax);
  9592. end;
  9593. end;
  9594. A_TEST, A_CMP:
  9595. begin
  9596. if (
  9597. { Too high a risk of non-linear behaviour that breaks DFA
  9598. here, unless it's cmp $0,%reg, which is equivalent to
  9599. test %reg,%reg }
  9600. OrXorUsed and
  9601. (taicpu(hp1).opcode = A_CMP) and
  9602. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9603. ) or
  9604. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9605. { Has to be an exact match on the register }
  9606. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9607. (
  9608. { Permit "test %reg,%reg" }
  9609. (taicpu(hp1).opcode = A_TEST) and
  9610. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9611. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9612. ) or
  9613. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9614. { Make sure the comparison value is not smaller than the
  9615. smallest allowed signed value for the minimum size (e.g.
  9616. -128 for 8-bit) }
  9617. not (
  9618. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9619. { Is it in the negative range? }
  9620. (
  9621. (taicpu(hp1).oper[0]^.val < 0) and
  9622. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9623. )
  9624. ) then
  9625. Break;
  9626. { Check to see if the active register is used afterwards }
  9627. TransferUsedRegs(TmpUsedRegs);
  9628. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9629. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9630. begin
  9631. { Make sure the comparison or any previous instructions
  9632. hasn't pushed the test values outside of the range of
  9633. MinSize }
  9634. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9635. begin
  9636. { Exceeded lower bound but not upper bound }
  9637. Exit;
  9638. end
  9639. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9640. begin
  9641. { Size didn't exceed lower bound }
  9642. TargetSize := MinSize;
  9643. end
  9644. else
  9645. Break;
  9646. case TargetSize of
  9647. S_B:
  9648. TargetSubReg := R_SUBL;
  9649. S_W:
  9650. TargetSubReg := R_SUBW;
  9651. S_L:
  9652. TargetSubReg := R_SUBD;
  9653. else
  9654. InternalError(2021051002);
  9655. end;
  9656. if TargetSize <> MaxSize then
  9657. begin
  9658. { Update the register to its new size }
  9659. setsubreg(ThisReg, TargetSubReg);
  9660. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9661. taicpu(hp1).oper[1]^.reg := ThisReg;
  9662. taicpu(hp1).opsize := TargetSize;
  9663. { Convert the input MOVZX to a MOV if necessary }
  9664. AdjustInitialLoadAndSize;
  9665. if (InstrMax >= 0) then
  9666. begin
  9667. for Index := 0 to InstrMax do
  9668. begin
  9669. { If p_removed is true, then the original MOV/Z was removed
  9670. and removing the AND instruction may not be safe if it
  9671. appears first }
  9672. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9673. InternalError(2020112311);
  9674. if InstrList[Index].oper[0]^.typ = top_reg then
  9675. InstrList[Index].oper[0]^.reg := ThisReg;
  9676. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9677. InstrList[Index].opsize := MinSize;
  9678. end;
  9679. end;
  9680. Result := True;
  9681. end;
  9682. Exit;
  9683. end;
  9684. end;
  9685. A_SETcc:
  9686. begin
  9687. { This allows this Movx optimisation to work through the SETcc instructions
  9688. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9689. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9690. skip over these SETcc instructions). }
  9691. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9692. { Of course, break out if the current register is used }
  9693. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9694. Break
  9695. else
  9696. { We must use Continue so the instruction doesn't get added
  9697. to InstrList }
  9698. Continue;
  9699. end;
  9700. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9701. begin
  9702. if
  9703. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9704. { Has to be an exact match on the register }
  9705. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9706. (
  9707. (
  9708. (taicpu(hp1).oper[0]^.typ = top_const) and
  9709. (
  9710. (
  9711. (taicpu(hp1).opcode = A_SHL) and
  9712. (
  9713. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9714. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9715. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9716. )
  9717. ) or (
  9718. (taicpu(hp1).opcode <> A_SHL) and
  9719. (
  9720. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9721. { Is it in the negative range? }
  9722. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9723. )
  9724. )
  9725. )
  9726. ) or (
  9727. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9728. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9729. )
  9730. ) then
  9731. Break;
  9732. { Only process OR and XOR if there are only bitwise operations,
  9733. since otherwise they can too easily fool the data flow
  9734. analysis (they can cause non-linear behaviour) }
  9735. case taicpu(hp1).opcode of
  9736. A_ADD:
  9737. begin
  9738. if OrXorUsed then
  9739. { Too high a risk of non-linear behaviour that breaks DFA here }
  9740. Break
  9741. else
  9742. BitwiseOnly := False;
  9743. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9744. begin
  9745. TestValMin := TestValMin * 2;
  9746. TestValMax := TestValMax * 2;
  9747. TestValSignedMax := TestValSignedMax * 2;
  9748. end
  9749. else
  9750. begin
  9751. WorkingValue := taicpu(hp1).oper[0]^.val;
  9752. TestValMin := TestValMin + WorkingValue;
  9753. TestValMax := TestValMax + WorkingValue;
  9754. TestValSignedMax := TestValSignedMax + WorkingValue;
  9755. end;
  9756. end;
  9757. A_SUB:
  9758. begin
  9759. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9760. begin
  9761. TestValMin := 0;
  9762. TestValMax := 0;
  9763. TestValSignedMax := 0;
  9764. end
  9765. else
  9766. begin
  9767. if OrXorUsed then
  9768. { Too high a risk of non-linear behaviour that breaks DFA here }
  9769. Break
  9770. else
  9771. BitwiseOnly := False;
  9772. WorkingValue := taicpu(hp1).oper[0]^.val;
  9773. TestValMin := TestValMin - WorkingValue;
  9774. TestValMax := TestValMax - WorkingValue;
  9775. TestValSignedMax := TestValSignedMax - WorkingValue;
  9776. end;
  9777. end;
  9778. A_AND:
  9779. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9780. begin
  9781. { we might be able to go smaller if AND appears first }
  9782. if InstrMax = -1 then
  9783. case MinSize of
  9784. S_B:
  9785. ;
  9786. S_W:
  9787. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9788. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9789. begin
  9790. TryShiftDown := S_B;
  9791. TryShiftDownLimit := $FF;
  9792. end;
  9793. S_L:
  9794. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9795. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9796. begin
  9797. TryShiftDown := S_B;
  9798. TryShiftDownLimit := $FF;
  9799. end
  9800. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9801. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9802. begin
  9803. TryShiftDown := S_W;
  9804. TryShiftDownLimit := $FFFF;
  9805. end;
  9806. else
  9807. InternalError(2020112320);
  9808. end;
  9809. WorkingValue := taicpu(hp1).oper[0]^.val;
  9810. TestValMin := TestValMin and WorkingValue;
  9811. TestValMax := TestValMax and WorkingValue;
  9812. TestValSignedMax := TestValSignedMax and WorkingValue;
  9813. end;
  9814. A_OR:
  9815. begin
  9816. if not BitwiseOnly then
  9817. Break;
  9818. OrXorUsed := True;
  9819. WorkingValue := taicpu(hp1).oper[0]^.val;
  9820. TestValMin := TestValMin or WorkingValue;
  9821. TestValMax := TestValMax or WorkingValue;
  9822. TestValSignedMax := TestValSignedMax or WorkingValue;
  9823. end;
  9824. A_XOR:
  9825. begin
  9826. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9827. begin
  9828. TestValMin := 0;
  9829. TestValMax := 0;
  9830. TestValSignedMax := 0;
  9831. end
  9832. else
  9833. begin
  9834. if not BitwiseOnly then
  9835. Break;
  9836. OrXorUsed := True;
  9837. WorkingValue := taicpu(hp1).oper[0]^.val;
  9838. TestValMin := TestValMin xor WorkingValue;
  9839. TestValMax := TestValMax xor WorkingValue;
  9840. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9841. end;
  9842. end;
  9843. A_SHL:
  9844. begin
  9845. BitwiseOnly := False;
  9846. WorkingValue := taicpu(hp1).oper[0]^.val;
  9847. TestValMin := TestValMin shl WorkingValue;
  9848. TestValMax := TestValMax shl WorkingValue;
  9849. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9850. end;
  9851. A_SHR,
  9852. { The first instruction was MOVZX, so the value won't be negative }
  9853. A_SAR:
  9854. begin
  9855. if InstrMax <> -1 then
  9856. BitwiseOnly := False
  9857. else
  9858. { we might be able to go smaller if SHR appears first }
  9859. case MinSize of
  9860. S_B:
  9861. ;
  9862. S_W:
  9863. if (taicpu(hp1).oper[0]^.val >= 8) then
  9864. begin
  9865. TryShiftDown := S_B;
  9866. TryShiftDownLimit := $FF;
  9867. TryShiftDownSignedLimit := $7F;
  9868. TryShiftDownSignedLimitLower := -128;
  9869. end;
  9870. S_L:
  9871. if (taicpu(hp1).oper[0]^.val >= 24) then
  9872. begin
  9873. TryShiftDown := S_B;
  9874. TryShiftDownLimit := $FF;
  9875. TryShiftDownSignedLimit := $7F;
  9876. TryShiftDownSignedLimitLower := -128;
  9877. end
  9878. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9879. begin
  9880. TryShiftDown := S_W;
  9881. TryShiftDownLimit := $FFFF;
  9882. TryShiftDownSignedLimit := $7FFF;
  9883. TryShiftDownSignedLimitLower := -32768;
  9884. end;
  9885. else
  9886. InternalError(2020112321);
  9887. end;
  9888. WorkingValue := taicpu(hp1).oper[0]^.val;
  9889. if taicpu(hp1).opcode = A_SAR then
  9890. begin
  9891. TestValMin := SarInt64(TestValMin, WorkingValue);
  9892. TestValMax := SarInt64(TestValMax, WorkingValue);
  9893. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9894. end
  9895. else
  9896. begin
  9897. TestValMin := TestValMin shr WorkingValue;
  9898. TestValMax := TestValMax shr WorkingValue;
  9899. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9900. end;
  9901. end;
  9902. else
  9903. InternalError(2020112303);
  9904. end;
  9905. end;
  9906. (*
  9907. A_IMUL:
  9908. case taicpu(hp1).ops of
  9909. 2:
  9910. begin
  9911. if not MatchOpType(hp1, top_reg, top_reg) or
  9912. { Has to be an exact match on the register }
  9913. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9914. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9915. Break;
  9916. TestValMin := TestValMin * TestValMin;
  9917. TestValMax := TestValMax * TestValMax;
  9918. TestValSignedMax := TestValSignedMax * TestValMax;
  9919. end;
  9920. 3:
  9921. begin
  9922. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9923. { Has to be an exact match on the register }
  9924. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9925. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9926. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9927. { Is it in the negative range? }
  9928. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9929. Break;
  9930. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9931. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9932. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9933. end;
  9934. else
  9935. Break;
  9936. end;
  9937. A_IDIV:
  9938. case taicpu(hp1).ops of
  9939. 3:
  9940. begin
  9941. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9942. { Has to be an exact match on the register }
  9943. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9944. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9945. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9946. { Is it in the negative range? }
  9947. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9948. Break;
  9949. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9950. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9951. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9952. end;
  9953. else
  9954. Break;
  9955. end;
  9956. *)
  9957. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9958. begin
  9959. { If there are no instructions in between, then we might be able to make a saving }
  9960. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9961. Break;
  9962. { We have something like:
  9963. movzbw %dl,%dx
  9964. ...
  9965. movswl %dx,%edx
  9966. Change the latter to a zero-extension then enter the
  9967. A_MOVZX case branch.
  9968. }
  9969. {$ifdef x86_64}
  9970. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9971. begin
  9972. { this becomes a zero extension from 32-bit to 64-bit, but
  9973. the upper 32 bits are already zero, so just delete the
  9974. instruction }
  9975. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9976. RemoveInstruction(hp1);
  9977. Result := True;
  9978. Exit;
  9979. end
  9980. else
  9981. {$endif x86_64}
  9982. begin
  9983. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9984. taicpu(hp1).opcode := A_MOVZX;
  9985. {$ifdef x86_64}
  9986. case taicpu(hp1).opsize of
  9987. S_BQ:
  9988. begin
  9989. taicpu(hp1).opsize := S_BL;
  9990. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9991. end;
  9992. S_WQ:
  9993. begin
  9994. taicpu(hp1).opsize := S_WL;
  9995. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9996. end;
  9997. S_LQ:
  9998. begin
  9999. taicpu(hp1).opcode := A_MOV;
  10000. taicpu(hp1).opsize := S_L;
  10001. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10002. { In this instance, we need to break out because the
  10003. instruction is no longer MOVZX or MOVSXD }
  10004. Result := True;
  10005. Exit;
  10006. end;
  10007. else
  10008. ;
  10009. end;
  10010. {$endif x86_64}
  10011. Result := CompressInstructions;
  10012. Exit;
  10013. end;
  10014. end;
  10015. A_MOVZX:
  10016. begin
  10017. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10018. Break;
  10019. if (InstrMax = -1) then
  10020. begin
  10021. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10022. begin
  10023. { Optimise around i40003 }
  10024. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10025. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10026. {$ifndef x86_64}
  10027. and (
  10028. (taicpu(p).oper[0]^.typ <> top_reg) or
  10029. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10030. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10031. )
  10032. {$endif not x86_64}
  10033. then
  10034. begin
  10035. if (taicpu(p).oper[0]^.typ = top_reg) then
  10036. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10037. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10038. taicpu(p).opsize := S_BL;
  10039. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10040. RemoveInstruction(hp1);
  10041. Result := True;
  10042. Exit;
  10043. end;
  10044. end
  10045. else
  10046. begin
  10047. { Will return false if the second parameter isn't ThisReg
  10048. (can happen on -O2 and under) }
  10049. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10050. begin
  10051. { The two MOVZX instructions are adjacent, so remove the first one }
  10052. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10053. RemoveCurrentP(p);
  10054. Result := True;
  10055. Exit;
  10056. end;
  10057. Break;
  10058. end;
  10059. end;
  10060. Result := CompressInstructions;
  10061. Exit;
  10062. end;
  10063. else
  10064. { This includes ADC, SBB and IDIV }
  10065. Break;
  10066. end;
  10067. if not CheckOverflowConditions then
  10068. Break;
  10069. { Contains highest index (so instruction count - 1) }
  10070. Inc(InstrMax);
  10071. if InstrMax > High(InstrList) then
  10072. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10073. InstrList[InstrMax] := taicpu(hp1);
  10074. end;
  10075. end;
  10076. {$pop}
  10077. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10078. var
  10079. hp1 : tai;
  10080. begin
  10081. Result:=false;
  10082. if (taicpu(p).ops >= 2) and
  10083. ((taicpu(p).oper[0]^.typ = top_const) or
  10084. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10085. (taicpu(p).oper[1]^.typ = top_reg) and
  10086. ((taicpu(p).ops = 2) or
  10087. ((taicpu(p).oper[2]^.typ = top_reg) and
  10088. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10089. GetLastInstruction(p,hp1) and
  10090. MatchInstruction(hp1,A_MOV,[]) and
  10091. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10092. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10093. begin
  10094. TransferUsedRegs(TmpUsedRegs);
  10095. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10096. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10097. { change
  10098. mov reg1,reg2
  10099. imul y,reg2 to imul y,reg1,reg2 }
  10100. begin
  10101. taicpu(p).ops := 3;
  10102. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10103. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10104. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10105. RemoveInstruction(hp1);
  10106. result:=true;
  10107. end;
  10108. end;
  10109. end;
  10110. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10111. var
  10112. ThisLabel: TAsmLabel;
  10113. begin
  10114. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10115. ThisLabel.decrefs;
  10116. taicpu(p).condition := C_None;
  10117. taicpu(p).opcode := A_RET;
  10118. taicpu(p).is_jmp := false;
  10119. taicpu(p).ops := taicpu(ret_p).ops;
  10120. case taicpu(ret_p).ops of
  10121. 0:
  10122. taicpu(p).clearop(0);
  10123. 1:
  10124. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10125. else
  10126. internalerror(2016041301);
  10127. end;
  10128. { If the original label is now dead, it might turn out that the label
  10129. immediately follows p. As a result, everything beyond it, which will
  10130. be just some final register configuration and a RET instruction, is
  10131. now dead code. [Kit] }
  10132. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10133. running RemoveDeadCodeAfterJump for each RET instruction, because
  10134. this optimisation rarely happens and most RETs appear at the end of
  10135. routines where there is nothing that can be stripped. [Kit] }
  10136. if not ThisLabel.is_used then
  10137. RemoveDeadCodeAfterJump(p);
  10138. end;
  10139. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10140. var
  10141. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10142. Unconditional, PotentialModified: Boolean;
  10143. OperPtr: POper;
  10144. NewRef: TReference;
  10145. InstrList: array of taicpu;
  10146. InstrMax, Index: Integer;
  10147. const
  10148. {$ifdef DEBUG_AOPTCPU}
  10149. SNoFlags: shortstring = ' so the flags aren''t modified';
  10150. {$else DEBUG_AOPTCPU}
  10151. SNoFlags = '';
  10152. {$endif DEBUG_AOPTCPU}
  10153. begin
  10154. Result:=false;
  10155. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10156. begin
  10157. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10158. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10159. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10160. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10161. GetNextInstruction(hp1, hp2) and
  10162. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10163. { Change from: To:
  10164. set(C) %reg j(~C) label
  10165. test %reg,%reg/cmp $0,%reg
  10166. je label
  10167. set(C) %reg j(C) label
  10168. test %reg,%reg/cmp $0,%reg
  10169. jne label
  10170. (Also do something similar with sete/setne instead of je/jne)
  10171. }
  10172. begin
  10173. { Before we do anything else, we need to check the instructions
  10174. in between SETcc and TEST to make sure they don't modify the
  10175. FLAGS register - if -O2 or under, there won't be any
  10176. instructions between SET and TEST }
  10177. TransferUsedRegs(TmpUsedRegs);
  10178. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10179. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10180. begin
  10181. next := p;
  10182. SetLength(InstrList, 0);
  10183. InstrMax := -1;
  10184. PotentialModified := False;
  10185. { Make a note of every instruction that modifies the FLAGS
  10186. register }
  10187. while GetNextInstruction(next, next) and (next <> hp1) do
  10188. begin
  10189. if next.typ <> ait_instruction then
  10190. { GetNextInstructionUsingReg should have returned False }
  10191. InternalError(2021051701);
  10192. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10193. begin
  10194. case taicpu(next).opcode of
  10195. A_SETcc,
  10196. A_CMOVcc,
  10197. A_Jcc:
  10198. begin
  10199. if PotentialModified then
  10200. { Not safe because the flags were modified earlier }
  10201. Exit
  10202. else
  10203. { Condition is the same as the initial SETcc, so this is safe
  10204. (don't add to instruction list though) }
  10205. Continue;
  10206. end;
  10207. A_ADD:
  10208. begin
  10209. if (taicpu(next).opsize = S_B) or
  10210. { LEA doesn't support 8-bit operands }
  10211. (taicpu(next).oper[1]^.typ <> top_reg) or
  10212. { Must write to a register }
  10213. (taicpu(next).oper[0]^.typ = top_ref) then
  10214. { Require a constant or a register }
  10215. Exit;
  10216. PotentialModified := True;
  10217. end;
  10218. A_SUB:
  10219. begin
  10220. if (taicpu(next).opsize = S_B) or
  10221. { LEA doesn't support 8-bit operands }
  10222. (taicpu(next).oper[1]^.typ <> top_reg) or
  10223. { Must write to a register }
  10224. (taicpu(next).oper[0]^.typ <> top_const) or
  10225. (taicpu(next).oper[0]^.val = $80000000) then
  10226. { Can't subtract a register with LEA - also
  10227. check that the value isn't -2^31, as this
  10228. can't be negated }
  10229. Exit;
  10230. PotentialModified := True;
  10231. end;
  10232. A_SAL,
  10233. A_SHL:
  10234. begin
  10235. if (taicpu(next).opsize = S_B) or
  10236. { LEA doesn't support 8-bit operands }
  10237. (taicpu(next).oper[1]^.typ <> top_reg) or
  10238. { Must write to a register }
  10239. (taicpu(next).oper[0]^.typ <> top_const) or
  10240. (taicpu(next).oper[0]^.val < 0) or
  10241. (taicpu(next).oper[0]^.val > 3) then
  10242. Exit;
  10243. PotentialModified := True;
  10244. end;
  10245. A_IMUL:
  10246. begin
  10247. if (taicpu(next).ops <> 3) or
  10248. (taicpu(next).oper[1]^.typ <> top_reg) or
  10249. { Must write to a register }
  10250. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10251. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10252. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10253. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10254. Exit
  10255. else
  10256. PotentialModified := True;
  10257. end;
  10258. else
  10259. { Don't know how to change this, so abort }
  10260. Exit;
  10261. end;
  10262. { Contains highest index (so instruction count - 1) }
  10263. Inc(InstrMax);
  10264. if InstrMax > High(InstrList) then
  10265. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10266. InstrList[InstrMax] := taicpu(next);
  10267. end;
  10268. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10269. end;
  10270. if not Assigned(next) or (next <> hp1) then
  10271. { It should be equal to hp1 }
  10272. InternalError(2021051702);
  10273. { Cycle through each instruction and check to see if we can
  10274. change them to versions that don't modify the flags }
  10275. if (InstrMax >= 0) then
  10276. begin
  10277. for Index := 0 to InstrMax do
  10278. case InstrList[Index].opcode of
  10279. A_ADD:
  10280. begin
  10281. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10282. InstrList[Index].opcode := A_LEA;
  10283. reference_reset(NewRef, 1, []);
  10284. NewRef.base := InstrList[Index].oper[1]^.reg;
  10285. if InstrList[Index].oper[0]^.typ = top_reg then
  10286. begin
  10287. NewRef.index := InstrList[Index].oper[0]^.reg;
  10288. NewRef.scalefactor := 1;
  10289. end
  10290. else
  10291. NewRef.offset := InstrList[Index].oper[0]^.val;
  10292. InstrList[Index].loadref(0, NewRef);
  10293. end;
  10294. A_SUB:
  10295. begin
  10296. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10297. InstrList[Index].opcode := A_LEA;
  10298. reference_reset(NewRef, 1, []);
  10299. NewRef.base := InstrList[Index].oper[1]^.reg;
  10300. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10301. InstrList[Index].loadref(0, NewRef);
  10302. end;
  10303. A_SHL,
  10304. A_SAL:
  10305. begin
  10306. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10307. InstrList[Index].opcode := A_LEA;
  10308. reference_reset(NewRef, 1, []);
  10309. NewRef.index := InstrList[Index].oper[1]^.reg;
  10310. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10311. InstrList[Index].loadref(0, NewRef);
  10312. end;
  10313. A_IMUL:
  10314. begin
  10315. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10316. InstrList[Index].opcode := A_LEA;
  10317. reference_reset(NewRef, 1, []);
  10318. NewRef.index := InstrList[Index].oper[1]^.reg;
  10319. case InstrList[Index].oper[0]^.val of
  10320. 2, 4, 8:
  10321. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10322. else {3, 5 and 9}
  10323. begin
  10324. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10325. NewRef.base := InstrList[Index].oper[1]^.reg;
  10326. end;
  10327. end;
  10328. InstrList[Index].loadref(0, NewRef);
  10329. end;
  10330. else
  10331. InternalError(2021051710);
  10332. end;
  10333. end;
  10334. { Mark the FLAGS register as used across this whole block }
  10335. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10336. end;
  10337. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10338. JumpC := taicpu(hp2).condition;
  10339. Unconditional := False;
  10340. if conditions_equal(JumpC, C_E) then
  10341. SetC := inverse_cond(taicpu(p).condition)
  10342. else if conditions_equal(JumpC, C_NE) then
  10343. SetC := taicpu(p).condition
  10344. else
  10345. { We've got something weird here (and inefficent) }
  10346. begin
  10347. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10348. SetC := C_NONE;
  10349. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10350. if condition_in(C_AE, JumpC) then
  10351. Unconditional := True
  10352. else
  10353. { Not sure what to do with this jump - drop out }
  10354. Exit;
  10355. end;
  10356. RemoveInstruction(hp1);
  10357. if Unconditional then
  10358. MakeUnconditional(taicpu(hp2))
  10359. else
  10360. begin
  10361. if SetC = C_NONE then
  10362. InternalError(2018061402);
  10363. taicpu(hp2).SetCondition(SetC);
  10364. end;
  10365. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10366. TmpUsedRegs }
  10367. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10368. begin
  10369. RemoveCurrentp(p, hp2);
  10370. if taicpu(hp2).opcode = A_SETcc then
  10371. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10372. else
  10373. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10374. end
  10375. else
  10376. if taicpu(hp2).opcode = A_SETcc then
  10377. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10378. else
  10379. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10380. Result := True;
  10381. end
  10382. else if
  10383. { Make sure the instructions are adjacent }
  10384. (
  10385. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10386. GetNextInstruction(p, hp1)
  10387. ) and
  10388. MatchInstruction(hp1, A_MOV, [S_B]) and
  10389. { Writing to memory is allowed }
  10390. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10391. begin
  10392. {
  10393. Watch out for sequences such as:
  10394. set(c)b %regb
  10395. movb %regb,(ref)
  10396. movb $0,1(ref)
  10397. movb $0,2(ref)
  10398. movb $0,3(ref)
  10399. Much more efficient to turn it into:
  10400. movl $0,%regl
  10401. set(c)b %regb
  10402. movl %regl,(ref)
  10403. Or:
  10404. set(c)b %regb
  10405. movzbl %regb,%regl
  10406. movl %regl,(ref)
  10407. }
  10408. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10409. GetNextInstruction(hp1, hp2) and
  10410. MatchInstruction(hp2, A_MOV, [S_B]) and
  10411. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10412. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10413. begin
  10414. { Don't do anything else except set Result to True }
  10415. end
  10416. else
  10417. begin
  10418. if taicpu(p).oper[0]^.typ = top_reg then
  10419. begin
  10420. TransferUsedRegs(TmpUsedRegs);
  10421. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10422. end;
  10423. { If it's not a register, it's a memory address }
  10424. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10425. begin
  10426. { Even if the register is still in use, we can minimise the
  10427. pipeline stall by changing the MOV into another SETcc. }
  10428. taicpu(hp1).opcode := A_SETcc;
  10429. taicpu(hp1).condition := taicpu(p).condition;
  10430. if taicpu(hp1).oper[1]^.typ = top_ref then
  10431. begin
  10432. { Swapping the operand pointers like this is probably a
  10433. bit naughty, but it is far faster than using loadoper
  10434. to transfer the reference from oper[1] to oper[0] if
  10435. you take into account the extra procedure calls and
  10436. the memory allocation and deallocation required }
  10437. OperPtr := taicpu(hp1).oper[1];
  10438. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10439. taicpu(hp1).oper[0] := OperPtr;
  10440. end
  10441. else
  10442. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10443. taicpu(hp1).clearop(1);
  10444. taicpu(hp1).ops := 1;
  10445. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10446. end
  10447. else
  10448. begin
  10449. if taicpu(hp1).oper[1]^.typ = top_reg then
  10450. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10451. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10452. RemoveInstruction(hp1);
  10453. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10454. end
  10455. end;
  10456. Result := True;
  10457. end;
  10458. end;
  10459. end;
  10460. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10461. var
  10462. hp1: tai;
  10463. Count: Integer;
  10464. OrigLabel: TAsmLabel;
  10465. begin
  10466. result := False;
  10467. { Sometimes, the optimisations below can permit this }
  10468. RemoveDeadCodeAfterJump(p);
  10469. 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
  10470. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10471. begin
  10472. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10473. { Also a side-effect of optimisations }
  10474. if CollapseZeroDistJump(p, OrigLabel) then
  10475. begin
  10476. Result := True;
  10477. Exit;
  10478. end;
  10479. hp1 := GetLabelWithSym(OrigLabel);
  10480. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10481. begin
  10482. if taicpu(hp1).opcode = A_RET then
  10483. begin
  10484. {
  10485. change
  10486. jmp .L1
  10487. ...
  10488. .L1:
  10489. ret
  10490. into
  10491. ret
  10492. }
  10493. begin
  10494. ConvertJumpToRET(p, hp1);
  10495. result:=true;
  10496. end;
  10497. end
  10498. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10499. not (cs_opt_size in current_settings.optimizerswitches) and
  10500. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10501. begin
  10502. Result := True;
  10503. Exit;
  10504. end;
  10505. end;
  10506. end;
  10507. end;
  10508. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai) : boolean;
  10509. begin
  10510. Result := assigned(p) and
  10511. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10512. (taicpu(p).oper[1]^.typ = top_reg) and
  10513. (
  10514. (taicpu(p).oper[0]^.typ = top_reg) or
  10515. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10516. it is not expected that this can cause a seg. violation }
  10517. (
  10518. (taicpu(p).oper[0]^.typ = top_ref) and
  10519. { TODO: Can we detect which references become constants at this
  10520. stage so we don't have to do a blanket ban? }
  10521. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10522. (
  10523. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10524. (
  10525. { If the reference also appears in the condition, then we know it's safe, otherwise
  10526. any kind of access violation would have occurred already }
  10527. Assigned(cond_p) and
  10528. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10529. (cond_p.typ = ait_instruction) and
  10530. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10531. { Just consider 2-operand comparison instructions for now to be safe }
  10532. (taicpu(cond_p).ops = 2) and
  10533. (
  10534. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10535. (
  10536. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10537. { Don't risk identical registers but different offsets, as we may have constructs
  10538. such as buffer streams with things like length fields that indicate whether
  10539. any more data follows. And there are probably some contrived examples where
  10540. writing to offsets behind the one being read also lead to access violations }
  10541. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10542. (
  10543. { Check that we're not modifying a register that appears in the reference }
  10544. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10545. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10546. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10547. )
  10548. )
  10549. )
  10550. )
  10551. )
  10552. )
  10553. );
  10554. end;
  10555. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10556. begin
  10557. { Update integer registers, ignoring deallocations }
  10558. repeat
  10559. while assigned(p) and
  10560. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10561. (p.typ = ait_label) or
  10562. ((p.typ = ait_marker) and
  10563. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10564. p := tai(p.next);
  10565. while assigned(p) and
  10566. (p.typ=ait_RegAlloc) Do
  10567. begin
  10568. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10569. begin
  10570. case tai_regalloc(p).ratype of
  10571. ra_alloc :
  10572. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10573. else
  10574. ;
  10575. end;
  10576. end;
  10577. p := tai(p.next);
  10578. end;
  10579. until not(assigned(p)) or
  10580. (not(p.typ in SkipInstr) and
  10581. not((p.typ = ait_label) and
  10582. labelCanBeSkipped(tai_label(p))));
  10583. end;
  10584. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10585. var
  10586. hp1,hp2: tai;
  10587. carryadd_opcode : TAsmOp;
  10588. symbol: TAsmSymbol;
  10589. increg, tmpreg: TRegister;
  10590. {$ifndef i8086}
  10591. { Code and variables specific to CMOV optimisations }
  10592. hp3,hp4,hp5,
  10593. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10594. l, c, w, x : Longint;
  10595. condition, second_condition : TAsmCond;
  10596. FoundMatchingJump, RegMatch: Boolean;
  10597. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10598. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10599. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10600. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10601. new register to store the constant }
  10602. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10603. var
  10604. RegSize: TSubRegister;
  10605. CurrentVal: TCGInt;
  10606. NewReg: TRegister;
  10607. X: ShortInt;
  10608. begin
  10609. Result := False;
  10610. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10611. Exit;
  10612. if StoredCount >= MAX_CMOV_REGISTERS then
  10613. { Arrays are full }
  10614. Exit;
  10615. { Remember that CMOV can't encode 8-bit registers }
  10616. case taicpu(p).opsize of
  10617. S_W:
  10618. RegSize := R_SUBW;
  10619. S_L:
  10620. RegSize := R_SUBD;
  10621. S_Q:
  10622. RegSize := R_SUBQ;
  10623. else
  10624. InternalError(2021100401);
  10625. end;
  10626. { See if the value has already been reserved for another CMOV instruction }
  10627. CurrentVal := taicpu(p).oper[0]^.val;
  10628. for X := 0 to StoredCount - 1 do
  10629. if ConstVals[X] = CurrentVal then
  10630. begin
  10631. ConstRegs[StoredCount] := ConstRegs[X];
  10632. ConstVals[StoredCount] := CurrentVal;
  10633. Result := True;
  10634. Inc(StoredCount);
  10635. { Don't increase CMOVCount this time, since we're re-using a register }
  10636. Exit;
  10637. end;
  10638. NewReg := GetIntRegisterBetween(RegSize, TmpUsedRegs, search_start_p, stop_search_p, True);
  10639. if NewReg = NR_NO then
  10640. { No free registers }
  10641. Exit;
  10642. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10643. up vying for the same register }
  10644. IncludeRegInUsedRegs(NewReg, TmpUsedRegs);
  10645. ConstRegs[StoredCount] := NewReg;
  10646. ConstVals[StoredCount] := CurrentVal;
  10647. Inc(StoredCount);
  10648. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10649. MOV required adds complexity and will cause diminishing returns
  10650. sooner than normal. This is more of an approximate weighting than
  10651. anything else. }
  10652. Inc(CMOVCount);
  10653. Result := True;
  10654. end;
  10655. {$endif i8086}
  10656. begin
  10657. result:=false;
  10658. if GetNextInstruction(p,hp1) then
  10659. begin
  10660. if (hp1.typ=ait_label) then
  10661. begin
  10662. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10663. Exit;
  10664. end
  10665. else if (hp1.typ<>ait_instruction) then
  10666. Exit;
  10667. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10668. if (
  10669. (
  10670. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10671. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10672. (Taicpu(hp1).oper[0]^.val=1)
  10673. ) or
  10674. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10675. ) and
  10676. GetNextInstruction(hp1,hp2) and
  10677. SkipAligns(hp2, hp2) and
  10678. (hp2.typ = ait_label) and
  10679. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10680. { jb @@1 cmc
  10681. inc/dec operand --> adc/sbb operand,0
  10682. @@1:
  10683. ... and ...
  10684. jnb @@1
  10685. inc/dec operand --> adc/sbb operand,0
  10686. @@1: }
  10687. begin
  10688. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10689. begin
  10690. case taicpu(hp1).opcode of
  10691. A_INC,
  10692. A_ADD:
  10693. carryadd_opcode:=A_ADC;
  10694. A_DEC,
  10695. A_SUB:
  10696. carryadd_opcode:=A_SBB;
  10697. else
  10698. InternalError(2021011001);
  10699. end;
  10700. Taicpu(p).clearop(0);
  10701. Taicpu(p).ops:=0;
  10702. Taicpu(p).is_jmp:=false;
  10703. Taicpu(p).opcode:=A_CMC;
  10704. Taicpu(p).condition:=C_NONE;
  10705. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10706. Taicpu(hp1).ops:=2;
  10707. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10708. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10709. else
  10710. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10711. Taicpu(hp1).loadconst(0,0);
  10712. Taicpu(hp1).opcode:=carryadd_opcode;
  10713. result:=true;
  10714. exit;
  10715. end
  10716. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10717. begin
  10718. case taicpu(hp1).opcode of
  10719. A_INC,
  10720. A_ADD:
  10721. carryadd_opcode:=A_ADC;
  10722. A_DEC,
  10723. A_SUB:
  10724. carryadd_opcode:=A_SBB;
  10725. else
  10726. InternalError(2021011002);
  10727. end;
  10728. Taicpu(hp1).ops:=2;
  10729. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10730. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10731. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10732. else
  10733. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10734. Taicpu(hp1).loadconst(0,0);
  10735. Taicpu(hp1).opcode:=carryadd_opcode;
  10736. RemoveCurrentP(p, hp1);
  10737. result:=true;
  10738. exit;
  10739. end
  10740. {
  10741. jcc @@1 setcc tmpreg
  10742. inc/dec/add/sub operand -> (movzx tmpreg)
  10743. @@1: add/sub tmpreg,operand
  10744. While this increases code size slightly, it makes the code much faster if the
  10745. jump is unpredictable
  10746. }
  10747. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10748. begin
  10749. { search for an available register which is volatile }
  10750. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10751. if increg <> NR_NO then
  10752. begin
  10753. { We don't need to check if tmpreg is in hp1 or not, because
  10754. it will be marked as in use at p (if not, this is
  10755. indictive of a compiler bug). }
  10756. TAsmLabel(symbol).decrefs;
  10757. Taicpu(p).clearop(0);
  10758. Taicpu(p).ops:=1;
  10759. Taicpu(p).is_jmp:=false;
  10760. Taicpu(p).opcode:=A_SETcc;
  10761. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10762. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10763. Taicpu(p).loadreg(0,increg);
  10764. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10765. begin
  10766. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10767. R_SUBW:
  10768. begin
  10769. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10770. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10771. end;
  10772. R_SUBD:
  10773. begin
  10774. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10775. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10776. end;
  10777. {$ifdef x86_64}
  10778. R_SUBQ:
  10779. begin
  10780. { MOVZX doesn't have a 64-bit variant, because
  10781. the 32-bit version implicitly zeroes the
  10782. upper 32-bits of the destination register }
  10783. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10784. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10785. setsubreg(tmpreg, R_SUBQ);
  10786. end;
  10787. {$endif x86_64}
  10788. else
  10789. Internalerror(2020030601);
  10790. end;
  10791. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10792. asml.InsertAfter(hp2,p);
  10793. end
  10794. else
  10795. tmpreg := increg;
  10796. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10797. begin
  10798. Taicpu(hp1).ops:=2;
  10799. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10800. end;
  10801. Taicpu(hp1).loadreg(0,tmpreg);
  10802. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10803. Result := True;
  10804. { p is no longer a Jcc instruction, so exit }
  10805. Exit;
  10806. end;
  10807. end;
  10808. end;
  10809. { Detect the following:
  10810. jmp<cond> @Lbl1
  10811. jmp @Lbl2
  10812. ...
  10813. @Lbl1:
  10814. ret
  10815. Change to:
  10816. jmp<inv_cond> @Lbl2
  10817. ret
  10818. }
  10819. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10820. begin
  10821. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10822. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10823. MatchInstruction(hp2,A_RET,[S_NO]) then
  10824. begin
  10825. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10826. { Change label address to that of the unconditional jump }
  10827. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10828. TAsmLabel(symbol).DecRefs;
  10829. taicpu(hp1).opcode := A_RET;
  10830. taicpu(hp1).is_jmp := false;
  10831. taicpu(hp1).ops := taicpu(hp2).ops;
  10832. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10833. case taicpu(hp2).ops of
  10834. 0:
  10835. taicpu(hp1).clearop(0);
  10836. 1:
  10837. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10838. else
  10839. internalerror(2016041302);
  10840. end;
  10841. end;
  10842. {$ifndef i8086}
  10843. end
  10844. {
  10845. convert
  10846. j<c> .L1
  10847. mov 1,reg
  10848. jmp .L2
  10849. .L1
  10850. mov 0,reg
  10851. .L2
  10852. into
  10853. mov 0,reg
  10854. set<not(c)> reg
  10855. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10856. would destroy the flag contents
  10857. }
  10858. else if MatchInstruction(hp1,A_MOV,[]) and
  10859. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10860. {$ifdef i386}
  10861. (
  10862. { Under i386, ESI, EDI, EBP and ESP
  10863. don't have an 8-bit representation }
  10864. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10865. ) and
  10866. {$endif i386}
  10867. (taicpu(hp1).oper[0]^.val=1) and
  10868. GetNextInstruction(hp1,hp2) and
  10869. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10870. GetNextInstruction(hp2,hp3) and
  10871. { skip align }
  10872. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10873. (hp3.typ=ait_label) and
  10874. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10875. (tai_label(hp3).labsym.getrefs=1) and
  10876. GetNextInstruction(hp3,hp4) and
  10877. MatchInstruction(hp4,A_MOV,[]) and
  10878. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10879. (taicpu(hp4).oper[0]^.val=0) and
  10880. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10881. GetNextInstruction(hp4,hp5) and
  10882. (hp5.typ=ait_label) and
  10883. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10884. (tai_label(hp5).labsym.getrefs=1) then
  10885. begin
  10886. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10887. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10888. { remove last label }
  10889. RemoveInstruction(hp5);
  10890. { remove second label }
  10891. RemoveInstruction(hp3);
  10892. { if align is present remove it }
  10893. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10894. RemoveInstruction(hp3);
  10895. { remove jmp }
  10896. RemoveInstruction(hp2);
  10897. if taicpu(hp1).opsize=S_B then
  10898. RemoveInstruction(hp1)
  10899. else
  10900. taicpu(hp1).loadconst(0,0);
  10901. taicpu(hp4).opcode:=A_SETcc;
  10902. taicpu(hp4).opsize:=S_B;
  10903. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10904. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10905. taicpu(hp4).opercnt:=1;
  10906. taicpu(hp4).ops:=1;
  10907. taicpu(hp4).freeop(1);
  10908. RemoveCurrentP(p);
  10909. Result:=true;
  10910. exit;
  10911. end
  10912. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.optimizecputype]) and
  10913. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  10914. begin
  10915. { check for
  10916. jCC xxx
  10917. <several movs>
  10918. xxx:
  10919. Also spot:
  10920. Jcc xxx
  10921. <several movs>
  10922. jmp xxx
  10923. Change to:
  10924. <several cmovs with inverted condition>
  10925. jmp xxx (only for the 2nd case)
  10926. }
  10927. hp2 := p;
  10928. hp_lblxxx := hp1;
  10929. hp_flagalloc := nil;
  10930. hp_stop := nil;
  10931. FoundMatchingJump := False;
  10932. { Remember the first instruction in the first block of MOVs }
  10933. hpmov1 := hp1;
  10934. TransferUsedRegs(TmpUsedRegs);
  10935. while assigned(hp_lblxxx) and
  10936. { stop on labels }
  10937. (hp_lblxxx.typ <> ait_label) do
  10938. begin
  10939. { Keep track of all integer registers that are used }
  10940. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  10941. if hp_lblxxx.typ = ait_instruction then
  10942. begin
  10943. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  10944. IsJumpToLabel(taicpu(hp_lblxxx)) then
  10945. begin
  10946. hp_stop := hp_lblxxx;
  10947. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  10948. begin
  10949. { We found Jcc xxx; <several movs>; Jmp xxx }
  10950. FoundMatchingJump := True;
  10951. Break;
  10952. end;
  10953. { If it's not the jump we're looking for, it's
  10954. possibly the "if..else" variant }
  10955. end
  10956. { Check to see if we have a valid MOV instruction instead }
  10957. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  10958. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  10959. Break
  10960. else
  10961. { This will be a valid MOV }
  10962. hp_stop := hp_lblxxx;
  10963. end;
  10964. hp2 := hp_lblxxx;
  10965. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  10966. end;
  10967. { Just make sure the last MOV is included if there's no jump }
  10968. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  10969. hp_stop := hp_lblxxx;
  10970. { Note, the logic behind using hp_stop over hp_lblxxx in the
  10971. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  10972. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  10973. jmp yyy; xxx:; movs; yyy:" variation }
  10974. if assigned(hp_lblxxx) and
  10975. (
  10976. { If we found JMP xxx, we don't actually need a label
  10977. (hp_lblxxx is the JMP instruction instead) }
  10978. FoundMatchingJump or
  10979. { Make sure we actually have the right label }
  10980. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  10981. ) then
  10982. begin
  10983. { Use TmpUsedRegs to track registers that we reserve }
  10984. { When allocating temporary registers, try to look one
  10985. instruction back, as defining them before a CMP or TEST
  10986. instruction will be faster, and also avoid picking a
  10987. register that was only just deallocated }
  10988. if GetLastInstruction(p, hp_prev) and
  10989. 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
  10990. begin
  10991. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  10992. for l := 0 to 1 do
  10993. with taicpu(hp_prev).oper[l]^ do
  10994. case typ of
  10995. top_reg:
  10996. if getregtype(reg) = R_INTREGISTER then
  10997. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  10998. top_ref:
  10999. begin
  11000. if
  11001. {$ifdef x86_64}
  11002. (ref^.base <> NR_RIP) and
  11003. {$endif x86_64}
  11004. (ref^.base <> NR_NO) then
  11005. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11006. if (ref^.index <> NR_NO) then
  11007. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11008. end
  11009. else
  11010. ;
  11011. end;
  11012. { When inserting instructions before hp_prev, try to insert
  11013. them before the allocation of the FLAGS register }
  11014. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  11015. { If not found, set it equal to hp_prev so it's something sensible }
  11016. hp_flagalloc := hp_prev;
  11017. hp_prev2 := nil;
  11018. { When dealing with a comparison against zero, take
  11019. note of the instruction before it to see if we can
  11020. move instructions further back in order to benefit
  11021. PostPeepholeOptTestOr.
  11022. }
  11023. if (
  11024. (
  11025. (taicpu(hp_prev).opcode = A_CMP) and
  11026. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  11027. ) or
  11028. (
  11029. (taicpu(hp_prev).opcode = A_TEST) and
  11030. (
  11031. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  11032. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  11033. )
  11034. )
  11035. ) and
  11036. GetLastInstruction(hp_prev, hp_prev2) then
  11037. begin
  11038. if (hp_prev2.typ = ait_instruction) and
  11039. { These instructions set the zero flag if the result is zero }
  11040. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11041. begin
  11042. { Also mark all the registers in this previous instruction
  11043. as 'in use', even if they've just been deallocated }
  11044. for l := 0 to 1 do
  11045. with taicpu(hp_prev2).oper[l]^ do
  11046. case typ of
  11047. top_reg:
  11048. if getregtype(reg) = R_INTREGISTER then
  11049. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11050. top_ref:
  11051. begin
  11052. if
  11053. {$ifdef x86_64}
  11054. (ref^.base <> NR_RIP) and
  11055. {$endif x86_64}
  11056. (ref^.base <> NR_NO) then
  11057. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11058. if (ref^.index <> NR_NO) then
  11059. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11060. end
  11061. else
  11062. ;
  11063. end;
  11064. end
  11065. else
  11066. { Unsuitable instruction }
  11067. hp_prev2 := nil;
  11068. end;
  11069. end
  11070. else
  11071. begin
  11072. hp_prev := p;
  11073. { When inserting instructions before hp_prev, try to insert
  11074. them before the allocation of the FLAGS register }
  11075. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  11076. { If not found, set it equal to p so it's something sensible }
  11077. hp_flagalloc := p;
  11078. hp_prev2 := nil;
  11079. end;
  11080. l := 0;
  11081. c := 0;
  11082. { Initialise RegWrites, ConstRegs and ConstVals }
  11083. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11084. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11085. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11086. while assigned(hp1) and
  11087. { Stop on the label we found }
  11088. (hp1 <> hp_lblxxx) do
  11089. begin
  11090. case hp1.typ of
  11091. ait_instruction:
  11092. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11093. begin
  11094. if CanBeCMOV(hp1, hp_prev) then
  11095. Inc(l)
  11096. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11097. { CMOV with constants grows the code size }
  11098. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  11099. begin
  11100. { Register was reserved by TryCMOVConst and
  11101. stored on ConstRegs[c] }
  11102. end
  11103. else
  11104. Break;
  11105. end
  11106. else
  11107. Break;
  11108. else
  11109. ;
  11110. end;
  11111. GetNextInstruction(hp1,hp1);
  11112. end;
  11113. if (hp1 = hp_lblxxx) then
  11114. begin
  11115. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  11116. begin
  11117. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11118. TmpUsedRegs[R_INTREGISTER].Clear;
  11119. x := 0;
  11120. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  11121. condition := inverse_cond(taicpu(p).condition);
  11122. UpdateUsedRegs(tai(p.next));
  11123. hp1 := hpmov1;
  11124. repeat
  11125. if not Assigned(hp1) then
  11126. InternalError(2018062900);
  11127. if (hp1.typ = ait_instruction) then
  11128. begin
  11129. { Extra safeguard }
  11130. if (taicpu(hp1).opcode <> A_MOV) then
  11131. InternalError(2018062901);
  11132. if taicpu(hp1).oper[0]^.typ = top_const then
  11133. begin
  11134. if x >= MAX_CMOV_REGISTERS then
  11135. InternalError(2021100410);
  11136. { If it's in TmpUsedRegs, then this register
  11137. is being used more than once and hence has
  11138. already had its value defined (it gets
  11139. added to UsedRegs through AllocRegBetween
  11140. below) }
  11141. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11142. begin
  11143. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11144. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  11145. asml.InsertBefore(hp_new, hp_flagalloc);
  11146. if Assigned(hp_prev2) then
  11147. TrySwapMovOp(hp_prev2, hp_new);
  11148. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11149. end
  11150. else
  11151. { We just need an instruction between hp_prev and hp1
  11152. where we know the register is marked as in use }
  11153. hp_new := hpmov1;
  11154. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11155. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11156. Inc(x);
  11157. end;
  11158. taicpu(hp1).opcode := A_CMOVcc;
  11159. taicpu(hp1).condition := condition;
  11160. end;
  11161. UpdateUsedRegs(tai(hp1.next));
  11162. GetNextInstruction(hp1, hp1);
  11163. until (hp1 = hp_lblxxx);
  11164. hp2 := hp_lblxxx;
  11165. repeat
  11166. if not Assigned(hp2) then
  11167. InternalError(2018062910);
  11168. case hp2.typ of
  11169. ait_label:
  11170. { What we expected - break out of the loop (it won't be a dead label at the top of
  11171. a cluster because that was optimised at an earlier stage) }
  11172. Break;
  11173. ait_align:
  11174. { Go to the next entry until a label is found (may be multiple aligns before it) }
  11175. begin
  11176. hp2 := tai(hp2.Next);
  11177. Continue;
  11178. end;
  11179. ait_instruction:
  11180. begin
  11181. if taicpu(hp2).opcode<>A_JMP then
  11182. InternalError(2018062912);
  11183. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  11184. Break;
  11185. end
  11186. else
  11187. begin
  11188. { Might be a comment or temporary allocation entry }
  11189. if not (hp2.typ in SkipInstr) then
  11190. InternalError(2018062911);
  11191. hp2 := tai(hp2.Next);
  11192. Continue;
  11193. end;
  11194. end;
  11195. until False;
  11196. { Now we can safely decrement the reference count }
  11197. tasmlabel(symbol).decrefs;
  11198. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  11199. { Remove the original jump }
  11200. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  11201. if hp2.typ=ait_instruction then
  11202. begin
  11203. p := hp2;
  11204. Result := True;
  11205. end
  11206. else
  11207. begin
  11208. UpdateUsedRegs(tai(hp2.next));
  11209. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  11210. { Remove the label if this is its final reference }
  11211. if (tasmlabel(symbol).getrefs=0) then
  11212. begin
  11213. { Make sure the aligns get stripped too }
  11214. hp1 := tai(hp_lblxxx.Previous);
  11215. while Assigned(hp1) and (hp1.typ = ait_align) do
  11216. begin
  11217. hp_lblxxx := hp1;
  11218. hp1 := tai(hp_lblxxx.Previous);
  11219. end;
  11220. StripLabelFast(hp_lblxxx);
  11221. end;
  11222. end;
  11223. Exit;
  11224. end;
  11225. end
  11226. else if assigned(hp_lblxxx) and
  11227. { check further for
  11228. jCC xxx
  11229. <several movs 1>
  11230. jmp yyy
  11231. xxx:
  11232. <several movs 2>
  11233. yyy:
  11234. }
  11235. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11236. { hp1 should be pointing to jmp yyy }
  11237. MatchInstruction(hp1, A_JMP, []) and
  11238. { real label and jump, no further references to the
  11239. label are allowed }
  11240. (TAsmLabel(symbol).getrefs=1) and
  11241. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  11242. begin
  11243. hp_jump := hp1;
  11244. { Don't set c to zero }
  11245. l := 0;
  11246. w := 0;
  11247. GetNextInstruction(hp_lblxxx, hpmov2);
  11248. hp2 := hp_lblxxx;
  11249. hp_lblyyy := hpmov2;
  11250. while assigned(hp_lblyyy) and
  11251. { stop on labels }
  11252. (hp_lblyyy.typ <> ait_label) do
  11253. begin
  11254. { Keep track of all integer registers that are used }
  11255. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11256. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11257. Break;
  11258. hp2 := hp_lblyyy;
  11259. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  11260. end;
  11261. { Analyse the second batch of MOVs to see if the setup is valid }
  11262. hp1 := hpmov2;
  11263. while assigned(hp1) and
  11264. (hp1 <> hp_lblyyy) do
  11265. begin
  11266. case hp1.typ of
  11267. ait_instruction:
  11268. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11269. begin
  11270. if CanBeCMOV(hp1, hp_prev) then
  11271. Inc(l)
  11272. else if not (cs_opt_size in current_settings.optimizerswitches)
  11273. { CMOV with constants grows the code size }
  11274. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  11275. begin
  11276. { Register was reserved by TryCMOVConst and
  11277. stored on ConstRegs[c] }
  11278. end
  11279. else
  11280. Break;
  11281. end
  11282. else
  11283. Break;
  11284. else
  11285. ;
  11286. end;
  11287. GetNextInstruction(hp1,hp1);
  11288. end;
  11289. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11290. TmpUsedRegs[R_INTREGISTER].Clear;
  11291. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11292. (hp1 = hp_lblyyy) and
  11293. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  11294. begin
  11295. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  11296. second_condition := taicpu(p).condition;
  11297. condition := inverse_cond(taicpu(p).condition);
  11298. UpdateUsedRegs(tai(p.next));
  11299. { Scan through the first set of MOVs to update UsedRegs,
  11300. but don't process them yet }
  11301. hp1 := hpmov1;
  11302. repeat
  11303. if not Assigned(hp1) then
  11304. InternalError(2018062901);
  11305. UpdateUsedRegs(tai(hp1.next));
  11306. GetNextInstruction(hp1, hp1);
  11307. until (hp1 = hp_lblxxx);
  11308. UpdateUsedRegs(tai(hp_lblxxx.next));
  11309. { Process the second set of MOVs first,
  11310. because if a destination register is
  11311. shared between the first and second MOV
  11312. sets, it is more efficient to turn the
  11313. first one into a MOV instruction and place
  11314. it before the CMP if possible, but we
  11315. won't know which registers are shared
  11316. until we've processed at least one list,
  11317. so we might as well make it the second
  11318. one since that won't be modified again. }
  11319. hp1 := hpmov2;
  11320. repeat
  11321. if not Assigned(hp1) then
  11322. InternalError(2018062902);
  11323. if (hp1.typ = ait_instruction) then
  11324. begin
  11325. { Extra safeguard }
  11326. if (taicpu(hp1).opcode <> A_MOV) then
  11327. InternalError(2018062903);
  11328. if taicpu(hp1).oper[0]^.typ = top_const then
  11329. begin
  11330. RegMatch := False;
  11331. for x := 0 to c - 1 do
  11332. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11333. begin
  11334. RegMatch := True;
  11335. { If it's in TmpUsedRegs, then this register
  11336. is being used more than once and hence has
  11337. already had its value defined (it gets
  11338. added to UsedRegs through AllocRegBetween
  11339. below) }
  11340. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11341. begin
  11342. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11343. asml.InsertBefore(hp_new, hp_flagalloc);
  11344. if Assigned(hp_prev2) then
  11345. TrySwapMovOp(hp_prev2, hp_new);
  11346. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11347. end
  11348. else
  11349. { We just need an instruction between hp_prev and hp1
  11350. where we know the register is marked as in use }
  11351. hp_new := hpmov2;
  11352. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11353. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11354. Break;
  11355. end;
  11356. if not RegMatch then
  11357. InternalError(2021100411);
  11358. end;
  11359. taicpu(hp1).opcode := A_CMOVcc;
  11360. taicpu(hp1).condition := second_condition;
  11361. { Store these writes to search for
  11362. duplicates later on }
  11363. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11364. Inc(w);
  11365. end;
  11366. UpdateUsedRegs(tai(hp1.next));
  11367. GetNextInstruction(hp1, hp1);
  11368. until (hp1 = hp_lblyyy);
  11369. { Now do the first set of MOVs }
  11370. hp1 := hpmov1;
  11371. repeat
  11372. if not Assigned(hp1) then
  11373. InternalError(2018062904);
  11374. if (hp1.typ = ait_instruction) then
  11375. begin
  11376. RegMatch := False;
  11377. { Extra safeguard }
  11378. if (taicpu(hp1).opcode <> A_MOV) then
  11379. InternalError(2018062905);
  11380. { Search through the RegWrites list to see
  11381. if there are any opposing CMOV pairs that
  11382. write to the same register }
  11383. for x := 0 to w - 1 do
  11384. if (RegWrites[x] = taicpu(hp1).oper[1]^.reg) then
  11385. begin
  11386. { We have a match. Keep this as a MOV }
  11387. { Move ahead in preparation }
  11388. GetNextInstruction(hp1, hp1);
  11389. RegMatch := True;
  11390. Break;
  11391. end;
  11392. if RegMatch then
  11393. Continue;
  11394. if taicpu(hp1).oper[0]^.typ = top_const then
  11395. begin
  11396. RegMatch := False;
  11397. for x := 0 to c - 1 do
  11398. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11399. begin
  11400. RegMatch := True;
  11401. { If it's in TmpUsedRegs, then this register
  11402. is being used more than once and hence has
  11403. already had its value defined (it gets
  11404. added to UsedRegs through AllocRegBetween
  11405. below) }
  11406. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11407. begin
  11408. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11409. asml.InsertBefore(hp_new, hp_flagalloc);
  11410. if Assigned(hp_prev2) then
  11411. TrySwapMovOp(hp_prev2, hp_new);
  11412. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11413. end
  11414. else
  11415. { We just need an instruction between hp_prev and hp1
  11416. where we know the register is marked as in use }
  11417. hp_new := hpmov1;
  11418. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11419. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11420. Break;
  11421. end;
  11422. if not RegMatch then
  11423. InternalError(2021100412);
  11424. end;
  11425. taicpu(hp1).opcode := A_CMOVcc;
  11426. taicpu(hp1).condition := condition;
  11427. end;
  11428. GetNextInstruction(hp1, hp1);
  11429. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11430. UpdateUsedRegs(tai(hp_jump.next));
  11431. UpdateUsedRegs(tai(hp_lblyyy.next));
  11432. { Get first instruction after label }
  11433. hp1 := p;
  11434. GetNextInstruction(hp_lblyyy, p);
  11435. { Don't dereference yet, as doing so will cause
  11436. GetNextInstruction to skip the label and
  11437. optional align marker. [Kit] }
  11438. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11439. { remove Jcc }
  11440. RemoveInstruction(hp1);
  11441. { Now we can safely decrement it }
  11442. tasmlabel(symbol).decrefs;
  11443. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11444. { Make sure the aligns get stripped too }
  11445. hp1 := tai(hp_lblxxx.Previous);
  11446. while Assigned(hp1) and (hp1.typ = ait_align) do
  11447. begin
  11448. hp_lblxxx := hp1;
  11449. hp1 := tai(hp_lblxxx.Previous);
  11450. end;
  11451. StripLabelFast(hp_lblxxx);
  11452. { remove jmp }
  11453. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11454. RemoveInstruction(hp_jump);
  11455. { As before, now we can safely decrement it }
  11456. TAsmLabel(symbol).decrefs;
  11457. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11458. if TAsmLabel(symbol).getrefs = 0 then
  11459. begin
  11460. { Make sure the aligns get stripped too }
  11461. hp1 := tai(hp_lblyyy.Previous);
  11462. while Assigned(hp1) and (hp1.typ = ait_align) do
  11463. begin
  11464. hp_lblyyy := hp1;
  11465. hp1 := tai(hp_lblyyy.Previous);
  11466. end;
  11467. StripLabelFast(hp_lblyyy);
  11468. end;
  11469. if Assigned(p) then
  11470. result := True;
  11471. exit;
  11472. end;
  11473. end;
  11474. end;
  11475. {$endif i8086}
  11476. end;
  11477. end;
  11478. end;
  11479. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11480. var
  11481. hp1,hp2,hp3: tai;
  11482. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11483. NewSize: TOpSize;
  11484. NewRegSize: TSubRegister;
  11485. Limit: TCgInt;
  11486. SwapOper: POper;
  11487. begin
  11488. result:=false;
  11489. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11490. GetNextInstruction(p,hp1) and
  11491. (hp1.typ = ait_instruction);
  11492. if reg_and_hp1_is_instr and
  11493. (
  11494. (taicpu(hp1).opcode <> A_LEA) or
  11495. { If the LEA instruction can be converted into an arithmetic instruction,
  11496. it may be possible to then fold it. }
  11497. (
  11498. { If the flags register is in use, don't change the instruction
  11499. to an ADD otherwise this will scramble the flags. [Kit] }
  11500. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11501. ConvertLEA(taicpu(hp1))
  11502. )
  11503. ) and
  11504. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11505. GetNextInstruction(hp1,hp2) and
  11506. MatchInstruction(hp2,A_MOV,[]) and
  11507. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11508. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11509. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11510. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11511. {$ifdef i386}
  11512. { not all registers have byte size sub registers on i386 }
  11513. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11514. {$endif i386}
  11515. (((taicpu(hp1).ops=2) and
  11516. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11517. ((taicpu(hp1).ops=1) and
  11518. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11519. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11520. begin
  11521. { change movsX/movzX reg/ref, reg2
  11522. add/sub/or/... reg3/$const, reg2
  11523. mov reg2 reg/ref
  11524. to add/sub/or/... reg3/$const, reg/ref }
  11525. { by example:
  11526. movswl %si,%eax movswl %si,%eax p
  11527. decl %eax addl %edx,%eax hp1
  11528. movw %ax,%si movw %ax,%si hp2
  11529. ->
  11530. movswl %si,%eax movswl %si,%eax p
  11531. decw %eax addw %edx,%eax hp1
  11532. movw %ax,%si movw %ax,%si hp2
  11533. }
  11534. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11535. {
  11536. ->
  11537. movswl %si,%eax movswl %si,%eax p
  11538. decw %si addw %dx,%si hp1
  11539. movw %ax,%si movw %ax,%si hp2
  11540. }
  11541. case taicpu(hp1).ops of
  11542. 1:
  11543. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11544. 2:
  11545. begin
  11546. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11547. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11548. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11549. end;
  11550. else
  11551. internalerror(2008042702);
  11552. end;
  11553. {
  11554. ->
  11555. decw %si addw %dx,%si p
  11556. }
  11557. DebugMsg(SPeepholeOptimization + 'var3',p);
  11558. RemoveCurrentP(p, hp1);
  11559. RemoveInstruction(hp2);
  11560. Result := True;
  11561. Exit;
  11562. end;
  11563. if reg_and_hp1_is_instr and
  11564. (taicpu(hp1).opcode = A_MOV) and
  11565. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11566. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11567. {$ifdef x86_64}
  11568. { check for implicit extension to 64 bit }
  11569. or
  11570. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11571. (taicpu(hp1).opsize=S_Q) and
  11572. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11573. )
  11574. {$endif x86_64}
  11575. )
  11576. then
  11577. begin
  11578. { change
  11579. movx %reg1,%reg2
  11580. mov %reg2,%reg3
  11581. dealloc %reg2
  11582. into
  11583. movx %reg,%reg3
  11584. }
  11585. TransferUsedRegs(TmpUsedRegs);
  11586. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11587. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11588. begin
  11589. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11590. {$ifdef x86_64}
  11591. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11592. (taicpu(hp1).opsize=S_Q) then
  11593. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11594. else
  11595. {$endif x86_64}
  11596. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11597. RemoveInstruction(hp1);
  11598. Result := True;
  11599. Exit;
  11600. end;
  11601. end;
  11602. if reg_and_hp1_is_instr and
  11603. ((taicpu(hp1).opcode=A_MOV) or
  11604. (taicpu(hp1).opcode=A_ADD) or
  11605. (taicpu(hp1).opcode=A_SUB) or
  11606. (taicpu(hp1).opcode=A_CMP) or
  11607. (taicpu(hp1).opcode=A_OR) or
  11608. (taicpu(hp1).opcode=A_XOR) or
  11609. (taicpu(hp1).opcode=A_AND)
  11610. ) and
  11611. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11612. begin
  11613. AndTest := (taicpu(hp1).opcode=A_AND) and
  11614. GetNextInstruction(hp1, hp2) and
  11615. (hp2.typ = ait_instruction) and
  11616. (
  11617. (
  11618. (taicpu(hp2).opcode=A_TEST) and
  11619. (
  11620. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11621. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11622. (
  11623. { If the AND and TEST instructions share a constant, this is also valid }
  11624. (taicpu(hp1).oper[0]^.typ = top_const) and
  11625. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11626. )
  11627. ) and
  11628. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11629. ) or
  11630. (
  11631. (taicpu(hp2).opcode=A_CMP) and
  11632. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11633. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11634. )
  11635. );
  11636. { change
  11637. movx (oper),%reg2
  11638. and $x,%reg2
  11639. test %reg2,%reg2
  11640. dealloc %reg2
  11641. into
  11642. op %reg1,%reg3
  11643. if the second op accesses only the bits stored in reg1
  11644. }
  11645. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11646. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11647. (taicpu(hp1).oper[0]^.typ = top_const) and
  11648. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11649. AndTest then
  11650. begin
  11651. { Check if the AND constant is in range }
  11652. case taicpu(p).opsize of
  11653. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11654. begin
  11655. NewSize := S_B;
  11656. Limit := $FF;
  11657. end;
  11658. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11659. begin
  11660. NewSize := S_W;
  11661. Limit := $FFFF;
  11662. end;
  11663. {$ifdef x86_64}
  11664. S_LQ:
  11665. begin
  11666. NewSize := S_L;
  11667. Limit := $FFFFFFFF;
  11668. end;
  11669. {$endif x86_64}
  11670. else
  11671. InternalError(2021120303);
  11672. end;
  11673. if (
  11674. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11675. { Check for negative operands }
  11676. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11677. ) and
  11678. GetNextInstruction(hp2,hp3) and
  11679. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11680. (taicpu(hp3).condition in [C_E,C_NE]) then
  11681. begin
  11682. TransferUsedRegs(TmpUsedRegs);
  11683. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11684. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11685. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11686. begin
  11687. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11688. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11689. taicpu(hp1).opcode := A_TEST;
  11690. taicpu(hp1).opsize := NewSize;
  11691. RemoveInstruction(hp2);
  11692. RemoveCurrentP(p, hp1);
  11693. Result:=true;
  11694. exit;
  11695. end;
  11696. end;
  11697. end;
  11698. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11699. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11700. (taicpu(hp1).opsize=S_B)) or
  11701. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11702. (taicpu(hp1).opsize=S_W))
  11703. {$ifdef x86_64}
  11704. or ((taicpu(p).opsize=S_LQ) and
  11705. (taicpu(hp1).opsize=S_L))
  11706. {$endif x86_64}
  11707. ) and
  11708. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11709. begin
  11710. { change
  11711. movx %reg1,%reg2
  11712. op %reg2,%reg3
  11713. dealloc %reg2
  11714. into
  11715. op %reg1,%reg3
  11716. if the second op accesses only the bits stored in reg1
  11717. }
  11718. TransferUsedRegs(TmpUsedRegs);
  11719. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11720. if AndTest then
  11721. begin
  11722. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11723. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11724. end
  11725. else
  11726. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11727. if not RegUsed then
  11728. begin
  11729. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11730. if taicpu(p).oper[0]^.typ=top_reg then
  11731. begin
  11732. case taicpu(hp1).opsize of
  11733. S_B:
  11734. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11735. S_W:
  11736. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11737. S_L:
  11738. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11739. else
  11740. Internalerror(2020102301);
  11741. end;
  11742. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11743. end
  11744. else
  11745. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11746. RemoveCurrentP(p);
  11747. if AndTest then
  11748. RemoveInstruction(hp2);
  11749. result:=true;
  11750. exit;
  11751. end;
  11752. end
  11753. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11754. (
  11755. { Bitwise operations only }
  11756. (taicpu(hp1).opcode=A_AND) or
  11757. (taicpu(hp1).opcode=A_TEST) or
  11758. (
  11759. (taicpu(hp1).oper[0]^.typ = top_const) and
  11760. (
  11761. (taicpu(hp1).opcode=A_OR) or
  11762. (taicpu(hp1).opcode=A_XOR)
  11763. )
  11764. )
  11765. ) and
  11766. (
  11767. (taicpu(hp1).oper[0]^.typ = top_const) or
  11768. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11769. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11770. ) then
  11771. begin
  11772. { change
  11773. movx %reg2,%reg2
  11774. op const,%reg2
  11775. into
  11776. op const,%reg2 (smaller version)
  11777. movx %reg2,%reg2
  11778. also change
  11779. movx %reg1,%reg2
  11780. and/test (oper),%reg2
  11781. dealloc %reg2
  11782. into
  11783. and/test (oper),%reg1
  11784. }
  11785. case taicpu(p).opsize of
  11786. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11787. begin
  11788. NewSize := S_B;
  11789. NewRegSize := R_SUBL;
  11790. Limit := $FF;
  11791. end;
  11792. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11793. begin
  11794. NewSize := S_W;
  11795. NewRegSize := R_SUBW;
  11796. Limit := $FFFF;
  11797. end;
  11798. {$ifdef x86_64}
  11799. S_LQ:
  11800. begin
  11801. NewSize := S_L;
  11802. NewRegSize := R_SUBD;
  11803. Limit := $FFFFFFFF;
  11804. end;
  11805. {$endif x86_64}
  11806. else
  11807. Internalerror(2021120302);
  11808. end;
  11809. TransferUsedRegs(TmpUsedRegs);
  11810. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11811. if AndTest then
  11812. begin
  11813. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11814. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11815. end
  11816. else
  11817. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11818. if
  11819. (
  11820. (taicpu(p).opcode = A_MOVZX) and
  11821. (
  11822. (taicpu(hp1).opcode=A_AND) or
  11823. (taicpu(hp1).opcode=A_TEST)
  11824. ) and
  11825. not (
  11826. { If both are references, then the final instruction will have
  11827. both operands as references, which is not allowed }
  11828. (taicpu(p).oper[0]^.typ = top_ref) and
  11829. (taicpu(hp1).oper[0]^.typ = top_ref)
  11830. ) and
  11831. not RegUsed
  11832. ) or
  11833. (
  11834. (
  11835. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  11836. not RegUsed
  11837. ) and
  11838. (taicpu(p).oper[0]^.typ = top_reg) and
  11839. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11840. (taicpu(hp1).oper[0]^.typ = top_const) and
  11841. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  11842. ) then
  11843. begin
  11844. {$if defined(i386) or defined(i8086)}
  11845. { If the target size is 8-bit, make sure we can actually encode it }
  11846. 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
  11847. Exit;
  11848. {$endif i386 or i8086}
  11849. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  11850. taicpu(hp1).opsize := NewSize;
  11851. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11852. if AndTest then
  11853. begin
  11854. RemoveInstruction(hp2);
  11855. if not RegUsed then
  11856. begin
  11857. taicpu(hp1).opcode := A_TEST;
  11858. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  11859. begin
  11860. { Make sure the reference is the second operand }
  11861. SwapOper := taicpu(hp1).oper[0];
  11862. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  11863. taicpu(hp1).oper[1] := SwapOper;
  11864. end;
  11865. end;
  11866. end;
  11867. case taicpu(hp1).oper[0]^.typ of
  11868. top_reg:
  11869. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  11870. top_const:
  11871. { For the AND/TEST case }
  11872. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  11873. else
  11874. ;
  11875. end;
  11876. if RegUsed then
  11877. begin
  11878. AsmL.Remove(p);
  11879. AsmL.InsertAfter(p, hp1);
  11880. p := hp1;
  11881. end
  11882. else
  11883. RemoveCurrentP(p, hp1);
  11884. result:=true;
  11885. exit;
  11886. end;
  11887. end;
  11888. end;
  11889. if reg_and_hp1_is_instr and
  11890. (taicpu(p).oper[0]^.typ = top_reg) and
  11891. (
  11892. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  11893. ) and
  11894. (taicpu(hp1).oper[0]^.typ = top_const) and
  11895. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11896. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11897. { Minimum shift value allowed is the bit difference between the sizes }
  11898. (taicpu(hp1).oper[0]^.val >=
  11899. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11900. 8 * (
  11901. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  11902. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11903. )
  11904. ) then
  11905. begin
  11906. { For:
  11907. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  11908. shl/sal ##, %reg1
  11909. Remove the movsx/movzx instruction if the shift overwrites the
  11910. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  11911. }
  11912. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  11913. RemoveCurrentP(p, hp1);
  11914. Result := True;
  11915. Exit;
  11916. end
  11917. else if reg_and_hp1_is_instr and
  11918. (taicpu(p).oper[0]^.typ = top_reg) and
  11919. (
  11920. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  11921. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  11922. ) and
  11923. (taicpu(hp1).oper[0]^.typ = top_const) and
  11924. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11925. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11926. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  11927. (taicpu(hp1).oper[0]^.val <
  11928. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11929. 8 * (
  11930. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11931. )
  11932. ) then
  11933. begin
  11934. { For:
  11935. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  11936. sar ##, %reg1 shr ##, %reg1
  11937. Move the shift to before the movx instruction if the shift value
  11938. is not too large.
  11939. }
  11940. asml.Remove(hp1);
  11941. asml.InsertBefore(hp1, p);
  11942. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11943. case taicpu(p).opsize of
  11944. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  11945. taicpu(hp1).opsize := S_B;
  11946. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  11947. taicpu(hp1).opsize := S_W;
  11948. {$ifdef x86_64}
  11949. S_LQ:
  11950. taicpu(hp1).opsize := S_L;
  11951. {$endif}
  11952. else
  11953. InternalError(2020112401);
  11954. end;
  11955. if (taicpu(hp1).opcode = A_SHR) then
  11956. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  11957. else
  11958. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  11959. Result := True;
  11960. end;
  11961. if reg_and_hp1_is_instr and
  11962. (taicpu(p).oper[0]^.typ = top_reg) and
  11963. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11964. (
  11965. (taicpu(hp1).opcode = taicpu(p).opcode)
  11966. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  11967. {$ifdef x86_64}
  11968. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  11969. {$endif x86_64}
  11970. ) then
  11971. begin
  11972. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  11973. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  11974. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11975. begin
  11976. {
  11977. For example:
  11978. movzbw %al,%ax
  11979. movzwl %ax,%eax
  11980. Compress into:
  11981. movzbl %al,%eax
  11982. }
  11983. RegUsed := False;
  11984. case taicpu(p).opsize of
  11985. S_BW:
  11986. case taicpu(hp1).opsize of
  11987. S_WL:
  11988. begin
  11989. taicpu(p).opsize := S_BL;
  11990. RegUsed := True;
  11991. end;
  11992. {$ifdef x86_64}
  11993. S_WQ:
  11994. begin
  11995. if taicpu(p).opcode = A_MOVZX then
  11996. begin
  11997. taicpu(p).opsize := S_BL;
  11998. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11999. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12000. end
  12001. else
  12002. taicpu(p).opsize := S_BQ;
  12003. RegUsed := True;
  12004. end;
  12005. {$endif x86_64}
  12006. else
  12007. ;
  12008. end;
  12009. {$ifdef x86_64}
  12010. S_BL:
  12011. case taicpu(hp1).opsize of
  12012. S_LQ:
  12013. begin
  12014. if taicpu(p).opcode = A_MOVZX then
  12015. begin
  12016. taicpu(p).opsize := S_BL;
  12017. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12018. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12019. end
  12020. else
  12021. taicpu(p).opsize := S_BQ;
  12022. RegUsed := True;
  12023. end;
  12024. else
  12025. ;
  12026. end;
  12027. S_WL:
  12028. case taicpu(hp1).opsize of
  12029. S_LQ:
  12030. begin
  12031. if taicpu(p).opcode = A_MOVZX then
  12032. begin
  12033. taicpu(p).opsize := S_WL;
  12034. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12035. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12036. end
  12037. else
  12038. taicpu(p).opsize := S_WQ;
  12039. RegUsed := True;
  12040. end;
  12041. else
  12042. ;
  12043. end;
  12044. {$endif x86_64}
  12045. else
  12046. ;
  12047. end;
  12048. if RegUsed then
  12049. begin
  12050. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12051. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12052. RemoveInstruction(hp1);
  12053. Result := True;
  12054. Exit;
  12055. end;
  12056. end;
  12057. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12058. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12059. GetNextInstruction(hp1, hp2) and
  12060. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12061. (
  12062. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12063. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12064. {$ifdef x86_64}
  12065. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12066. {$endif x86_64}
  12067. ) and
  12068. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12069. (
  12070. (
  12071. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12072. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12073. ) or
  12074. (
  12075. { Only allow the operands in reverse order for TEST instructions }
  12076. (taicpu(hp2).opcode = A_TEST) and
  12077. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12078. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12079. )
  12080. ) then
  12081. begin
  12082. {
  12083. For example:
  12084. movzbl %al,%eax
  12085. movzbl (ref),%edx
  12086. andl %edx,%eax
  12087. (%edx deallocated)
  12088. Change to:
  12089. andb (ref),%al
  12090. movzbl %al,%eax
  12091. Rules are:
  12092. - First two instructions have the same opcode and opsize
  12093. - First instruction's operands are the same super-register
  12094. - Second instruction operates on a different register
  12095. - Third instruction is AND, OR, XOR or TEST
  12096. - Third instruction's operands are the destination registers of the first two instructions
  12097. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12098. - Second instruction's destination register is deallocated afterwards
  12099. }
  12100. TransferUsedRegs(TmpUsedRegs);
  12101. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12102. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12103. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12104. begin
  12105. case taicpu(p).opsize of
  12106. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12107. NewSize := S_B;
  12108. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12109. NewSize := S_W;
  12110. {$ifdef x86_64}
  12111. S_LQ:
  12112. NewSize := S_L;
  12113. {$endif x86_64}
  12114. else
  12115. InternalError(2021120301);
  12116. end;
  12117. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12118. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12119. taicpu(hp2).opsize := NewSize;
  12120. RemoveInstruction(hp1);
  12121. { With TEST, it's best to keep the MOVX instruction at the top }
  12122. if (taicpu(hp2).opcode <> A_TEST) then
  12123. begin
  12124. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12125. asml.Remove(p);
  12126. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12127. asml.InsertAfter(p, hp2);
  12128. p := hp2;
  12129. end
  12130. else
  12131. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12132. Result := True;
  12133. Exit;
  12134. end;
  12135. end;
  12136. end;
  12137. if taicpu(p).opcode=A_MOVZX then
  12138. begin
  12139. { removes superfluous And's after movzx's }
  12140. if reg_and_hp1_is_instr and
  12141. (taicpu(hp1).opcode = A_AND) and
  12142. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12143. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12144. {$ifdef x86_64}
  12145. { check for implicit extension to 64 bit }
  12146. or
  12147. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12148. (taicpu(hp1).opsize=S_Q) and
  12149. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12150. )
  12151. {$endif x86_64}
  12152. )
  12153. then
  12154. begin
  12155. case taicpu(p).opsize Of
  12156. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12157. if (taicpu(hp1).oper[0]^.val = $ff) then
  12158. begin
  12159. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12160. RemoveInstruction(hp1);
  12161. Result:=true;
  12162. exit;
  12163. end;
  12164. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12165. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12166. begin
  12167. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12168. RemoveInstruction(hp1);
  12169. Result:=true;
  12170. exit;
  12171. end;
  12172. {$ifdef x86_64}
  12173. S_LQ:
  12174. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12175. begin
  12176. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12177. RemoveInstruction(hp1);
  12178. Result:=true;
  12179. exit;
  12180. end;
  12181. {$endif x86_64}
  12182. else
  12183. ;
  12184. end;
  12185. { we cannot get rid of the and, but can we get rid of the movz ?}
  12186. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12187. begin
  12188. case taicpu(p).opsize Of
  12189. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12190. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12191. begin
  12192. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12193. RemoveCurrentP(p,hp1);
  12194. Result:=true;
  12195. exit;
  12196. end;
  12197. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12198. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12199. begin
  12200. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12201. RemoveCurrentP(p,hp1);
  12202. Result:=true;
  12203. exit;
  12204. end;
  12205. {$ifdef x86_64}
  12206. S_LQ:
  12207. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12208. begin
  12209. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12210. RemoveCurrentP(p,hp1);
  12211. Result:=true;
  12212. exit;
  12213. end;
  12214. {$endif x86_64}
  12215. else
  12216. ;
  12217. end;
  12218. end;
  12219. end;
  12220. { changes some movzx constructs to faster synonyms (all examples
  12221. are given with eax/ax, but are also valid for other registers)}
  12222. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12223. begin
  12224. case taicpu(p).opsize of
  12225. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12226. (the machine code is equivalent to movzbl %al,%eax), but the
  12227. code generator still generates that assembler instruction and
  12228. it is silently converted. This should probably be checked.
  12229. [Kit] }
  12230. S_BW:
  12231. begin
  12232. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12233. (
  12234. not IsMOVZXAcceptable
  12235. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12236. or (
  12237. (cs_opt_size in current_settings.optimizerswitches) and
  12238. (taicpu(p).oper[1]^.reg = NR_AX)
  12239. )
  12240. ) then
  12241. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12242. begin
  12243. DebugMsg(SPeepholeOptimization + 'var7',p);
  12244. taicpu(p).opcode := A_AND;
  12245. taicpu(p).changeopsize(S_W);
  12246. taicpu(p).loadConst(0,$ff);
  12247. Result := True;
  12248. end
  12249. else if not IsMOVZXAcceptable and
  12250. GetNextInstruction(p, hp1) and
  12251. (tai(hp1).typ = ait_instruction) and
  12252. (taicpu(hp1).opcode = A_AND) and
  12253. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12254. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12255. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12256. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12257. begin
  12258. DebugMsg(SPeepholeOptimization + 'var8',p);
  12259. taicpu(p).opcode := A_MOV;
  12260. taicpu(p).changeopsize(S_W);
  12261. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12262. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12263. Result := True;
  12264. end;
  12265. end;
  12266. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12267. S_BL:
  12268. if not IsMOVZXAcceptable then
  12269. begin
  12270. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12271. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12272. begin
  12273. DebugMsg(SPeepholeOptimization + 'var9',p);
  12274. taicpu(p).opcode := A_AND;
  12275. taicpu(p).changeopsize(S_L);
  12276. taicpu(p).loadConst(0,$ff);
  12277. Result := True;
  12278. end
  12279. else if GetNextInstruction(p, hp1) and
  12280. (tai(hp1).typ = ait_instruction) and
  12281. (taicpu(hp1).opcode = A_AND) and
  12282. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12283. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12284. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12285. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12286. begin
  12287. DebugMsg(SPeepholeOptimization + 'var10',p);
  12288. taicpu(p).opcode := A_MOV;
  12289. taicpu(p).changeopsize(S_L);
  12290. { do not use R_SUBWHOLE
  12291. as movl %rdx,%eax
  12292. is invalid in assembler PM }
  12293. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12294. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12295. Result := True;
  12296. end;
  12297. end;
  12298. {$endif i8086}
  12299. S_WL:
  12300. if not IsMOVZXAcceptable then
  12301. begin
  12302. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12303. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12304. begin
  12305. DebugMsg(SPeepholeOptimization + 'var11',p);
  12306. taicpu(p).opcode := A_AND;
  12307. taicpu(p).changeopsize(S_L);
  12308. taicpu(p).loadConst(0,$ffff);
  12309. Result := True;
  12310. end
  12311. else if GetNextInstruction(p, hp1) and
  12312. (tai(hp1).typ = ait_instruction) and
  12313. (taicpu(hp1).opcode = A_AND) and
  12314. (taicpu(hp1).oper[0]^.typ = top_const) and
  12315. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12316. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12317. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12318. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12319. begin
  12320. DebugMsg(SPeepholeOptimization + 'var12',p);
  12321. taicpu(p).opcode := A_MOV;
  12322. taicpu(p).changeopsize(S_L);
  12323. { do not use R_SUBWHOLE
  12324. as movl %rdx,%eax
  12325. is invalid in assembler PM }
  12326. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12327. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12328. Result := True;
  12329. end;
  12330. end;
  12331. else
  12332. InternalError(2017050705);
  12333. end;
  12334. end
  12335. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12336. begin
  12337. if GetNextInstruction(p, hp1) and
  12338. (tai(hp1).typ = ait_instruction) and
  12339. (taicpu(hp1).opcode = A_AND) and
  12340. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12341. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12342. begin
  12343. //taicpu(p).opcode := A_MOV;
  12344. case taicpu(p).opsize Of
  12345. S_BL:
  12346. begin
  12347. DebugMsg(SPeepholeOptimization + 'var13',p);
  12348. taicpu(hp1).changeopsize(S_L);
  12349. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12350. end;
  12351. S_WL:
  12352. begin
  12353. DebugMsg(SPeepholeOptimization + 'var14',p);
  12354. taicpu(hp1).changeopsize(S_L);
  12355. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12356. end;
  12357. S_BW:
  12358. begin
  12359. DebugMsg(SPeepholeOptimization + 'var15',p);
  12360. taicpu(hp1).changeopsize(S_W);
  12361. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12362. end;
  12363. else
  12364. Internalerror(2017050704)
  12365. end;
  12366. Result := True;
  12367. end;
  12368. end;
  12369. end;
  12370. end;
  12371. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12372. var
  12373. hp1, hp2 : tai;
  12374. MaskLength : Cardinal;
  12375. MaskedBits : TCgInt;
  12376. ActiveReg : TRegister;
  12377. begin
  12378. Result:=false;
  12379. { There are no optimisations for reference targets }
  12380. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12381. Exit;
  12382. while GetNextInstruction(p, hp1) and
  12383. (hp1.typ = ait_instruction) do
  12384. begin
  12385. if (taicpu(p).oper[0]^.typ = top_const) then
  12386. begin
  12387. case taicpu(hp1).opcode of
  12388. A_AND:
  12389. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12390. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12391. { the second register must contain the first one, so compare their subreg types }
  12392. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12393. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12394. { change
  12395. and const1, reg
  12396. and const2, reg
  12397. to
  12398. and (const1 and const2), reg
  12399. }
  12400. begin
  12401. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12402. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12403. RemoveCurrentP(p, hp1);
  12404. Result:=true;
  12405. exit;
  12406. end;
  12407. A_CMP:
  12408. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12409. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12410. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12411. { Just check that the condition on the next instruction is compatible }
  12412. GetNextInstruction(hp1, hp2) and
  12413. (hp2.typ = ait_instruction) and
  12414. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12415. then
  12416. { change
  12417. and 2^n, reg
  12418. cmp 2^n, reg
  12419. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12420. to
  12421. and 2^n, reg
  12422. test reg, reg
  12423. j(~c) / set(~c) / cmov(~c)
  12424. }
  12425. begin
  12426. { Keep TEST instruction in, rather than remove it, because
  12427. it may trigger other optimisations such as MovAndTest2Test }
  12428. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12429. taicpu(hp1).opcode := A_TEST;
  12430. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12431. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12432. Result := True;
  12433. Exit;
  12434. end
  12435. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  12436. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12437. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  12438. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  12439. { change
  12440. and $ff/$ff/$ffff, reg
  12441. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  12442. dealloc reg
  12443. to
  12444. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  12445. }
  12446. begin
  12447. TransferUsedRegs(TmpUsedRegs);
  12448. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12449. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  12450. begin
  12451. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  12452. case taicpu(p).oper[0]^.val of
  12453. $ff:
  12454. begin
  12455. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  12456. taicpu(hp1).opsize:=S_B;
  12457. end;
  12458. $ffff:
  12459. begin
  12460. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  12461. taicpu(hp1).opsize:=S_W;
  12462. end;
  12463. $ffffffff:
  12464. begin
  12465. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12466. taicpu(hp1).opsize:=S_L;
  12467. end;
  12468. else
  12469. Internalerror(2023030401);
  12470. end;
  12471. RemoveCurrentP(p);
  12472. Result := True;
  12473. Exit;
  12474. end;
  12475. end;
  12476. A_MOVZX:
  12477. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12478. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12479. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12480. (
  12481. (
  12482. (taicpu(p).opsize=S_W) and
  12483. (taicpu(hp1).opsize=S_BW)
  12484. ) or
  12485. (
  12486. (taicpu(p).opsize=S_L) and
  12487. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12488. )
  12489. {$ifdef x86_64}
  12490. or
  12491. (
  12492. (taicpu(p).opsize=S_Q) and
  12493. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12494. )
  12495. {$endif x86_64}
  12496. ) then
  12497. begin
  12498. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12499. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12500. ) or
  12501. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12502. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12503. then
  12504. begin
  12505. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12506. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12507. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12508. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12509. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12510. }
  12511. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12512. RemoveInstruction(hp1);
  12513. { See if there are other optimisations possible }
  12514. Continue;
  12515. end;
  12516. end;
  12517. A_SHL:
  12518. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12519. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12520. begin
  12521. {$ifopt R+}
  12522. {$define RANGE_WAS_ON}
  12523. {$R-}
  12524. {$endif}
  12525. { get length of potential and mask }
  12526. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12527. { really a mask? }
  12528. {$ifdef RANGE_WAS_ON}
  12529. {$R+}
  12530. {$endif}
  12531. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12532. { unmasked part shifted out? }
  12533. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12534. begin
  12535. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12536. RemoveCurrentP(p, hp1);
  12537. Result:=true;
  12538. exit;
  12539. end;
  12540. end;
  12541. A_SHR:
  12542. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12543. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12544. (taicpu(hp1).oper[0]^.val <= 63) then
  12545. begin
  12546. { Does SHR combined with the AND cover all the bits?
  12547. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12548. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12549. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12550. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12551. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12552. begin
  12553. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12554. RemoveCurrentP(p, hp1);
  12555. Result := True;
  12556. Exit;
  12557. end;
  12558. end;
  12559. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12560. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12561. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12562. begin
  12563. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12564. (
  12565. (
  12566. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12567. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12568. ) or (
  12569. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12570. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12571. {$ifdef x86_64}
  12572. ) or (
  12573. (taicpu(hp1).opsize = S_LQ) and
  12574. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12575. {$endif x86_64}
  12576. )
  12577. ) then
  12578. begin
  12579. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12580. begin
  12581. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12582. RemoveInstruction(hp1);
  12583. { See if there are other optimisations possible }
  12584. Continue;
  12585. end;
  12586. { The super-registers are the same though.
  12587. Note that this change by itself doesn't improve
  12588. code speed, but it opens up other optimisations. }
  12589. {$ifdef x86_64}
  12590. { Convert 64-bit register to 32-bit }
  12591. case taicpu(hp1).opsize of
  12592. S_BQ:
  12593. begin
  12594. taicpu(hp1).opsize := S_BL;
  12595. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12596. end;
  12597. S_WQ:
  12598. begin
  12599. taicpu(hp1).opsize := S_WL;
  12600. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12601. end
  12602. else
  12603. ;
  12604. end;
  12605. {$endif x86_64}
  12606. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12607. taicpu(hp1).opcode := A_MOVZX;
  12608. { See if there are other optimisations possible }
  12609. Continue;
  12610. end;
  12611. end;
  12612. else
  12613. ;
  12614. end;
  12615. end
  12616. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12617. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12618. begin
  12619. {$ifdef x86_64}
  12620. if (taicpu(p).opsize = S_Q) then
  12621. begin
  12622. { Never necessary }
  12623. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12624. RemoveCurrentP(p, hp1);
  12625. Result := True;
  12626. Exit;
  12627. end;
  12628. {$endif x86_64}
  12629. { Forward check to determine necessity of and %reg,%reg }
  12630. TransferUsedRegs(TmpUsedRegs);
  12631. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12632. { Saves on a bunch of dereferences }
  12633. ActiveReg := taicpu(p).oper[1]^.reg;
  12634. case taicpu(hp1).opcode of
  12635. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12636. if (
  12637. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12638. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12639. ) and
  12640. (
  12641. (taicpu(hp1).opcode <> A_MOV) or
  12642. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12643. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12644. ) and
  12645. not (
  12646. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12647. (taicpu(hp1).opcode = A_MOV) and
  12648. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12649. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12650. ) and
  12651. (
  12652. (
  12653. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12654. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12655. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12656. ) or
  12657. (
  12658. {$ifdef x86_64}
  12659. (
  12660. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12661. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12662. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12663. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12664. ) and
  12665. {$endif x86_64}
  12666. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12667. )
  12668. ) then
  12669. begin
  12670. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12671. RemoveCurrentP(p, hp1);
  12672. Result := True;
  12673. Exit;
  12674. end;
  12675. A_ADD,
  12676. A_AND,
  12677. A_BSF,
  12678. A_BSR,
  12679. A_BTC,
  12680. A_BTR,
  12681. A_BTS,
  12682. A_OR,
  12683. A_SUB,
  12684. A_XOR:
  12685. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12686. if (
  12687. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12688. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12689. ) and
  12690. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12691. begin
  12692. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12693. RemoveCurrentP(p, hp1);
  12694. Result := True;
  12695. Exit;
  12696. end;
  12697. A_CMP,
  12698. A_TEST:
  12699. if (
  12700. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12701. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12702. ) and
  12703. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12704. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12705. begin
  12706. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12707. RemoveCurrentP(p, hp1);
  12708. Result := True;
  12709. Exit;
  12710. end;
  12711. A_BSWAP,
  12712. A_NEG,
  12713. A_NOT:
  12714. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12715. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12716. begin
  12717. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12718. RemoveCurrentP(p, hp1);
  12719. Result := True;
  12720. Exit;
  12721. end;
  12722. else
  12723. ;
  12724. end;
  12725. end;
  12726. if (taicpu(hp1).is_jmp) and
  12727. (taicpu(hp1).opcode<>A_JMP) and
  12728. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12729. begin
  12730. { change
  12731. and x, reg
  12732. jxx
  12733. to
  12734. test x, reg
  12735. jxx
  12736. if reg is deallocated before the
  12737. jump, but only if it's a conditional jump (PFV)
  12738. }
  12739. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12740. taicpu(p).opcode := A_TEST;
  12741. Exit;
  12742. end;
  12743. Break;
  12744. end;
  12745. { Lone AND tests }
  12746. if (taicpu(p).oper[0]^.typ = top_const) then
  12747. begin
  12748. {
  12749. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12750. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12751. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12752. }
  12753. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12754. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12755. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12756. begin
  12757. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12758. if taicpu(p).opsize = S_L then
  12759. begin
  12760. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12761. Result := True;
  12762. end;
  12763. end;
  12764. end;
  12765. { Backward check to determine necessity of and %reg,%reg }
  12766. if (taicpu(p).oper[0]^.typ = top_reg) and
  12767. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12768. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12769. GetLastInstruction(p, hp2) and
  12770. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12771. { Check size of adjacent instruction to determine if the AND is
  12772. effectively a null operation }
  12773. (
  12774. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12775. { Note: Don't include S_Q }
  12776. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12777. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12778. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  12779. ) then
  12780. begin
  12781. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  12782. { If GetNextInstruction returned False, hp1 will be nil }
  12783. RemoveCurrentP(p, hp1);
  12784. Result := True;
  12785. Exit;
  12786. end;
  12787. end;
  12788. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  12789. var
  12790. hp1, hp2: tai;
  12791. NewRef: TReference;
  12792. Distance: Cardinal;
  12793. TempTracking: TAllUsedRegs;
  12794. { This entire nested function is used in an if-statement below, but we
  12795. want to avoid all the used reg transfers and GetNextInstruction calls
  12796. until we really have to check }
  12797. function MemRegisterNotUsedLater: Boolean; inline;
  12798. var
  12799. hp2: tai;
  12800. begin
  12801. TransferUsedRegs(TmpUsedRegs);
  12802. hp2 := p;
  12803. repeat
  12804. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12805. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12806. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  12807. end;
  12808. begin
  12809. Result := False;
  12810. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12811. (taicpu(p).oper[1]^.typ = top_reg) then
  12812. begin
  12813. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12814. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12815. (hp1.typ <> ait_instruction) or
  12816. not
  12817. (
  12818. (cs_opt_level3 in current_settings.optimizerswitches) or
  12819. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12820. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12821. ) then
  12822. Exit;
  12823. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12824. addq $x, %rax
  12825. movq %rax, %rdx
  12826. sarq $63, %rdx
  12827. (%rax still in use)
  12828. ...letting OptPass2ADD run its course (and without -Os) will produce:
  12829. leaq $x(%rax),%rdx
  12830. addq $x, %rax
  12831. sarq $63, %rdx
  12832. ...which is okay since it breaks the dependency chain between
  12833. addq and movq, but if OptPass2MOV is called first:
  12834. addq $x, %rax
  12835. cqto
  12836. ...which is better in all ways, taking only 2 cycles to execute
  12837. and much smaller in code size.
  12838. }
  12839. { The extra register tracking is quite strenuous }
  12840. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12841. MatchInstruction(hp1, A_MOV, []) then
  12842. begin
  12843. { Update the register tracking to the MOV instruction }
  12844. CopyUsedRegs(TempTracking);
  12845. hp2 := p;
  12846. repeat
  12847. UpdateUsedRegs(tai(hp2.Next));
  12848. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12849. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12850. OptPass2ADD get called again }
  12851. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12852. begin
  12853. { Reset the tracking to the current instruction }
  12854. RestoreUsedRegs(TempTracking);
  12855. ReleaseUsedRegs(TempTracking);
  12856. Result := True;
  12857. Exit;
  12858. end;
  12859. { Reset the tracking to the current instruction }
  12860. RestoreUsedRegs(TempTracking);
  12861. ReleaseUsedRegs(TempTracking);
  12862. { If OptPass2MOV returned True, we don't need to set Result to
  12863. True if hp1 didn't change because the ADD instruction didn't
  12864. get modified and we'll be evaluating hp1 again when the
  12865. peephole optimizer reaches it }
  12866. end;
  12867. { Change:
  12868. add %reg2,%reg1
  12869. (%reg2 not modified in between)
  12870. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  12871. To:
  12872. mov/s/z #(%reg1,%reg2),%reg1
  12873. }
  12874. if (taicpu(p).oper[0]^.typ = top_reg) and
  12875. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  12876. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  12877. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  12878. (
  12879. (
  12880. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  12881. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  12882. { r/esp cannot be an index }
  12883. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  12884. ) or (
  12885. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  12886. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  12887. )
  12888. ) and (
  12889. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  12890. (
  12891. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  12892. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12893. MemRegisterNotUsedLater
  12894. )
  12895. ) then
  12896. begin
  12897. if (
  12898. { Instructions are guaranteed to be adjacent on -O2 and under }
  12899. (cs_opt_level3 in current_settings.optimizerswitches) and
  12900. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  12901. ) then
  12902. begin
  12903. { If the other register is used in between, move the MOV
  12904. instruction to right after the ADD instruction so a
  12905. saving can still be made }
  12906. Asml.Remove(hp1);
  12907. Asml.InsertAfter(hp1, p);
  12908. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12909. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12910. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  12911. RemoveCurrentp(p, hp1);
  12912. end
  12913. else
  12914. begin
  12915. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  12916. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12917. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12918. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  12919. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12920. { hp1 may not be the immediate next instruction under -O3 }
  12921. RemoveCurrentp(p)
  12922. else
  12923. RemoveCurrentp(p, hp1);
  12924. end;
  12925. Result := True;
  12926. Exit;
  12927. end;
  12928. { Change:
  12929. addl/q $x,%reg1
  12930. movl/q %reg1,%reg2
  12931. To:
  12932. leal/q $x(%reg1),%reg2
  12933. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12934. Breaks the dependency chain.
  12935. }
  12936. if (taicpu(p).oper[0]^.typ = top_const) and
  12937. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12938. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12939. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12940. (
  12941. { Instructions are guaranteed to be adjacent on -O2 and under }
  12942. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12943. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12944. ) then
  12945. begin
  12946. TransferUsedRegs(TmpUsedRegs);
  12947. hp2 := p;
  12948. repeat
  12949. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12950. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12951. if (
  12952. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  12953. not (cs_opt_size in current_settings.optimizerswitches) or
  12954. (
  12955. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12956. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12957. )
  12958. ) then
  12959. begin
  12960. { Change the MOV instruction to a LEA instruction, and update the
  12961. first operand }
  12962. reference_reset(NewRef, 1, []);
  12963. NewRef.base := taicpu(p).oper[1]^.reg;
  12964. NewRef.scalefactor := 1;
  12965. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  12966. taicpu(hp1).opcode := A_LEA;
  12967. taicpu(hp1).loadref(0, NewRef);
  12968. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12969. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12970. begin
  12971. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12972. { Move what is now the LEA instruction to before the ADD instruction }
  12973. Asml.Remove(hp1);
  12974. Asml.InsertBefore(hp1, p);
  12975. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12976. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  12977. p := hp1;
  12978. end
  12979. else
  12980. begin
  12981. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12982. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  12983. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12984. { hp1 may not be the immediate next instruction under -O3 }
  12985. RemoveCurrentp(p)
  12986. else
  12987. RemoveCurrentp(p, hp1);
  12988. end;
  12989. Result := True;
  12990. end;
  12991. end;
  12992. end;
  12993. end;
  12994. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  12995. var
  12996. SubReg: TSubRegister;
  12997. begin
  12998. Result:=false;
  12999. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  13000. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13001. with taicpu(p).oper[0]^.ref^ do
  13002. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  13003. begin
  13004. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  13005. begin
  13006. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  13007. taicpu(p).opcode := A_ADD;
  13008. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  13009. Result := True;
  13010. end
  13011. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  13012. begin
  13013. if (base <> NR_NO) then
  13014. begin
  13015. if (scalefactor <= 1) then
  13016. begin
  13017. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  13018. taicpu(p).opcode := A_ADD;
  13019. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  13020. Result := True;
  13021. end;
  13022. end
  13023. else
  13024. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  13025. if (scalefactor in [2, 4, 8]) then
  13026. begin
  13027. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  13028. taicpu(p).loadconst(0, BsrByte(scalefactor));
  13029. taicpu(p).opcode := A_SHL;
  13030. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  13031. Result := True;
  13032. end;
  13033. end;
  13034. end;
  13035. end;
  13036. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  13037. var
  13038. hp1, hp2: tai;
  13039. NewRef: TReference;
  13040. Distance: Cardinal;
  13041. TempTracking: TAllUsedRegs;
  13042. begin
  13043. Result := False;
  13044. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13045. MatchOpType(taicpu(p),top_const,top_reg) then
  13046. begin
  13047. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13048. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13049. (hp1.typ <> ait_instruction) or
  13050. not
  13051. (
  13052. (cs_opt_level3 in current_settings.optimizerswitches) or
  13053. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13054. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13055. ) then
  13056. Exit;
  13057. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13058. subq $x, %rax
  13059. movq %rax, %rdx
  13060. sarq $63, %rdx
  13061. (%rax still in use)
  13062. ...letting OptPass2SUB run its course (and without -Os) will produce:
  13063. leaq $-x(%rax),%rdx
  13064. movq $x, %rax
  13065. sarq $63, %rdx
  13066. ...which is okay since it breaks the dependency chain between
  13067. subq and movq, but if OptPass2MOV is called first:
  13068. subq $x, %rax
  13069. cqto
  13070. ...which is better in all ways, taking only 2 cycles to execute
  13071. and much smaller in code size.
  13072. }
  13073. { The extra register tracking is quite strenuous }
  13074. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13075. MatchInstruction(hp1, A_MOV, []) then
  13076. begin
  13077. { Update the register tracking to the MOV instruction }
  13078. CopyUsedRegs(TempTracking);
  13079. hp2 := p;
  13080. repeat
  13081. UpdateUsedRegs(tai(hp2.Next));
  13082. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13083. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13084. OptPass2SUB get called again }
  13085. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13086. begin
  13087. { Reset the tracking to the current instruction }
  13088. RestoreUsedRegs(TempTracking);
  13089. ReleaseUsedRegs(TempTracking);
  13090. Result := True;
  13091. Exit;
  13092. end;
  13093. { Reset the tracking to the current instruction }
  13094. RestoreUsedRegs(TempTracking);
  13095. ReleaseUsedRegs(TempTracking);
  13096. { If OptPass2MOV returned True, we don't need to set Result to
  13097. True if hp1 didn't change because the SUB instruction didn't
  13098. get modified and we'll be evaluating hp1 again when the
  13099. peephole optimizer reaches it }
  13100. end;
  13101. { Change:
  13102. subl/q $x,%reg1
  13103. movl/q %reg1,%reg2
  13104. To:
  13105. leal/q $-x(%reg1),%reg2
  13106. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13107. Breaks the dependency chain and potentially permits the removal of
  13108. a CMP instruction if one follows.
  13109. }
  13110. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13111. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13112. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13113. (
  13114. { Instructions are guaranteed to be adjacent on -O2 and under }
  13115. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13116. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13117. ) then
  13118. begin
  13119. TransferUsedRegs(TmpUsedRegs);
  13120. hp2 := p;
  13121. repeat
  13122. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13123. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13124. if (
  13125. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13126. not (cs_opt_size in current_settings.optimizerswitches) or
  13127. (
  13128. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13129. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13130. )
  13131. ) then
  13132. begin
  13133. { Change the MOV instruction to a LEA instruction, and update the
  13134. first operand }
  13135. reference_reset(NewRef, 1, []);
  13136. NewRef.base := taicpu(p).oper[1]^.reg;
  13137. NewRef.scalefactor := 1;
  13138. NewRef.offset := -taicpu(p).oper[0]^.val;
  13139. taicpu(hp1).opcode := A_LEA;
  13140. taicpu(hp1).loadref(0, NewRef);
  13141. TransferUsedRegs(TmpUsedRegs);
  13142. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13143. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13144. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13145. begin
  13146. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13147. { Move what is now the LEA instruction to before the SUB instruction }
  13148. Asml.Remove(hp1);
  13149. Asml.InsertBefore(hp1, p);
  13150. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13151. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13152. p := hp1;
  13153. end
  13154. else
  13155. begin
  13156. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13157. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13158. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13159. { hp1 may not be the immediate next instruction under -O3 }
  13160. RemoveCurrentp(p)
  13161. else
  13162. RemoveCurrentp(p, hp1);
  13163. end;
  13164. Result := True;
  13165. end;
  13166. end;
  13167. end;
  13168. end;
  13169. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13170. begin
  13171. { we can skip all instructions not messing with the stack pointer }
  13172. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13173. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13174. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13175. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13176. ({(taicpu(hp1).ops=0) or }
  13177. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13178. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13179. ) and }
  13180. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13181. )
  13182. ) do
  13183. GetNextInstruction(hp1,hp1);
  13184. Result:=assigned(hp1);
  13185. end;
  13186. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13187. var
  13188. hp1, hp2, hp3, hp4, hp5: tai;
  13189. begin
  13190. Result:=false;
  13191. hp5:=nil;
  13192. { replace
  13193. leal(q) x(<stackpointer>),<stackpointer>
  13194. call procname
  13195. leal(q) -x(<stackpointer>),<stackpointer>
  13196. ret
  13197. by
  13198. jmp procname
  13199. but do it only on level 4 because it destroys stack back traces
  13200. }
  13201. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13202. MatchOpType(taicpu(p),top_ref,top_reg) and
  13203. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13204. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13205. { the -8 or -24 are not required, but bail out early if possible,
  13206. higher values are unlikely }
  13207. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13208. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13209. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13210. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13211. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13212. GetNextInstruction(p, hp1) and
  13213. { Take a copy of hp1 }
  13214. SetAndTest(hp1, hp4) and
  13215. { trick to skip label }
  13216. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13217. SkipSimpleInstructions(hp1) and
  13218. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13219. GetNextInstruction(hp1, hp2) and
  13220. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13221. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13222. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13223. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13224. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13225. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13226. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13227. { Segment register will be NR_NO }
  13228. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13229. GetNextInstruction(hp2, hp3) and
  13230. { trick to skip label }
  13231. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13232. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13233. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13234. SetAndTest(hp3,hp5) and
  13235. GetNextInstruction(hp3,hp3) and
  13236. MatchInstruction(hp3,A_RET,[S_NO])
  13237. )
  13238. ) and
  13239. (taicpu(hp3).ops=0) then
  13240. begin
  13241. taicpu(hp1).opcode := A_JMP;
  13242. taicpu(hp1).is_jmp := true;
  13243. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13244. RemoveCurrentP(p, hp4);
  13245. RemoveInstruction(hp2);
  13246. RemoveInstruction(hp3);
  13247. if Assigned(hp5) then
  13248. begin
  13249. AsmL.Remove(hp5);
  13250. ASmL.InsertBefore(hp5,hp1)
  13251. end;
  13252. Result:=true;
  13253. end;
  13254. end;
  13255. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13256. {$ifdef x86_64}
  13257. var
  13258. hp1, hp2, hp3, hp4, hp5: tai;
  13259. {$endif x86_64}
  13260. begin
  13261. Result:=false;
  13262. {$ifdef x86_64}
  13263. hp5:=nil;
  13264. { replace
  13265. push %rax
  13266. call procname
  13267. pop %rcx
  13268. ret
  13269. by
  13270. jmp procname
  13271. but do it only on level 4 because it destroys stack back traces
  13272. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13273. for all supported calling conventions
  13274. }
  13275. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13276. MatchOpType(taicpu(p),top_reg) and
  13277. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13278. GetNextInstruction(p, hp1) and
  13279. { Take a copy of hp1 }
  13280. SetAndTest(hp1, hp4) and
  13281. { trick to skip label }
  13282. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13283. SkipSimpleInstructions(hp1) and
  13284. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13285. GetNextInstruction(hp1, hp2) and
  13286. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13287. MatchOpType(taicpu(hp2),top_reg) and
  13288. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13289. GetNextInstruction(hp2, hp3) and
  13290. { trick to skip label }
  13291. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13292. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13293. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13294. SetAndTest(hp3,hp5) and
  13295. GetNextInstruction(hp3,hp3) and
  13296. MatchInstruction(hp3,A_RET,[S_NO])
  13297. )
  13298. ) and
  13299. (taicpu(hp3).ops=0) then
  13300. begin
  13301. taicpu(hp1).opcode := A_JMP;
  13302. taicpu(hp1).is_jmp := true;
  13303. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13304. RemoveCurrentP(p, hp4);
  13305. RemoveInstruction(hp2);
  13306. RemoveInstruction(hp3);
  13307. if Assigned(hp5) then
  13308. begin
  13309. AsmL.Remove(hp5);
  13310. ASmL.InsertBefore(hp5,hp1)
  13311. end;
  13312. Result:=true;
  13313. end;
  13314. {$endif x86_64}
  13315. end;
  13316. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13317. var
  13318. Value, RegName: string;
  13319. begin
  13320. Result:=false;
  13321. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13322. begin
  13323. case taicpu(p).oper[0]^.val of
  13324. 0:
  13325. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13326. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13327. begin
  13328. { change "mov $0,%reg" into "xor %reg,%reg" }
  13329. taicpu(p).opcode := A_XOR;
  13330. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13331. Result := True;
  13332. {$ifdef x86_64}
  13333. end
  13334. else if (taicpu(p).opsize = S_Q) then
  13335. begin
  13336. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13337. { The actual optimization }
  13338. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13339. taicpu(p).changeopsize(S_L);
  13340. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13341. Result := True;
  13342. end;
  13343. $1..$FFFFFFFF:
  13344. begin
  13345. { Code size reduction by J. Gareth "Kit" Moreton }
  13346. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13347. case taicpu(p).opsize of
  13348. S_Q:
  13349. begin
  13350. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13351. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13352. { The actual optimization }
  13353. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13354. taicpu(p).changeopsize(S_L);
  13355. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13356. Result := True;
  13357. end;
  13358. else
  13359. { Do nothing };
  13360. end;
  13361. {$endif x86_64}
  13362. end;
  13363. -1:
  13364. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13365. if (cs_opt_size in current_settings.optimizerswitches) and
  13366. (taicpu(p).opsize <> S_B) and
  13367. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13368. begin
  13369. { change "mov $-1,%reg" into "or $-1,%reg" }
  13370. { NOTES:
  13371. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13372. - This operation creates a false dependency on the register, so only do it when optimising for size
  13373. - 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
  13374. }
  13375. taicpu(p).opcode := A_OR;
  13376. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13377. Result := True;
  13378. end;
  13379. else
  13380. { Do nothing };
  13381. end;
  13382. end;
  13383. end;
  13384. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13385. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13386. begin
  13387. Result := False;
  13388. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13389. Exit;
  13390. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13391. so don't bother optimising }
  13392. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13393. Exit;
  13394. if (taicpu(p).oper[0]^.typ <> top_const) or
  13395. { If the value can fit into an 8-bit signed integer, a smaller
  13396. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13397. falls within this range }
  13398. (
  13399. (taicpu(p).oper[0]^.val > -128) and
  13400. (taicpu(p).oper[0]^.val <= 127)
  13401. ) then
  13402. Exit;
  13403. { If we're optimising for size, this is acceptable }
  13404. if (cs_opt_size in current_settings.optimizerswitches) then
  13405. Exit(True);
  13406. if (taicpu(p).oper[1]^.typ = top_reg) and
  13407. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13408. Exit(True);
  13409. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13410. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13411. Exit(True);
  13412. end;
  13413. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13414. var
  13415. hp1: tai;
  13416. Value: TCGInt;
  13417. begin
  13418. Result := False;
  13419. if MatchOpType(taicpu(p), top_const, top_reg) then
  13420. begin
  13421. { Detect:
  13422. andw x, %ax (0 <= x < $8000)
  13423. ...
  13424. movzwl %ax,%eax
  13425. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13426. }
  13427. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13428. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13429. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13430. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13431. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13432. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13433. begin
  13434. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13435. taicpu(hp1).opcode := A_CWDE;
  13436. taicpu(hp1).clearop(0);
  13437. taicpu(hp1).clearop(1);
  13438. taicpu(hp1).ops := 0;
  13439. { A change was made, but not with p, so don't set Result, but
  13440. notify the compiler that a change was made }
  13441. Include(OptsToCheck, aoc_ForceNewIteration);
  13442. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13443. end;
  13444. end;
  13445. { If "not x" is a power of 2 (popcnt = 1), change:
  13446. and $x, %reg/ref
  13447. To:
  13448. btr lb(x), %reg/ref
  13449. }
  13450. if IsBTXAcceptable(p) and
  13451. (
  13452. { Make sure a TEST doesn't follow that plays with the register }
  13453. not GetNextInstruction(p, hp1) or
  13454. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13455. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13456. ) then
  13457. begin
  13458. {$push}{$R-}{$Q-}
  13459. { Value is a sign-extended 32-bit integer - just correct it
  13460. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13461. checks to see if this operand is an immediate. }
  13462. Value := not taicpu(p).oper[0]^.val;
  13463. {$pop}
  13464. {$ifdef x86_64}
  13465. if taicpu(p).opsize = S_L then
  13466. {$endif x86_64}
  13467. Value := Value and $FFFFFFFF;
  13468. if (PopCnt(QWord(Value)) = 1) then
  13469. begin
  13470. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13471. taicpu(p).opcode := A_BTR;
  13472. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13473. Result := True;
  13474. Exit;
  13475. end;
  13476. end;
  13477. end;
  13478. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13479. begin
  13480. Result := False;
  13481. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13482. Exit;
  13483. { Convert:
  13484. movswl %ax,%eax -> cwtl
  13485. movslq %eax,%rax -> cdqe
  13486. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13487. refer to the same opcode and depends only on the assembler's
  13488. current operand-size attribute. [Kit]
  13489. }
  13490. with taicpu(p) do
  13491. case opsize of
  13492. S_WL:
  13493. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13494. begin
  13495. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13496. opcode := A_CWDE;
  13497. clearop(0);
  13498. clearop(1);
  13499. ops := 0;
  13500. Result := True;
  13501. end;
  13502. {$ifdef x86_64}
  13503. S_LQ:
  13504. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13505. begin
  13506. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13507. opcode := A_CDQE;
  13508. clearop(0);
  13509. clearop(1);
  13510. ops := 0;
  13511. Result := True;
  13512. end;
  13513. {$endif x86_64}
  13514. else
  13515. ;
  13516. end;
  13517. end;
  13518. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13519. var
  13520. hp1, hp2: tai;
  13521. IdentityMask, Shift: TCGInt;
  13522. LimitSize: Topsize;
  13523. DoNotMerge: Boolean;
  13524. begin
  13525. Result := False;
  13526. { All these optimisations work on "shr const,%reg" }
  13527. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13528. Exit;
  13529. DoNotMerge := False;
  13530. Shift := taicpu(p).oper[0]^.val;
  13531. LimitSize := taicpu(p).opsize;
  13532. hp1 := p;
  13533. repeat
  13534. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13535. Break;
  13536. { Detect:
  13537. shr x, %reg
  13538. and y, %reg
  13539. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13540. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13541. }
  13542. case taicpu(hp1).opcode of
  13543. A_AND:
  13544. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13545. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13546. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13547. begin
  13548. { Make sure the FLAGS register isn't in use }
  13549. TransferUsedRegs(TmpUsedRegs);
  13550. hp2 := p;
  13551. repeat
  13552. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13553. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13554. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13555. begin
  13556. { Generate the identity mask }
  13557. case taicpu(p).opsize of
  13558. S_B:
  13559. IdentityMask := $FF shr Shift;
  13560. S_W:
  13561. IdentityMask := $FFFF shr Shift;
  13562. S_L:
  13563. IdentityMask := $FFFFFFFF shr Shift;
  13564. {$ifdef x86_64}
  13565. S_Q:
  13566. { We need to force the operands to be unsigned 64-bit
  13567. integers otherwise the wrong value is generated }
  13568. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13569. {$endif x86_64}
  13570. else
  13571. InternalError(2022081501);
  13572. end;
  13573. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13574. begin
  13575. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13576. { All the possible 1 bits are covered, so we can remove the AND }
  13577. hp2 := tai(hp1.Previous);
  13578. RemoveInstruction(hp1);
  13579. { p wasn't actually changed, so don't set Result to True,
  13580. but a change was nonetheless made elsewhere }
  13581. Include(OptsToCheck, aoc_ForceNewIteration);
  13582. { Do another pass in case other AND or MOVZX instructions
  13583. follow }
  13584. hp1 := hp2;
  13585. Continue;
  13586. end;
  13587. end;
  13588. end;
  13589. A_TEST, A_CMP, A_Jcc:
  13590. { Skip over conditional jumps and relevant comparisons }
  13591. Continue;
  13592. A_MOVZX:
  13593. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13594. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13595. begin
  13596. { Since the original register is being read as is, subsequent
  13597. SHRs must not be merged at this point }
  13598. DoNotMerge := True;
  13599. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13600. begin
  13601. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13602. begin
  13603. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13604. { All the possible 1 bits are covered, so we can remove the AND }
  13605. hp2 := tai(hp1.Previous);
  13606. RemoveInstruction(hp1);
  13607. hp1 := hp2;
  13608. end
  13609. else { Different register target }
  13610. begin
  13611. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13612. taicpu(hp1).opcode := A_MOV;
  13613. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13614. case taicpu(hp1).opsize of
  13615. S_BW:
  13616. taicpu(hp1).opsize := S_W;
  13617. S_BL, S_WL:
  13618. taicpu(hp1).opsize := S_L;
  13619. else
  13620. InternalError(2022081503);
  13621. end;
  13622. end;
  13623. end
  13624. else if (Shift > 0) and
  13625. (taicpu(p).opsize = S_W) and
  13626. (taicpu(hp1).opsize = S_WL) and
  13627. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13628. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13629. begin
  13630. { Detect:
  13631. shr x, %ax (x > 0)
  13632. ...
  13633. movzwl %ax,%eax
  13634. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13635. }
  13636. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13637. taicpu(hp1).opcode := A_CWDE;
  13638. taicpu(hp1).clearop(0);
  13639. taicpu(hp1).clearop(1);
  13640. taicpu(hp1).ops := 0;
  13641. end;
  13642. { Move onto the next instruction }
  13643. Continue;
  13644. end;
  13645. A_SHL, A_SAL, A_SHR:
  13646. if (taicpu(hp1).opsize <= LimitSize) and
  13647. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13648. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13649. begin
  13650. { Make sure the sizes don't exceed the register size limit
  13651. (measured by the shift value falling below the limit) }
  13652. if taicpu(hp1).opsize < LimitSize then
  13653. LimitSize := taicpu(hp1).opsize;
  13654. if taicpu(hp1).opcode = A_SHR then
  13655. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13656. else
  13657. begin
  13658. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13659. DoNotMerge := True;
  13660. end;
  13661. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13662. Break;
  13663. { Since we've established that the combined shift is within
  13664. limits, we can actually combine the adjacent SHR
  13665. instructions even if they're different sizes }
  13666. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13667. begin
  13668. hp2 := tai(hp1.Previous);
  13669. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13670. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13671. RemoveInstruction(hp1);
  13672. hp1 := hp2;
  13673. end;
  13674. { Move onto the next instruction }
  13675. Continue;
  13676. end;
  13677. else
  13678. ;
  13679. end;
  13680. Break;
  13681. until False;
  13682. { Detect the following (looking backwards):
  13683. shr %cl,%reg
  13684. shr x, %reg
  13685. Swap the two SHR instructions to minimise a pipeline stall.
  13686. }
  13687. if GetLastInstruction(p, hp1) and
  13688. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13689. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13690. { First operand will be %cl }
  13691. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13692. { Just to be sure }
  13693. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13694. begin
  13695. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13696. { Moving the entries this way ensures the register tracking remains correct }
  13697. Asml.Remove(p);
  13698. Asml.InsertBefore(p, hp1);
  13699. p := hp1;
  13700. { Don't set Result to True because the current instruction is now
  13701. "shr %cl,%reg" and there's nothing more we can do with it }
  13702. end;
  13703. end;
  13704. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13705. var
  13706. hp1, hp2: tai;
  13707. Opposite, SecondOpposite: TAsmOp;
  13708. NewCond: TAsmCond;
  13709. begin
  13710. Result := False;
  13711. { Change:
  13712. add/sub 128,(dest)
  13713. To:
  13714. sub/add -128,(dest)
  13715. This generaally takes fewer bytes to encode because -128 can be stored
  13716. in a signed byte, whereas +128 cannot.
  13717. }
  13718. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13719. begin
  13720. if taicpu(p).opcode = A_ADD then
  13721. Opposite := A_SUB
  13722. else
  13723. Opposite := A_ADD;
  13724. { Be careful if the flags are in use, because the CF flag inverts
  13725. when changing from ADD to SUB and vice versa }
  13726. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13727. GetNextInstruction(p, hp1) then
  13728. begin
  13729. TransferUsedRegs(TmpUsedRegs);
  13730. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13731. hp2 := hp1;
  13732. { Scan ahead to check if everything's safe }
  13733. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13734. begin
  13735. if (hp1.typ <> ait_instruction) then
  13736. { Probably unsafe since the flags are still in use }
  13737. Exit;
  13738. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13739. { Stop searching at an unconditional jump }
  13740. Break;
  13741. if not
  13742. (
  13743. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13744. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13745. ) and
  13746. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13747. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13748. Exit;
  13749. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13750. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13751. { Move to the next instruction }
  13752. GetNextInstruction(hp1, hp1);
  13753. end;
  13754. while Assigned(hp2) and (hp2 <> hp1) do
  13755. begin
  13756. NewCond := C_None;
  13757. case taicpu(hp2).condition of
  13758. C_A, C_NBE:
  13759. NewCond := C_BE;
  13760. C_B, C_C, C_NAE:
  13761. NewCond := C_AE;
  13762. C_AE, C_NB, C_NC:
  13763. NewCond := C_B;
  13764. C_BE, C_NA:
  13765. NewCond := C_A;
  13766. else
  13767. { No change needed };
  13768. end;
  13769. if NewCond <> C_None then
  13770. begin
  13771. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13772. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13773. taicpu(hp2).condition := NewCond;
  13774. end
  13775. else
  13776. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13777. begin
  13778. { Because of the flipping of the carry bit, to ensure
  13779. the operation remains equivalent, ADC becomes SBB
  13780. and vice versa, and the constant is not-inverted.
  13781. If multiple ADCs or SBBs appear in a row, each one
  13782. changed causes the carry bit to invert, so they all
  13783. need to be flipped }
  13784. if taicpu(hp2).opcode = A_ADC then
  13785. SecondOpposite := A_SBB
  13786. else
  13787. SecondOpposite := A_ADC;
  13788. if taicpu(hp2).oper[0]^.typ <> top_const then
  13789. { Should have broken out of this optimisation already }
  13790. InternalError(2021112901);
  13791. 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]^) + ' -> ' +
  13792. 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);
  13793. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  13794. taicpu(hp2).opcode := SecondOpposite;
  13795. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  13796. end;
  13797. { Move to the next instruction }
  13798. GetNextInstruction(hp2, hp2);
  13799. end;
  13800. if (hp2 <> hp1) then
  13801. InternalError(2021111501);
  13802. end;
  13803. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  13804. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  13805. taicpu(p).opcode := Opposite;
  13806. taicpu(p).oper[0]^.val := -128;
  13807. { No further optimisations can be made on this instruction, so move
  13808. onto the next one to save time }
  13809. p := tai(p.Next);
  13810. UpdateUsedRegs(p);
  13811. Result := True;
  13812. Exit;
  13813. end;
  13814. { Detect:
  13815. add/sub %reg2,(dest)
  13816. add/sub x, (dest)
  13817. (dest can be a register or a reference)
  13818. Swap the instructions to minimise a pipeline stall. This reverses the
  13819. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  13820. optimisations could be made.
  13821. }
  13822. if (taicpu(p).oper[0]^.typ = top_reg) and
  13823. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  13824. (
  13825. (
  13826. (taicpu(p).oper[1]^.typ = top_reg) and
  13827. { We can try searching further ahead if we're writing to a register }
  13828. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  13829. ) or
  13830. (
  13831. (taicpu(p).oper[1]^.typ = top_ref) and
  13832. GetNextInstruction(p, hp1)
  13833. )
  13834. ) and
  13835. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  13836. (taicpu(hp1).oper[0]^.typ = top_const) and
  13837. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  13838. begin
  13839. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  13840. TransferUsedRegs(TmpUsedRegs);
  13841. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13842. hp2 := p;
  13843. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  13844. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  13845. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  13846. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13847. begin
  13848. asml.remove(hp1);
  13849. asml.InsertBefore(hp1, p);
  13850. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  13851. Result := True;
  13852. end;
  13853. end;
  13854. end;
  13855. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  13856. var
  13857. hp1: tai;
  13858. begin
  13859. Result:=false;
  13860. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  13861. while GetNextInstruction(p, hp1) and
  13862. TrySwapMovCmp(p, hp1) do
  13863. begin
  13864. if MatchInstruction(hp1, A_MOV, []) then
  13865. begin
  13866. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13867. begin
  13868. { A little hacky, but since CMP doesn't read the flags, only
  13869. modify them, it's safe if they get scrambled by MOV -> XOR }
  13870. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13871. Result := PostPeepholeOptMov(hp1);
  13872. {$ifdef x86_64}
  13873. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13874. { Used to shrink instruction size }
  13875. PostPeepholeOptXor(hp1);
  13876. {$endif x86_64}
  13877. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13878. end
  13879. else
  13880. begin
  13881. Result := PostPeepholeOptMov(hp1);
  13882. {$ifdef x86_64}
  13883. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13884. { Used to shrink instruction size }
  13885. PostPeepholeOptXor(hp1);
  13886. {$endif x86_64}
  13887. end;
  13888. end;
  13889. { Enabling this flag is actually a null operation, but it marks
  13890. the code as 'modified' during this pass }
  13891. Include(OptsToCheck, aoc_ForceNewIteration);
  13892. end;
  13893. { change "cmp $0, %reg" to "test %reg, %reg" }
  13894. if MatchOpType(taicpu(p),top_const,top_reg) and
  13895. (taicpu(p).oper[0]^.val = 0) then
  13896. begin
  13897. taicpu(p).opcode := A_TEST;
  13898. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  13899. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  13900. Result:=true;
  13901. end;
  13902. end;
  13903. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  13904. var
  13905. IsTestConstX, IsValid : Boolean;
  13906. hp1,hp2 : tai;
  13907. begin
  13908. Result:=false;
  13909. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  13910. if (taicpu(p).opcode = A_TEST) then
  13911. while GetNextInstruction(p, hp1) and
  13912. TrySwapMovCmp(p, hp1) do
  13913. begin
  13914. if MatchInstruction(hp1, A_MOV, []) then
  13915. begin
  13916. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13917. begin
  13918. { A little hacky, but since TEST doesn't read the flags, only
  13919. modify them, it's safe if they get scrambled by MOV -> XOR }
  13920. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13921. Result := PostPeepholeOptMov(hp1);
  13922. {$ifdef x86_64}
  13923. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13924. { Used to shrink instruction size }
  13925. PostPeepholeOptXor(hp1);
  13926. {$endif x86_64}
  13927. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13928. end
  13929. else
  13930. begin
  13931. Result := PostPeepholeOptMov(hp1);
  13932. {$ifdef x86_64}
  13933. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13934. { Used to shrink instruction size }
  13935. PostPeepholeOptXor(hp1);
  13936. {$endif x86_64}
  13937. end;
  13938. end;
  13939. { Enabling this flag is actually a null operation, but it marks
  13940. the code as 'modified' during this pass }
  13941. Include(OptsToCheck, aoc_ForceNewIteration);
  13942. end;
  13943. { If x is a power of 2 (popcnt = 1), change:
  13944. or $x, %reg/ref
  13945. To:
  13946. bts lb(x), %reg/ref
  13947. }
  13948. if (taicpu(p).opcode = A_OR) and
  13949. IsBTXAcceptable(p) and
  13950. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  13951. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13952. (
  13953. { Don't optimise if a test instruction follows }
  13954. not GetNextInstruction(p, hp1) or
  13955. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  13956. ) then
  13957. begin
  13958. 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);
  13959. taicpu(p).opcode := A_BTS;
  13960. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13961. Result := True;
  13962. Exit;
  13963. end;
  13964. { If x is a power of 2 (popcnt = 1), change:
  13965. test $x, %reg/ref
  13966. je / sete / cmove (or jne / setne)
  13967. To:
  13968. bt lb(x), %reg/ref
  13969. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  13970. }
  13971. if (taicpu(p).opcode = A_TEST) and
  13972. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  13973. (taicpu(p).oper[0]^.typ = top_const) and
  13974. (
  13975. (cs_opt_size in current_settings.optimizerswitches) or
  13976. (
  13977. (taicpu(p).oper[1]^.typ = top_reg) and
  13978. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13979. ) or
  13980. (
  13981. (taicpu(p).oper[1]^.typ <> top_reg) and
  13982. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13983. )
  13984. ) and
  13985. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13986. { For sizes less than S_L, the byte size is equal or larger with BT,
  13987. so don't bother optimising }
  13988. (taicpu(p).opsize >= S_L) then
  13989. begin
  13990. IsValid := True;
  13991. { Check the next set of instructions, watching the FLAGS register
  13992. and the conditions used }
  13993. TransferUsedRegs(TmpUsedRegs);
  13994. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13995. hp1 := p;
  13996. hp2 := nil;
  13997. while GetNextInstruction(hp1, hp1) do
  13998. begin
  13999. if not Assigned(hp2) then
  14000. { The first instruction after TEST }
  14001. hp2 := hp1;
  14002. if (hp1.typ <> ait_instruction) then
  14003. begin
  14004. { If the flags are no longer in use, everything is fine }
  14005. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14006. IsValid := False;
  14007. Break;
  14008. end;
  14009. case taicpu(hp1).condition of
  14010. C_None:
  14011. begin
  14012. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14013. { Something is not quite normal, so play safe and don't change }
  14014. IsValid := False;
  14015. Break;
  14016. end;
  14017. C_E, C_Z, C_NE, C_NZ:
  14018. { This is fine };
  14019. else
  14020. begin
  14021. { Unsupported condition }
  14022. IsValid := False;
  14023. Break;
  14024. end;
  14025. end;
  14026. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  14027. end;
  14028. if IsValid then
  14029. begin
  14030. while hp2 <> hp1 do
  14031. begin
  14032. case taicpu(hp2).condition of
  14033. C_Z, C_E:
  14034. taicpu(hp2).condition := C_NC;
  14035. C_NZ, C_NE:
  14036. taicpu(hp2).condition := C_C;
  14037. else
  14038. { Should not get this by this point }
  14039. InternalError(2022110701);
  14040. end;
  14041. GetNextInstruction(hp2, hp2);
  14042. end;
  14043. 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);
  14044. taicpu(p).opcode := A_BT;
  14045. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14046. Result := True;
  14047. Exit;
  14048. end;
  14049. end;
  14050. { removes the line marked with (x) from the sequence
  14051. and/or/xor/add/sub/... $x, %y
  14052. test/or %y, %y | test $-1, %y (x)
  14053. j(n)z _Label
  14054. as the first instruction already adjusts the ZF
  14055. %y operand may also be a reference }
  14056. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  14057. MatchOperand(taicpu(p).oper[0]^,-1);
  14058. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  14059. GetLastInstruction(p, hp1) and
  14060. (tai(hp1).typ = ait_instruction) and
  14061. GetNextInstruction(p,hp2) and
  14062. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  14063. case taicpu(hp1).opcode Of
  14064. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  14065. { These two instructions set the zero flag if the result is zero }
  14066. A_POPCNT, A_LZCNT:
  14067. begin
  14068. if (
  14069. { With POPCNT, an input of zero will set the zero flag
  14070. because the population count of zero is zero }
  14071. (taicpu(hp1).opcode = A_POPCNT) and
  14072. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  14073. (
  14074. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  14075. { Faster than going through the second half of the 'or'
  14076. condition below }
  14077. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14078. )
  14079. ) or (
  14080. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14081. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14082. { and in case of carry for A(E)/B(E)/C/NC }
  14083. (
  14084. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14085. (
  14086. (taicpu(hp1).opcode <> A_ADD) and
  14087. (taicpu(hp1).opcode <> A_SUB) and
  14088. (taicpu(hp1).opcode <> A_LZCNT)
  14089. )
  14090. )
  14091. ) then
  14092. begin
  14093. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14094. RemoveCurrentP(p, hp2);
  14095. Result:=true;
  14096. Exit;
  14097. end;
  14098. end;
  14099. A_SHL, A_SAL, A_SHR, A_SAR:
  14100. begin
  14101. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14102. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14103. { therefore, it's only safe to do this optimization for }
  14104. { shifts by a (nonzero) constant }
  14105. (taicpu(hp1).oper[0]^.typ = top_const) and
  14106. (taicpu(hp1).oper[0]^.val <> 0) and
  14107. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14108. { and in case of carry for A(E)/B(E)/C/NC }
  14109. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14110. begin
  14111. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14112. RemoveCurrentP(p, hp2);
  14113. Result:=true;
  14114. Exit;
  14115. end;
  14116. end;
  14117. A_DEC, A_INC, A_NEG:
  14118. begin
  14119. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14120. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14121. { and in case of carry for A(E)/B(E)/C/NC }
  14122. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14123. begin
  14124. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14125. RemoveCurrentP(p, hp2);
  14126. Result:=true;
  14127. Exit;
  14128. end;
  14129. end;
  14130. A_ANDN, A_BZHI:
  14131. begin
  14132. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14133. { Only the zero and sign flags are consistent with what the result is }
  14134. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14135. begin
  14136. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14137. RemoveCurrentP(p, hp2);
  14138. Result:=true;
  14139. Exit;
  14140. end;
  14141. end;
  14142. A_BEXTR:
  14143. begin
  14144. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14145. { Only the zero flag is set }
  14146. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14147. begin
  14148. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14149. RemoveCurrentP(p, hp2);
  14150. Result:=true;
  14151. Exit;
  14152. end;
  14153. end;
  14154. else
  14155. ;
  14156. end; { case }
  14157. { change "test $-1,%reg" into "test %reg,%reg" }
  14158. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14159. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14160. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14161. if MatchInstruction(p, A_OR, []) and
  14162. { Can only match if they're both registers }
  14163. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14164. begin
  14165. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14166. taicpu(p).opcode := A_TEST;
  14167. { No need to set Result to True, as we've done all the optimisations we can }
  14168. end;
  14169. end;
  14170. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14171. var
  14172. hp1,hp3 : tai;
  14173. {$ifndef x86_64}
  14174. hp2 : taicpu;
  14175. {$endif x86_64}
  14176. begin
  14177. Result:=false;
  14178. hp3:=nil;
  14179. {$ifndef x86_64}
  14180. { don't do this on modern CPUs, this really hurts them due to
  14181. broken call/ret pairing }
  14182. if (current_settings.optimizecputype < cpu_Pentium2) and
  14183. not(cs_create_pic in current_settings.moduleswitches) and
  14184. GetNextInstruction(p, hp1) and
  14185. MatchInstruction(hp1,A_JMP,[S_NO]) and
  14186. MatchOpType(taicpu(hp1),top_ref) and
  14187. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14188. begin
  14189. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14190. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14191. InsertLLItem(p.previous, p, hp2);
  14192. taicpu(p).opcode := A_JMP;
  14193. taicpu(p).is_jmp := true;
  14194. RemoveInstruction(hp1);
  14195. Result:=true;
  14196. end
  14197. else
  14198. {$endif x86_64}
  14199. { replace
  14200. call procname
  14201. ret
  14202. by
  14203. jmp procname
  14204. but do it only on level 4 because it destroys stack back traces
  14205. else if the subroutine is marked as no return, remove the ret
  14206. }
  14207. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14208. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14209. GetNextInstruction(p, hp1) and
  14210. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14211. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14212. SetAndTest(hp1,hp3) and
  14213. GetNextInstruction(hp1,hp1) and
  14214. MatchInstruction(hp1,A_RET,[S_NO])
  14215. )
  14216. ) and
  14217. (taicpu(hp1).ops=0) then
  14218. begin
  14219. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14220. { we might destroy stack alignment here if we do not do a call }
  14221. (target_info.stackalign<=sizeof(SizeUInt)) then
  14222. begin
  14223. taicpu(p).opcode := A_JMP;
  14224. taicpu(p).is_jmp := true;
  14225. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14226. end
  14227. else
  14228. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14229. RemoveInstruction(hp1);
  14230. if Assigned(hp3) then
  14231. begin
  14232. AsmL.Remove(hp3);
  14233. AsmL.InsertBefore(hp3,p)
  14234. end;
  14235. Result:=true;
  14236. end;
  14237. end;
  14238. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14239. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14240. begin
  14241. case OpSize of
  14242. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14243. Result := (Val <= $FF) and (Val >= -128);
  14244. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14245. Result := (Val <= $FFFF) and (Val >= -32768);
  14246. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14247. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14248. else
  14249. Result := True;
  14250. end;
  14251. end;
  14252. var
  14253. hp1, hp2 : tai;
  14254. SizeChange: Boolean;
  14255. PreMessage: string;
  14256. begin
  14257. Result := False;
  14258. if (taicpu(p).oper[0]^.typ = top_reg) and
  14259. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14260. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14261. begin
  14262. { Change (using movzbl %al,%eax as an example):
  14263. movzbl %al, %eax movzbl %al, %eax
  14264. cmpl x, %eax testl %eax,%eax
  14265. To:
  14266. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14267. movzbl %al, %eax movzbl %al, %eax
  14268. Smaller instruction and minimises pipeline stall as the CPU
  14269. doesn't have to wait for the register to get zero-extended. [Kit]
  14270. Also allow if the smaller of the two registers is being checked,
  14271. as this still removes the false dependency.
  14272. }
  14273. if
  14274. (
  14275. (
  14276. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14277. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14278. ) or (
  14279. { If MatchOperand returns True, they must both be registers }
  14280. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14281. )
  14282. ) and
  14283. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14284. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14285. begin
  14286. 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);
  14287. asml.Remove(hp1);
  14288. asml.InsertBefore(hp1, p);
  14289. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14290. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14291. begin
  14292. taicpu(hp1).opcode := A_TEST;
  14293. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14294. end;
  14295. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14296. case taicpu(p).opsize of
  14297. S_BW, S_BL:
  14298. begin
  14299. SizeChange := taicpu(hp1).opsize <> S_B;
  14300. taicpu(hp1).changeopsize(S_B);
  14301. end;
  14302. S_WL:
  14303. begin
  14304. SizeChange := taicpu(hp1).opsize <> S_W;
  14305. taicpu(hp1).changeopsize(S_W);
  14306. end
  14307. else
  14308. InternalError(2020112701);
  14309. end;
  14310. UpdateUsedRegs(tai(p.Next));
  14311. { Check if the register is used aferwards - if not, we can
  14312. remove the movzx instruction completely }
  14313. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14314. begin
  14315. { Hp1 is a better position than p for debugging purposes }
  14316. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14317. RemoveCurrentp(p, hp1);
  14318. Result := True;
  14319. end;
  14320. if SizeChange then
  14321. DebugMsg(SPeepholeOptimization + PreMessage +
  14322. 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)
  14323. else
  14324. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14325. Exit;
  14326. end;
  14327. { Change (using movzwl %ax,%eax as an example):
  14328. movzwl %ax, %eax
  14329. movb %al, (dest) (Register is smaller than read register in movz)
  14330. To:
  14331. movb %al, (dest) (Move one back to avoid a false dependency)
  14332. movzwl %ax, %eax
  14333. }
  14334. if (taicpu(hp1).opcode = A_MOV) and
  14335. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14336. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14337. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14338. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14339. begin
  14340. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14341. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14342. asml.Remove(hp1);
  14343. asml.InsertBefore(hp1, p);
  14344. if taicpu(hp1).oper[1]^.typ = top_reg then
  14345. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14346. { Check if the register is used aferwards - if not, we can
  14347. remove the movzx instruction completely }
  14348. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14349. begin
  14350. { Hp1 is a better position than p for debugging purposes }
  14351. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14352. RemoveCurrentp(p, hp1);
  14353. Result := True;
  14354. end;
  14355. Exit;
  14356. end;
  14357. end;
  14358. end;
  14359. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14360. var
  14361. hp1: tai;
  14362. {$ifdef x86_64}
  14363. PreMessage, RegName: string;
  14364. {$endif x86_64}
  14365. begin
  14366. Result := False;
  14367. { If x is a power of 2 (popcnt = 1), change:
  14368. xor $x, %reg/ref
  14369. To:
  14370. btc lb(x), %reg/ref
  14371. }
  14372. if IsBTXAcceptable(p) and
  14373. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14374. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14375. (
  14376. { Don't optimise if a test instruction follows }
  14377. not GetNextInstruction(p, hp1) or
  14378. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14379. ) then
  14380. begin
  14381. 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);
  14382. taicpu(p).opcode := A_BTC;
  14383. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14384. Result := True;
  14385. Exit;
  14386. end;
  14387. {$ifdef x86_64}
  14388. { Code size reduction by J. Gareth "Kit" Moreton }
  14389. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14390. as this removes the REX prefix }
  14391. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14392. Exit;
  14393. if taicpu(p).oper[0]^.typ <> top_reg then
  14394. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14395. InternalError(2018011500);
  14396. case taicpu(p).opsize of
  14397. S_Q:
  14398. begin
  14399. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14400. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14401. { The actual optimization }
  14402. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14403. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14404. taicpu(p).changeopsize(S_L);
  14405. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14406. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14407. end;
  14408. else
  14409. ;
  14410. end;
  14411. {$endif x86_64}
  14412. end;
  14413. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14414. var
  14415. XReg: TRegister;
  14416. begin
  14417. Result := False;
  14418. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14419. Smaller encoding and slightly faster on some platforms (also works for
  14420. ZMM-sized registers) }
  14421. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14422. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14423. begin
  14424. XReg := taicpu(p).oper[0]^.reg;
  14425. if (taicpu(p).oper[1]^.reg = XReg) then
  14426. begin
  14427. taicpu(p).changeopsize(S_XMM);
  14428. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14429. if (cs_opt_size in current_settings.optimizerswitches) then
  14430. begin
  14431. { Change input registers to %xmm0 to reduce size. Note that
  14432. there's a risk of a false dependency doing this, so only
  14433. optimise for size here }
  14434. XReg := NR_XMM0;
  14435. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14436. end
  14437. else
  14438. begin
  14439. setsubreg(XReg, R_SUBMMX);
  14440. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14441. end;
  14442. taicpu(p).oper[0]^.reg := XReg;
  14443. taicpu(p).oper[1]^.reg := XReg;
  14444. Result := True;
  14445. end;
  14446. end;
  14447. end;
  14448. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14449. var
  14450. OperIdx: Integer;
  14451. begin
  14452. for OperIdx := 0 to p.ops - 1 do
  14453. if p.oper[OperIdx]^.typ = top_ref then
  14454. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14455. end;
  14456. end.