aoptx86.pas 674 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. { Attempts to allocate a volatile integer register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  79. { Attempts to allocate a volatile MM register for use between p and hp,
  80. using AUsedRegs for the current register usage information. Returns NR_NO
  81. if no free register could be found }
  82. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  83. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  84. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  85. { checks whether reading the value in reg1 depends on the value of reg2. This
  86. is very similar to SuperRegisterEquals, except it takes into account that
  87. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  88. depend on the value in AH). }
  89. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  90. { Replaces all references to AOldReg in a memory reference to ANewReg }
  91. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Replaces all references to AOldReg in an operand to ANewReg }
  93. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an instruction to ANewReg,
  95. except where the register is being written }
  96. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  97. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  98. or writes to a global symbol }
  99. class function IsRefSafe(const ref: PReference): Boolean; static;
  100. { Returns true if the given MOV instruction can be safely converted to CMOV }
  101. class function CanBeCMOV(p, cond_p: tai) : boolean; static;
  102. { Like UpdateUsedRegs, but ignores deallocations }
  103. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  104. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  105. class function IsBTXAcceptable(p : tai) : boolean; static;
  106. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  107. conversion was successful }
  108. function ConvertLEA(const p : taicpu): Boolean;
  109. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  110. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  111. procedure DebugMsg(const s : string; p : tai);inline;
  112. class function IsExitCode(p : tai) : boolean; static;
  113. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  114. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  115. procedure RemoveLastDeallocForFuncRes(p : tai);
  116. function DoArithCombineOpt(var p : tai) : Boolean;
  117. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  118. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  119. function PrePeepholeOptSxx(var p : tai) : boolean;
  120. function PrePeepholeOptIMUL(var p : tai) : boolean;
  121. function PrePeepholeOptAND(var p : tai) : boolean;
  122. function OptPass1Test(var p: tai): boolean;
  123. function OptPass1Add(var p: tai): boolean;
  124. function OptPass1AND(var p : tai) : boolean;
  125. function OptPass1_V_MOVAP(var p : tai) : boolean;
  126. function OptPass1VOP(var p : tai) : boolean;
  127. function OptPass1MOV(var p : tai) : boolean;
  128. function OptPass1Movx(var p : tai) : boolean;
  129. function OptPass1MOVXX(var p : tai) : boolean;
  130. function OptPass1OP(var p : tai) : boolean;
  131. function OptPass1LEA(var p : tai) : boolean;
  132. function OptPass1Sub(var p : tai) : boolean;
  133. function OptPass1SHLSAL(var p : tai) : boolean;
  134. function OptPass1SHR(var p : tai) : boolean;
  135. function OptPass1FSTP(var p : tai) : boolean;
  136. function OptPass1FLD(var p : tai) : boolean;
  137. function OptPass1Cmp(var p : tai) : boolean;
  138. function OptPass1PXor(var p : tai) : boolean;
  139. function OptPass1VPXor(var p: tai): boolean;
  140. function OptPass1Imul(var p : tai) : boolean;
  141. function OptPass1Jcc(var p : tai) : boolean;
  142. function OptPass1SHXX(var p: tai): boolean;
  143. function OptPass1VMOVDQ(var p: tai): Boolean;
  144. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  145. function OptPass2Movx(var p : tai): Boolean;
  146. function OptPass2MOV(var p : tai) : boolean;
  147. function OptPass2Imul(var p : tai) : boolean;
  148. function OptPass2Jmp(var p : tai) : boolean;
  149. function OptPass2Jcc(var p : tai) : boolean;
  150. function OptPass2Lea(var p: tai): Boolean;
  151. function OptPass2SUB(var p: tai): Boolean;
  152. function OptPass2ADD(var p : tai): Boolean;
  153. function OptPass2SETcc(var p : tai) : boolean;
  154. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  155. function PostPeepholeOptMov(var p : tai) : Boolean;
  156. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  157. function PostPeepholeOptXor(var p : tai) : Boolean;
  158. function PostPeepholeOptAnd(var p : tai) : boolean;
  159. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  160. function PostPeepholeOptCmp(var p : tai) : Boolean;
  161. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  162. function PostPeepholeOptCall(var p : tai) : Boolean;
  163. function PostPeepholeOptLea(var p : tai) : Boolean;
  164. function PostPeepholeOptPush(var p: tai): Boolean;
  165. function PostPeepholeOptShr(var p : tai) : boolean;
  166. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  167. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  168. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  169. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  170. function TrySwapMovOp(var p, hp1: tai): Boolean;
  171. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  172. { Processor-dependent reference optimisation }
  173. class procedure OptimizeRefs(var p: taicpu); static;
  174. end;
  175. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  176. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  177. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  178. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  179. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  180. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  181. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  182. {$if max_operands>2}
  183. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  184. {$endif max_operands>2}
  185. function RefsEqual(const r1, r2: treference): boolean;
  186. { Note that Result is set to True if the references COULD overlap but the
  187. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  188. might still overlap because %reg2 could be equal to %reg1-4 }
  189. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  190. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  191. { returns true, if ref is a reference using only the registers passed as base and index
  192. and having an offset }
  193. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  194. implementation
  195. uses
  196. cutils,verbose,
  197. systems,
  198. globals,
  199. cpuinfo,
  200. procinfo,
  201. paramgr,
  202. aasmbase,
  203. aoptbase,aoptutils,
  204. symconst,symsym,
  205. cgx86,
  206. itcpugas;
  207. {$ifdef DEBUG_AOPTCPU}
  208. const
  209. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  210. {$else DEBUG_AOPTCPU}
  211. { Empty strings help the optimizer to remove string concatenations that won't
  212. ever appear to the user on release builds. [Kit] }
  213. const
  214. SPeepholeOptimization = '';
  215. {$endif DEBUG_AOPTCPU}
  216. LIST_STEP_SIZE = 4;
  217. {$ifndef 8086}
  218. MAX_CMOV_INSTRUCTIONS = 4;
  219. MAX_CMOV_REGISTERS = 8;
  220. {$endif 8086}
  221. type
  222. TJumpTrackingItem = class(TLinkedListItem)
  223. private
  224. FSymbol: TAsmSymbol;
  225. FRefs: LongInt;
  226. public
  227. constructor Create(ASymbol: TAsmSymbol);
  228. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  229. property Symbol: TAsmSymbol read FSymbol;
  230. property Refs: LongInt read FRefs;
  231. end;
  232. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  233. begin
  234. inherited Create;
  235. FSymbol := ASymbol;
  236. FRefs := 0;
  237. end;
  238. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  239. begin
  240. Inc(FRefs);
  241. end;
  242. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  243. begin
  244. result :=
  245. (instr.typ = ait_instruction) and
  246. (taicpu(instr).opcode = op) and
  247. ((opsize = []) or (taicpu(instr).opsize in opsize));
  248. end;
  249. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  250. begin
  251. result :=
  252. (instr.typ = ait_instruction) and
  253. ((taicpu(instr).opcode = op1) or
  254. (taicpu(instr).opcode = op2)
  255. ) and
  256. ((opsize = []) or (taicpu(instr).opsize in opsize));
  257. end;
  258. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  259. begin
  260. result :=
  261. (instr.typ = ait_instruction) and
  262. ((taicpu(instr).opcode = op1) or
  263. (taicpu(instr).opcode = op2) or
  264. (taicpu(instr).opcode = op3)
  265. ) and
  266. ((opsize = []) or (taicpu(instr).opsize in opsize));
  267. end;
  268. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  269. const opsize : topsizes) : boolean;
  270. var
  271. op : TAsmOp;
  272. begin
  273. result:=false;
  274. if (instr.typ <> ait_instruction) or
  275. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  276. exit;
  277. for op in ops do
  278. begin
  279. if taicpu(instr).opcode = op then
  280. begin
  281. result:=true;
  282. exit;
  283. end;
  284. end;
  285. end;
  286. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  287. begin
  288. result := (oper.typ = top_reg) and (oper.reg = reg);
  289. end;
  290. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  291. begin
  292. result := (oper.typ = top_const) and (oper.val = a);
  293. end;
  294. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  295. begin
  296. result := oper1.typ = oper2.typ;
  297. if result then
  298. case oper1.typ of
  299. top_const:
  300. Result:=oper1.val = oper2.val;
  301. top_reg:
  302. Result:=oper1.reg = oper2.reg;
  303. top_ref:
  304. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  305. else
  306. internalerror(2013102801);
  307. end
  308. end;
  309. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  310. begin
  311. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  312. if result then
  313. case oper1.typ of
  314. top_const:
  315. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  316. top_reg:
  317. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  318. top_ref:
  319. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  320. else
  321. internalerror(2020052401);
  322. end
  323. end;
  324. function RefsEqual(const r1, r2: treference): boolean;
  325. begin
  326. RefsEqual :=
  327. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  328. (r1.relsymbol = r2.relsymbol) and
  329. (r1.segment = r2.segment) and (r1.base = r2.base) and
  330. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  331. (r1.offset = r2.offset) and
  332. (r1.volatility + r2.volatility = []);
  333. end;
  334. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  335. begin
  336. if (r1.symbol<>r2.symbol) then
  337. { If the index registers are different, there's a chance one could
  338. be set so it equals the other symbol }
  339. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  340. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  341. (r1.relsymbol = r2.relsymbol) and
  342. (r1.segment = r2.segment) and (r1.base = r2.base) and
  343. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  344. (r1.volatility + r2.volatility = []) then
  345. { In this case, it all depends on the offsets }
  346. Exit(abs(r1.offset - r2.offset) < Range);
  347. { There's a chance things MIGHT overlap, so take no chances }
  348. Result := True;
  349. end;
  350. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  351. begin
  352. Result:=(ref.offset=0) and
  353. (ref.scalefactor in [0,1]) and
  354. (ref.segment=NR_NO) and
  355. (ref.symbol=nil) and
  356. (ref.relsymbol=nil) and
  357. ((base=NR_INVALID) or
  358. (ref.base=base)) and
  359. ((index=NR_INVALID) or
  360. (ref.index=index)) and
  361. (ref.volatility=[]);
  362. end;
  363. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  364. begin
  365. Result:=(ref.scalefactor in [0,1]) and
  366. (ref.segment=NR_NO) and
  367. (ref.symbol=nil) and
  368. (ref.relsymbol=nil) and
  369. ((base=NR_INVALID) or
  370. (ref.base=base)) and
  371. ((index=NR_INVALID) or
  372. (ref.index=index)) and
  373. (ref.volatility=[]);
  374. end;
  375. function InstrReadsFlags(p: tai): boolean;
  376. begin
  377. InstrReadsFlags := true;
  378. case p.typ of
  379. ait_instruction:
  380. if InsProp[taicpu(p).opcode].Ch*
  381. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  382. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  383. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  384. exit;
  385. ait_label:
  386. exit;
  387. else
  388. ;
  389. end;
  390. InstrReadsFlags := false;
  391. end;
  392. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  393. begin
  394. Next:=Current;
  395. repeat
  396. Result:=GetNextInstruction(Next,Next);
  397. until not (Result) or
  398. not(cs_opt_level3 in current_settings.optimizerswitches) or
  399. (Next.typ<>ait_instruction) or
  400. RegInInstruction(reg,Next) or
  401. is_calljmp(taicpu(Next).opcode);
  402. end;
  403. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  404. var
  405. GetNextResult: Boolean;
  406. begin
  407. Result:=0;
  408. Next:=Current;
  409. repeat
  410. GetNextResult := GetNextInstruction(Next,Next);
  411. if GetNextResult then
  412. Inc(Result)
  413. else
  414. { Must return zero upon hitting the end of the linked list without a match }
  415. Result := 0;
  416. until not (GetNextResult) or
  417. not(cs_opt_level3 in current_settings.optimizerswitches) or
  418. (Next.typ<>ait_instruction) or
  419. RegInInstruction(reg,Next) or
  420. is_calljmp(taicpu(Next).opcode);
  421. end;
  422. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  423. procedure TrackJump(Symbol: TAsmSymbol);
  424. var
  425. Search: TJumpTrackingItem;
  426. begin
  427. { See if an entry already exists in our jump tracking list
  428. (faster to search backwards due to the higher chance of
  429. matching destinations) }
  430. Search := TJumpTrackingItem(JumpTracking.Last);
  431. while Assigned(Search) do
  432. begin
  433. if Search.Symbol = Symbol then
  434. begin
  435. { Found it - remove it so it can be pushed to the front }
  436. JumpTracking.Remove(Search);
  437. Break;
  438. end;
  439. Search := TJumpTrackingItem(Search.Previous);
  440. end;
  441. if not Assigned(Search) then
  442. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  443. JumpTracking.Concat(Search);
  444. Search.IncRefs;
  445. end;
  446. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  447. var
  448. Search: TJumpTrackingItem;
  449. begin
  450. Result := False;
  451. { See if this label appears in the tracking list }
  452. Search := TJumpTrackingItem(JumpTracking.Last);
  453. while Assigned(Search) do
  454. begin
  455. if Search.Symbol = Symbol then
  456. begin
  457. { Found it - let's see what we can discover }
  458. if Search.Symbol.getrefs = Search.Refs then
  459. begin
  460. { Success - all the references are accounted for }
  461. JumpTracking.Remove(Search);
  462. Search.Free;
  463. { It is logically impossible for CrossJump to be false here
  464. because we must have run into a conditional jump for
  465. this label at some point }
  466. if not CrossJump then
  467. InternalError(2022041710);
  468. if JumpTracking.First = nil then
  469. { Tracking list is now empty - no more cross jumps }
  470. CrossJump := False;
  471. Result := True;
  472. Exit;
  473. end;
  474. { If the references don't match, it's possible to enter
  475. this label through other means, so drop out }
  476. Exit;
  477. end;
  478. Search := TJumpTrackingItem(Search.Previous);
  479. end;
  480. end;
  481. var
  482. Next_Label: tai;
  483. begin
  484. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  485. Next := Current;
  486. repeat
  487. Result := GetNextInstruction(Next,Next);
  488. if not Result then
  489. Break;
  490. if Next.typ = ait_align then
  491. Result := SkipAligns(Next, Next);
  492. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  493. if is_calljmpuncondret(taicpu(Next).opcode) then
  494. begin
  495. if (taicpu(Next).opcode = A_JMP) and
  496. { Remove dead code now to save time }
  497. RemoveDeadCodeAfterJump(taicpu(Next)) then
  498. { A jump was removed, but not the current instruction, and
  499. Result doesn't necessarily translate into an optimisation
  500. routine's Result, so use the "Force New Iteration" flag so
  501. mark a new pass }
  502. Include(OptsToCheck, aoc_ForceNewIteration);
  503. if not Assigned(JumpTracking) then
  504. begin
  505. { Cross-label optimisations often causes other optimisations
  506. to perform worse because they're not given the chance to
  507. optimise locally. In this case, don't do the cross-label
  508. optimisations yet, but flag them as a potential possibility
  509. for the next iteration of Pass 1 }
  510. if not NotFirstIteration then
  511. Include(OptsToCheck, aoc_ForceNewIteration);
  512. end
  513. else if IsJumpToLabel(taicpu(Next)) and
  514. GetNextInstruction(Next, Next_Label) and
  515. SkipAligns(Next_Label, Next_Label) then
  516. begin
  517. { If we have JMP .lbl, and the label after it has all of its
  518. references tracked, then this is probably an if-else style of
  519. block and we can keep tracking. If the label for this jump
  520. then appears later and is fully tracked, then it's the end
  521. of the if-else blocks and the code paths converge (thus
  522. marking the end of the cross-jump) }
  523. if (Next_Label.typ = ait_label) then
  524. begin
  525. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  526. begin
  527. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  528. Next := Next_Label;
  529. { CrossJump gets set to false by LabelAccountedFor if the
  530. list is completely emptied (as it indicates that all
  531. code paths have converged). We could avoid this nuance
  532. by moving the TrackJump call to before the
  533. LabelAccountedFor call, but this is slower in situations
  534. where LabelAccountedFor would return False due to the
  535. creation of a new object that is not used and destroyed
  536. soon after. }
  537. CrossJump := True;
  538. Continue;
  539. end;
  540. end
  541. else if (Next_Label.typ <> ait_marker) then
  542. { We just did a RemoveDeadCodeAfterJump, so either we find
  543. a label, the end of the procedure or some kind of marker}
  544. InternalError(2022041720);
  545. end;
  546. Result := False;
  547. Exit;
  548. end
  549. else
  550. begin
  551. if not Assigned(JumpTracking) then
  552. begin
  553. { Cross-label optimisations often causes other optimisations
  554. to perform worse because they're not given the chance to
  555. optimise locally. In this case, don't do the cross-label
  556. optimisations yet, but flag them as a potential possibility
  557. for the next iteration of Pass 1 }
  558. if not NotFirstIteration then
  559. Include(OptsToCheck, aoc_ForceNewIteration);
  560. end
  561. else if IsJumpToLabel(taicpu(Next)) then
  562. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  563. else
  564. { Conditional jumps should always be a jump to label }
  565. InternalError(2022041701);
  566. CrossJump := True;
  567. Continue;
  568. end;
  569. if Next.typ = ait_label then
  570. begin
  571. if not Assigned(JumpTracking) then
  572. begin
  573. { Cross-label optimisations often causes other optimisations
  574. to perform worse because they're not given the chance to
  575. optimise locally. In this case, don't do the cross-label
  576. optimisations yet, but flag them as a potential possibility
  577. for the next iteration of Pass 1 }
  578. if not NotFirstIteration then
  579. Include(OptsToCheck, aoc_ForceNewIteration);
  580. end
  581. else if LabelAccountedFor(tai_label(Next).labsym) then
  582. Continue;
  583. { If we reach here, we're at a label that hasn't been seen before
  584. (or JumpTracking was nil) }
  585. Break;
  586. end;
  587. until not Result or
  588. not (cs_opt_level3 in current_settings.optimizerswitches) or
  589. not (Next.typ in [ait_label, ait_instruction]) or
  590. RegInInstruction(reg,Next);
  591. end;
  592. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  593. begin
  594. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  595. begin
  596. Result:=GetNextInstruction(Current,Next);
  597. exit;
  598. end;
  599. Next:=tai(Current.Next);
  600. Result:=false;
  601. while assigned(Next) do
  602. begin
  603. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  604. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  605. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  606. exit
  607. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  608. begin
  609. Result:=true;
  610. exit;
  611. end;
  612. Next:=tai(Next.Next);
  613. end;
  614. end;
  615. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  616. begin
  617. Result:=RegReadByInstruction(reg,hp);
  618. end;
  619. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  620. var
  621. p: taicpu;
  622. opcount: longint;
  623. begin
  624. RegReadByInstruction := false;
  625. if hp.typ <> ait_instruction then
  626. exit;
  627. p := taicpu(hp);
  628. case p.opcode of
  629. A_CALL:
  630. regreadbyinstruction := true;
  631. A_IMUL:
  632. case p.ops of
  633. 1:
  634. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  635. (
  636. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  637. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  638. );
  639. 2,3:
  640. regReadByInstruction :=
  641. reginop(reg,p.oper[0]^) or
  642. reginop(reg,p.oper[1]^);
  643. else
  644. InternalError(2019112801);
  645. end;
  646. A_MUL:
  647. begin
  648. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  649. (
  650. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  651. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  652. );
  653. end;
  654. A_IDIV,A_DIV:
  655. begin
  656. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  657. (
  658. (getregtype(reg)=R_INTREGISTER) and
  659. (
  660. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  661. )
  662. );
  663. end;
  664. else
  665. begin
  666. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  667. begin
  668. RegReadByInstruction := false;
  669. exit;
  670. end;
  671. for opcount := 0 to p.ops-1 do
  672. if (p.oper[opCount]^.typ = top_ref) and
  673. RegInRef(reg,p.oper[opcount]^.ref^) then
  674. begin
  675. RegReadByInstruction := true;
  676. exit
  677. end;
  678. { special handling for SSE MOVSD }
  679. if (p.opcode=A_MOVSD) and (p.ops>0) then
  680. begin
  681. if p.ops<>2 then
  682. internalerror(2017042702);
  683. regReadByInstruction := reginop(reg,p.oper[0]^) or
  684. (
  685. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  686. );
  687. exit;
  688. end;
  689. with insprop[p.opcode] do
  690. begin
  691. case getregtype(reg) of
  692. R_INTREGISTER:
  693. begin
  694. case getsupreg(reg) of
  695. RS_EAX:
  696. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  697. begin
  698. RegReadByInstruction := true;
  699. exit
  700. end;
  701. RS_ECX:
  702. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  703. begin
  704. RegReadByInstruction := true;
  705. exit
  706. end;
  707. RS_EDX:
  708. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  709. begin
  710. RegReadByInstruction := true;
  711. exit
  712. end;
  713. RS_EBX:
  714. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  715. begin
  716. RegReadByInstruction := true;
  717. exit
  718. end;
  719. RS_ESP:
  720. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  721. begin
  722. RegReadByInstruction := true;
  723. exit
  724. end;
  725. RS_EBP:
  726. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  727. begin
  728. RegReadByInstruction := true;
  729. exit
  730. end;
  731. RS_ESI:
  732. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  733. begin
  734. RegReadByInstruction := true;
  735. exit
  736. end;
  737. RS_EDI:
  738. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  739. begin
  740. RegReadByInstruction := true;
  741. exit
  742. end;
  743. end;
  744. end;
  745. R_MMREGISTER:
  746. begin
  747. case getsupreg(reg) of
  748. RS_XMM0:
  749. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  750. begin
  751. RegReadByInstruction := true;
  752. exit
  753. end;
  754. end;
  755. end;
  756. else
  757. ;
  758. end;
  759. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  760. begin
  761. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  762. begin
  763. case p.condition of
  764. C_A,C_NBE, { CF=0 and ZF=0 }
  765. C_BE,C_NA: { CF=1 or ZF=1 }
  766. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  767. C_AE,C_NB,C_NC, { CF=0 }
  768. C_B,C_NAE,C_C: { CF=1 }
  769. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  770. C_NE,C_NZ, { ZF=0 }
  771. C_E,C_Z: { ZF=1 }
  772. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  773. C_G,C_NLE, { ZF=0 and SF=OF }
  774. C_LE,C_NG: { ZF=1 or SF<>OF }
  775. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  776. C_GE,C_NL, { SF=OF }
  777. C_L,C_NGE: { SF<>OF }
  778. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  779. C_NO, { OF=0 }
  780. C_O: { OF=1 }
  781. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  782. C_NP,C_PO, { PF=0 }
  783. C_P,C_PE: { PF=1 }
  784. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  785. C_NS, { SF=0 }
  786. C_S: { SF=1 }
  787. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  788. else
  789. internalerror(2017042701);
  790. end;
  791. if RegReadByInstruction then
  792. exit;
  793. end;
  794. case getsubreg(reg) of
  795. R_SUBW,R_SUBD,R_SUBQ:
  796. RegReadByInstruction :=
  797. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  798. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  799. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  800. R_SUBFLAGCARRY:
  801. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  802. R_SUBFLAGPARITY:
  803. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  804. R_SUBFLAGAUXILIARY:
  805. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  806. R_SUBFLAGZERO:
  807. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  808. R_SUBFLAGSIGN:
  809. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  810. R_SUBFLAGOVERFLOW:
  811. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  812. R_SUBFLAGINTERRUPT:
  813. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  814. R_SUBFLAGDIRECTION:
  815. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  816. else
  817. internalerror(2017042601);
  818. end;
  819. exit;
  820. end;
  821. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  822. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  823. (p.oper[0]^.reg=p.oper[1]^.reg) then
  824. exit;
  825. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  826. begin
  827. RegReadByInstruction := true;
  828. exit
  829. end;
  830. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  831. begin
  832. RegReadByInstruction := true;
  833. exit
  834. end;
  835. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  836. begin
  837. RegReadByInstruction := true;
  838. exit
  839. end;
  840. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  841. begin
  842. RegReadByInstruction := true;
  843. exit
  844. end;
  845. end;
  846. end;
  847. end;
  848. end;
  849. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  850. begin
  851. result:=false;
  852. if p1.typ<>ait_instruction then
  853. exit;
  854. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  855. exit(true);
  856. if (getregtype(reg)=R_INTREGISTER) and
  857. { change information for xmm movsd are not correct }
  858. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  859. begin
  860. case getsupreg(reg) of
  861. { RS_EAX = RS_RAX on x86-64 }
  862. RS_EAX:
  863. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  864. RS_ECX:
  865. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  866. RS_EDX:
  867. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  868. RS_EBX:
  869. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  870. RS_ESP:
  871. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  872. RS_EBP:
  873. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  874. RS_ESI:
  875. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  876. RS_EDI:
  877. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  878. else
  879. ;
  880. end;
  881. if result then
  882. exit;
  883. end
  884. else if getregtype(reg)=R_MMREGISTER then
  885. begin
  886. case getsupreg(reg) of
  887. RS_XMM0:
  888. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  889. else
  890. ;
  891. end;
  892. if result then
  893. exit;
  894. end
  895. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  896. begin
  897. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  898. exit(true);
  899. case getsubreg(reg) of
  900. R_SUBFLAGCARRY:
  901. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  902. R_SUBFLAGPARITY:
  903. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  904. R_SUBFLAGAUXILIARY:
  905. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  906. R_SUBFLAGZERO:
  907. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  908. R_SUBFLAGSIGN:
  909. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  910. R_SUBFLAGOVERFLOW:
  911. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  912. R_SUBFLAGINTERRUPT:
  913. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  914. R_SUBFLAGDIRECTION:
  915. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  916. R_SUBW,R_SUBD,R_SUBQ:
  917. { Everything except the direction bits }
  918. Result:=
  919. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  920. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  921. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  922. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  923. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  924. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  925. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  926. else
  927. ;
  928. end;
  929. if result then
  930. exit;
  931. end
  932. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  933. exit(true);
  934. Result:=inherited RegInInstruction(Reg, p1);
  935. end;
  936. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  937. const
  938. WriteOps: array[0..3] of set of TInsChange =
  939. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  940. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  941. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  942. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  943. var
  944. OperIdx: Integer;
  945. begin
  946. Result := False;
  947. if p1.typ <> ait_instruction then
  948. exit;
  949. with insprop[taicpu(p1).opcode] do
  950. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  951. begin
  952. case getsubreg(reg) of
  953. R_SUBW,R_SUBD,R_SUBQ:
  954. Result :=
  955. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  956. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  957. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  958. R_SUBFLAGCARRY:
  959. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  960. R_SUBFLAGPARITY:
  961. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  962. R_SUBFLAGAUXILIARY:
  963. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  964. R_SUBFLAGZERO:
  965. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  966. R_SUBFLAGSIGN:
  967. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  968. R_SUBFLAGOVERFLOW:
  969. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  970. R_SUBFLAGINTERRUPT:
  971. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  972. R_SUBFLAGDIRECTION:
  973. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  974. else
  975. internalerror(2017042602);
  976. end;
  977. exit;
  978. end;
  979. case taicpu(p1).opcode of
  980. A_CALL:
  981. { We could potentially set Result to False if the register in
  982. question is non-volatile for the subroutine's calling convention,
  983. but this would require detecting the calling convention in use and
  984. also assuming that the routine doesn't contain malformed assembly
  985. language, for example... so it could only be done under -O4 as it
  986. would be considered a side-effect. [Kit] }
  987. Result := True;
  988. A_MOVSD:
  989. { special handling for SSE MOVSD }
  990. if (taicpu(p1).ops>0) then
  991. begin
  992. if taicpu(p1).ops<>2 then
  993. internalerror(2017042703);
  994. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  995. end;
  996. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  997. so fix it here (FK)
  998. }
  999. A_VMOVSS,
  1000. A_VMOVSD:
  1001. begin
  1002. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1003. exit;
  1004. end;
  1005. A_IMUL:
  1006. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1007. else
  1008. ;
  1009. end;
  1010. if Result then
  1011. exit;
  1012. with insprop[taicpu(p1).opcode] do
  1013. begin
  1014. if getregtype(reg)=R_INTREGISTER then
  1015. begin
  1016. case getsupreg(reg) of
  1017. RS_EAX:
  1018. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1019. begin
  1020. Result := True;
  1021. exit
  1022. end;
  1023. RS_ECX:
  1024. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1025. begin
  1026. Result := True;
  1027. exit
  1028. end;
  1029. RS_EDX:
  1030. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1031. begin
  1032. Result := True;
  1033. exit
  1034. end;
  1035. RS_EBX:
  1036. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1037. begin
  1038. Result := True;
  1039. exit
  1040. end;
  1041. RS_ESP:
  1042. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1043. begin
  1044. Result := True;
  1045. exit
  1046. end;
  1047. RS_EBP:
  1048. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1049. begin
  1050. Result := True;
  1051. exit
  1052. end;
  1053. RS_ESI:
  1054. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1055. begin
  1056. Result := True;
  1057. exit
  1058. end;
  1059. RS_EDI:
  1060. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1061. begin
  1062. Result := True;
  1063. exit
  1064. end;
  1065. end;
  1066. end;
  1067. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1068. if (WriteOps[OperIdx]*Ch<>[]) and
  1069. { The register doesn't get modified inside a reference }
  1070. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1071. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1072. begin
  1073. Result := true;
  1074. exit
  1075. end;
  1076. end;
  1077. end;
  1078. {$ifdef DEBUG_AOPTCPU}
  1079. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1080. begin
  1081. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1082. end;
  1083. function debug_tostr(i: tcgint): string; inline;
  1084. begin
  1085. Result := tostr(i);
  1086. end;
  1087. function debug_hexstr(i: tcgint): string;
  1088. begin
  1089. Result := '0x';
  1090. case i of
  1091. 0..$FF:
  1092. Result := Result + hexstr(i, 2);
  1093. $100..$FFFF:
  1094. Result := Result + hexstr(i, 4);
  1095. $10000..$FFFFFF:
  1096. Result := Result + hexstr(i, 6);
  1097. $1000000..$FFFFFFFF:
  1098. Result := Result + hexstr(i, 8);
  1099. else
  1100. Result := Result + hexstr(i, 16);
  1101. end;
  1102. end;
  1103. function debug_regname(r: TRegister): string; inline;
  1104. begin
  1105. Result := '%' + std_regname(r);
  1106. end;
  1107. { Debug output function - creates a string representation of an operator }
  1108. function debug_operstr(oper: TOper): string;
  1109. begin
  1110. case oper.typ of
  1111. top_const:
  1112. Result := '$' + debug_tostr(oper.val);
  1113. top_reg:
  1114. Result := debug_regname(oper.reg);
  1115. top_ref:
  1116. begin
  1117. if oper.ref^.offset <> 0 then
  1118. Result := debug_tostr(oper.ref^.offset) + '('
  1119. else
  1120. Result := '(';
  1121. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1122. begin
  1123. Result := Result + debug_regname(oper.ref^.base);
  1124. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1125. Result := Result + ',' + debug_regname(oper.ref^.index);
  1126. end
  1127. else
  1128. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1129. Result := Result + debug_regname(oper.ref^.index);
  1130. if (oper.ref^.scalefactor > 1) then
  1131. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1132. else
  1133. Result := Result + ')';
  1134. end;
  1135. else
  1136. Result := '[UNKNOWN]';
  1137. end;
  1138. end;
  1139. function debug_op2str(opcode: tasmop): string; inline;
  1140. begin
  1141. Result := std_op2str[opcode];
  1142. end;
  1143. function debug_opsize2str(opsize: topsize): string; inline;
  1144. begin
  1145. Result := gas_opsize2str[opsize];
  1146. end;
  1147. {$else DEBUG_AOPTCPU}
  1148. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1149. begin
  1150. end;
  1151. function debug_tostr(i: tcgint): string; inline;
  1152. begin
  1153. Result := '';
  1154. end;
  1155. function debug_hexstr(i: tcgint): string; inline;
  1156. begin
  1157. Result := '';
  1158. end;
  1159. function debug_regname(r: TRegister): string; inline;
  1160. begin
  1161. Result := '';
  1162. end;
  1163. function debug_operstr(oper: TOper): string; inline;
  1164. begin
  1165. Result := '';
  1166. end;
  1167. function debug_op2str(opcode: tasmop): string; inline;
  1168. begin
  1169. Result := '';
  1170. end;
  1171. function debug_opsize2str(opsize: topsize): string; inline;
  1172. begin
  1173. Result := '';
  1174. end;
  1175. {$endif DEBUG_AOPTCPU}
  1176. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1177. begin
  1178. {$ifdef x86_64}
  1179. { Always fine on x86-64 }
  1180. Result := True;
  1181. {$else x86_64}
  1182. Result :=
  1183. {$ifdef i8086}
  1184. (current_settings.cputype >= cpu_386) and
  1185. {$endif i8086}
  1186. (
  1187. { Always accept if optimising for size }
  1188. (cs_opt_size in current_settings.optimizerswitches) or
  1189. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1190. (current_settings.optimizecputype >= cpu_Pentium2)
  1191. );
  1192. {$endif x86_64}
  1193. end;
  1194. { Attempts to allocate a volatile integer register for use between p and hp,
  1195. using AUsedRegs for the current register usage information. Returns NR_NO
  1196. if no free register could be found }
  1197. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1198. var
  1199. RegSet: TCPURegisterSet;
  1200. CurrentSuperReg: Integer;
  1201. CurrentReg: TRegister;
  1202. Currentp: tai;
  1203. Breakout: Boolean;
  1204. begin
  1205. Result := NR_NO;
  1206. RegSet :=
  1207. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1208. current_procinfo.saved_regs_int;
  1209. for CurrentSuperReg in RegSet do
  1210. begin
  1211. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1212. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1213. {$if defined(i386) or defined(i8086)}
  1214. { If the target size is 8-bit, make sure we can actually encode it }
  1215. and (
  1216. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1217. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1218. )
  1219. {$endif i386 or i8086}
  1220. then
  1221. begin
  1222. Currentp := p;
  1223. Breakout := False;
  1224. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1225. begin
  1226. case Currentp.typ of
  1227. ait_instruction:
  1228. begin
  1229. if RegInInstruction(CurrentReg, Currentp) then
  1230. begin
  1231. Breakout := True;
  1232. Break;
  1233. end;
  1234. { Cannot allocate across an unconditional jump }
  1235. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1236. Exit;
  1237. end;
  1238. ait_marker:
  1239. { Don't try anything more if a marker is hit }
  1240. Exit;
  1241. ait_regalloc:
  1242. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1243. begin
  1244. Breakout := True;
  1245. Break;
  1246. end;
  1247. else
  1248. ;
  1249. end;
  1250. end;
  1251. if Breakout then
  1252. { Try the next register }
  1253. Continue;
  1254. { We have a free register available }
  1255. Result := CurrentReg;
  1256. if not DontAlloc then
  1257. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1258. Exit;
  1259. end;
  1260. end;
  1261. end;
  1262. { Attempts to allocate a volatile MM register for use between p and hp,
  1263. using AUsedRegs for the current register usage information. Returns NR_NO
  1264. if no free register could be found }
  1265. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1266. var
  1267. RegSet: TCPURegisterSet;
  1268. CurrentSuperReg: Integer;
  1269. CurrentReg: TRegister;
  1270. Currentp: tai;
  1271. Breakout: Boolean;
  1272. begin
  1273. Result := NR_NO;
  1274. RegSet :=
  1275. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1276. current_procinfo.saved_regs_mm;
  1277. for CurrentSuperReg in RegSet do
  1278. begin
  1279. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1280. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1281. begin
  1282. Currentp := p;
  1283. Breakout := False;
  1284. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1285. begin
  1286. case Currentp.typ of
  1287. ait_instruction:
  1288. begin
  1289. if RegInInstruction(CurrentReg, Currentp) then
  1290. begin
  1291. Breakout := True;
  1292. Break;
  1293. end;
  1294. { Cannot allocate across an unconditional jump }
  1295. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1296. Exit;
  1297. end;
  1298. ait_marker:
  1299. { Don't try anything more if a marker is hit }
  1300. Exit;
  1301. ait_regalloc:
  1302. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1303. begin
  1304. Breakout := True;
  1305. Break;
  1306. end;
  1307. else
  1308. ;
  1309. end;
  1310. end;
  1311. if Breakout then
  1312. { Try the next register }
  1313. Continue;
  1314. { We have a free register available }
  1315. Result := CurrentReg;
  1316. if not DontAlloc then
  1317. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1318. Exit;
  1319. end;
  1320. end;
  1321. end;
  1322. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1323. begin
  1324. if not SuperRegistersEqual(reg1,reg2) then
  1325. exit(false);
  1326. if getregtype(reg1)<>R_INTREGISTER then
  1327. exit(true); {because SuperRegisterEqual is true}
  1328. case getsubreg(reg1) of
  1329. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1330. higher, it preserves the high bits, so the new value depends on
  1331. reg2's previous value. In other words, it is equivalent to doing:
  1332. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1333. R_SUBL:
  1334. exit(getsubreg(reg2)=R_SUBL);
  1335. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1336. higher, it actually does a:
  1337. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1338. R_SUBH:
  1339. exit(getsubreg(reg2)=R_SUBH);
  1340. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1341. bits of reg2:
  1342. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1343. R_SUBW:
  1344. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1345. { a write to R_SUBD always overwrites every other subregister,
  1346. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1347. R_SUBD,
  1348. R_SUBQ:
  1349. exit(true);
  1350. else
  1351. internalerror(2017042801);
  1352. end;
  1353. end;
  1354. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1355. begin
  1356. if not SuperRegistersEqual(reg1,reg2) then
  1357. exit(false);
  1358. if getregtype(reg1)<>R_INTREGISTER then
  1359. exit(true); {because SuperRegisterEqual is true}
  1360. case getsubreg(reg1) of
  1361. R_SUBL:
  1362. exit(getsubreg(reg2)<>R_SUBH);
  1363. R_SUBH:
  1364. exit(getsubreg(reg2)<>R_SUBL);
  1365. R_SUBW,
  1366. R_SUBD,
  1367. R_SUBQ:
  1368. exit(true);
  1369. else
  1370. internalerror(2017042802);
  1371. end;
  1372. end;
  1373. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1374. var
  1375. hp1 : tai;
  1376. l : TCGInt;
  1377. begin
  1378. result:=false;
  1379. { changes the code sequence
  1380. shr/sar const1, x
  1381. shl const2, x
  1382. to
  1383. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1384. if GetNextInstruction(p, hp1) and
  1385. MatchInstruction(hp1,A_SHL,[]) and
  1386. (taicpu(p).oper[0]^.typ = top_const) and
  1387. (taicpu(hp1).oper[0]^.typ = top_const) and
  1388. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1389. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1390. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1391. begin
  1392. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1393. not(cs_opt_size in current_settings.optimizerswitches) then
  1394. begin
  1395. { shr/sar const1, %reg
  1396. shl const2, %reg
  1397. with const1 > const2 }
  1398. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1399. taicpu(hp1).opcode := A_AND;
  1400. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1401. case taicpu(p).opsize Of
  1402. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1403. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1404. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1405. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1406. else
  1407. Internalerror(2017050703)
  1408. end;
  1409. end
  1410. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1411. not(cs_opt_size in current_settings.optimizerswitches) then
  1412. begin
  1413. { shr/sar const1, %reg
  1414. shl const2, %reg
  1415. with const1 < const2 }
  1416. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1417. taicpu(p).opcode := A_AND;
  1418. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1419. case taicpu(p).opsize Of
  1420. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1421. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1422. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1423. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1424. else
  1425. Internalerror(2017050702)
  1426. end;
  1427. end
  1428. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1429. begin
  1430. { shr/sar const1, %reg
  1431. shl const2, %reg
  1432. with const1 = const2 }
  1433. taicpu(p).opcode := A_AND;
  1434. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1435. case taicpu(p).opsize Of
  1436. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1437. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1438. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1439. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1440. else
  1441. Internalerror(2017050701)
  1442. end;
  1443. RemoveInstruction(hp1);
  1444. end;
  1445. end;
  1446. end;
  1447. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1448. var
  1449. opsize : topsize;
  1450. hp1, hp2 : tai;
  1451. tmpref : treference;
  1452. ShiftValue : Cardinal;
  1453. BaseValue : TCGInt;
  1454. begin
  1455. result:=false;
  1456. opsize:=taicpu(p).opsize;
  1457. { changes certain "imul const, %reg"'s to lea sequences }
  1458. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1459. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1460. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1461. if (taicpu(p).oper[0]^.val = 1) then
  1462. if (taicpu(p).ops = 2) then
  1463. { remove "imul $1, reg" }
  1464. begin
  1465. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1466. Result := RemoveCurrentP(p);
  1467. end
  1468. else
  1469. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1470. begin
  1471. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1472. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1473. asml.InsertAfter(hp1, p);
  1474. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1475. RemoveCurrentP(p, hp1);
  1476. Result := True;
  1477. end
  1478. else if ((taicpu(p).ops <= 2) or
  1479. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1480. not(cs_opt_size in current_settings.optimizerswitches) and
  1481. (not(GetNextInstruction(p, hp1)) or
  1482. not((tai(hp1).typ = ait_instruction) and
  1483. ((taicpu(hp1).opcode=A_Jcc) and
  1484. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1485. begin
  1486. {
  1487. imul X, reg1, reg2 to
  1488. lea (reg1,reg1,Y), reg2
  1489. shl ZZ,reg2
  1490. imul XX, reg1 to
  1491. lea (reg1,reg1,YY), reg1
  1492. shl ZZ,reg2
  1493. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1494. it does not exist as a separate optimization target in FPC though.
  1495. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1496. at most two zeros
  1497. }
  1498. reference_reset(tmpref,1,[]);
  1499. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1500. begin
  1501. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1502. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1503. TmpRef.base := taicpu(p).oper[1]^.reg;
  1504. TmpRef.index := taicpu(p).oper[1]^.reg;
  1505. if not(BaseValue in [3,5,9]) then
  1506. Internalerror(2018110101);
  1507. TmpRef.ScaleFactor := BaseValue-1;
  1508. if (taicpu(p).ops = 2) then
  1509. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1510. else
  1511. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1512. AsmL.InsertAfter(hp1,p);
  1513. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1514. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1515. RemoveCurrentP(p, hp1);
  1516. if ShiftValue>0 then
  1517. begin
  1518. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1519. AsmL.InsertAfter(hp2,hp1);
  1520. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1521. end;
  1522. Result := True;
  1523. end;
  1524. end;
  1525. end;
  1526. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1527. begin
  1528. Result := False;
  1529. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1530. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1531. begin
  1532. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1533. taicpu(p).opcode := A_MOV;
  1534. Result := True;
  1535. end;
  1536. end;
  1537. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1538. var
  1539. p: taicpu absolute hp; { Implicit typecast }
  1540. i: Integer;
  1541. begin
  1542. Result := False;
  1543. if not assigned(hp) or
  1544. (hp.typ <> ait_instruction) then
  1545. Exit;
  1546. Prefetch(insprop[p.opcode]);
  1547. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1548. with insprop[p.opcode] do
  1549. begin
  1550. case getsubreg(reg) of
  1551. R_SUBW,R_SUBD,R_SUBQ:
  1552. Result:=
  1553. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1554. uncommon flags are checked first }
  1555. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1556. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1557. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1558. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1559. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1560. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1561. R_SUBFLAGCARRY:
  1562. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1563. R_SUBFLAGPARITY:
  1564. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1565. R_SUBFLAGAUXILIARY:
  1566. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1567. R_SUBFLAGZERO:
  1568. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1569. R_SUBFLAGSIGN:
  1570. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1571. R_SUBFLAGOVERFLOW:
  1572. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1573. R_SUBFLAGINTERRUPT:
  1574. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1575. R_SUBFLAGDIRECTION:
  1576. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1577. else
  1578. internalerror(2017050501);
  1579. end;
  1580. exit;
  1581. end;
  1582. { Handle special cases first }
  1583. case p.opcode of
  1584. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1585. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1586. begin
  1587. Result :=
  1588. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1589. (p.oper[1]^.typ = top_reg) and
  1590. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1591. (
  1592. (p.oper[0]^.typ = top_const) or
  1593. (
  1594. (p.oper[0]^.typ = top_reg) and
  1595. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1596. ) or (
  1597. (p.oper[0]^.typ = top_ref) and
  1598. not RegInRef(reg,p.oper[0]^.ref^)
  1599. )
  1600. );
  1601. end;
  1602. A_MUL, A_IMUL:
  1603. Result :=
  1604. (
  1605. (p.ops=3) and { IMUL only }
  1606. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1607. (
  1608. (
  1609. (p.oper[1]^.typ=top_reg) and
  1610. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1611. ) or (
  1612. (p.oper[1]^.typ=top_ref) and
  1613. not RegInRef(reg,p.oper[1]^.ref^)
  1614. )
  1615. )
  1616. ) or (
  1617. (
  1618. (p.ops=1) and
  1619. (
  1620. (
  1621. (
  1622. (p.oper[0]^.typ=top_reg) and
  1623. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1624. )
  1625. ) or (
  1626. (p.oper[0]^.typ=top_ref) and
  1627. not RegInRef(reg,p.oper[0]^.ref^)
  1628. )
  1629. ) and (
  1630. (
  1631. (p.opsize=S_B) and
  1632. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1633. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1634. ) or (
  1635. (p.opsize=S_W) and
  1636. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1637. ) or (
  1638. (p.opsize=S_L) and
  1639. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1640. {$ifdef x86_64}
  1641. ) or (
  1642. (p.opsize=S_Q) and
  1643. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1644. {$endif x86_64}
  1645. )
  1646. )
  1647. )
  1648. );
  1649. A_CBW:
  1650. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1651. {$ifndef x86_64}
  1652. A_LDS:
  1653. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1654. A_LES:
  1655. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1656. {$endif not x86_64}
  1657. A_LFS:
  1658. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1659. A_LGS:
  1660. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1661. A_LSS:
  1662. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1663. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1664. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1665. A_LODSB:
  1666. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1667. A_LODSW:
  1668. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1669. {$ifdef x86_64}
  1670. A_LODSQ:
  1671. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1672. {$endif x86_64}
  1673. A_LODSD:
  1674. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1675. A_FSTSW, A_FNSTSW:
  1676. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1677. else
  1678. begin
  1679. with insprop[p.opcode] do
  1680. begin
  1681. if (
  1682. { xor %reg,%reg etc. is classed as a new value }
  1683. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1684. MatchOpType(p, top_reg, top_reg) and
  1685. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1686. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1687. ) then
  1688. begin
  1689. Result := True;
  1690. Exit;
  1691. end;
  1692. { Make sure the entire register is overwritten }
  1693. if (getregtype(reg) = R_INTREGISTER) then
  1694. begin
  1695. if (p.ops > 0) then
  1696. begin
  1697. if RegInOp(reg, p.oper[0]^) then
  1698. begin
  1699. if (p.oper[0]^.typ = top_ref) then
  1700. begin
  1701. if RegInRef(reg, p.oper[0]^.ref^) then
  1702. begin
  1703. Result := False;
  1704. Exit;
  1705. end;
  1706. end
  1707. else if (p.oper[0]^.typ = top_reg) then
  1708. begin
  1709. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1710. begin
  1711. Result := False;
  1712. Exit;
  1713. end
  1714. else if ([Ch_WOp1]*Ch<>[]) then
  1715. begin
  1716. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1717. Result := True
  1718. else
  1719. begin
  1720. Result := False;
  1721. Exit;
  1722. end;
  1723. end;
  1724. end;
  1725. end;
  1726. if (p.ops > 1) then
  1727. begin
  1728. if RegInOp(reg, p.oper[1]^) then
  1729. begin
  1730. if (p.oper[1]^.typ = top_ref) then
  1731. begin
  1732. if RegInRef(reg, p.oper[1]^.ref^) then
  1733. begin
  1734. Result := False;
  1735. Exit;
  1736. end;
  1737. end
  1738. else if (p.oper[1]^.typ = top_reg) then
  1739. begin
  1740. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1741. begin
  1742. Result := False;
  1743. Exit;
  1744. end
  1745. else if ([Ch_WOp2]*Ch<>[]) then
  1746. begin
  1747. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1748. Result := True
  1749. else
  1750. begin
  1751. Result := False;
  1752. Exit;
  1753. end;
  1754. end;
  1755. end;
  1756. end;
  1757. if (p.ops > 2) then
  1758. begin
  1759. if RegInOp(reg, p.oper[2]^) then
  1760. begin
  1761. if (p.oper[2]^.typ = top_ref) then
  1762. begin
  1763. if RegInRef(reg, p.oper[2]^.ref^) then
  1764. begin
  1765. Result := False;
  1766. Exit;
  1767. end;
  1768. end
  1769. else if (p.oper[2]^.typ = top_reg) then
  1770. begin
  1771. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1772. begin
  1773. Result := False;
  1774. Exit;
  1775. end
  1776. else if ([Ch_WOp3]*Ch<>[]) then
  1777. begin
  1778. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1779. Result := True
  1780. else
  1781. begin
  1782. Result := False;
  1783. Exit;
  1784. end;
  1785. end;
  1786. end;
  1787. end;
  1788. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1789. begin
  1790. if (p.oper[3]^.typ = top_ref) then
  1791. begin
  1792. if RegInRef(reg, p.oper[3]^.ref^) then
  1793. begin
  1794. Result := False;
  1795. Exit;
  1796. end;
  1797. end
  1798. else if (p.oper[3]^.typ = top_reg) then
  1799. begin
  1800. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1801. begin
  1802. Result := False;
  1803. Exit;
  1804. end
  1805. else if ([Ch_WOp4]*Ch<>[]) then
  1806. begin
  1807. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1808. Result := True
  1809. else
  1810. begin
  1811. Result := False;
  1812. Exit;
  1813. end;
  1814. end;
  1815. end;
  1816. end;
  1817. end;
  1818. end;
  1819. end;
  1820. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1821. case getsupreg(reg) of
  1822. RS_EAX:
  1823. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1824. begin
  1825. Result := True;
  1826. Exit;
  1827. end;
  1828. RS_ECX:
  1829. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1830. begin
  1831. Result := True;
  1832. Exit;
  1833. end;
  1834. RS_EDX:
  1835. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1836. begin
  1837. Result := True;
  1838. Exit;
  1839. end;
  1840. RS_EBX:
  1841. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1842. begin
  1843. Result := True;
  1844. Exit;
  1845. end;
  1846. RS_ESP:
  1847. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1848. begin
  1849. Result := True;
  1850. Exit;
  1851. end;
  1852. RS_EBP:
  1853. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1854. begin
  1855. Result := True;
  1856. Exit;
  1857. end;
  1858. RS_ESI:
  1859. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1860. begin
  1861. Result := True;
  1862. Exit;
  1863. end;
  1864. RS_EDI:
  1865. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1866. begin
  1867. Result := True;
  1868. Exit;
  1869. end;
  1870. else
  1871. ;
  1872. end;
  1873. end;
  1874. end;
  1875. end;
  1876. end;
  1877. end;
  1878. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1879. var
  1880. hp2,hp3 : tai;
  1881. begin
  1882. { some x86-64 issue a NOP before the real exit code }
  1883. if MatchInstruction(p,A_NOP,[]) then
  1884. GetNextInstruction(p,p);
  1885. result:=assigned(p) and (p.typ=ait_instruction) and
  1886. ((taicpu(p).opcode = A_RET) or
  1887. ((taicpu(p).opcode=A_LEAVE) and
  1888. GetNextInstruction(p,hp2) and
  1889. MatchInstruction(hp2,A_RET,[S_NO])
  1890. ) or
  1891. (((taicpu(p).opcode=A_LEA) and
  1892. MatchOpType(taicpu(p),top_ref,top_reg) and
  1893. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1894. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1895. ) and
  1896. GetNextInstruction(p,hp2) and
  1897. MatchInstruction(hp2,A_RET,[S_NO])
  1898. ) or
  1899. ((((taicpu(p).opcode=A_MOV) and
  1900. MatchOpType(taicpu(p),top_reg,top_reg) and
  1901. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1902. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1903. ((taicpu(p).opcode=A_LEA) and
  1904. MatchOpType(taicpu(p),top_ref,top_reg) and
  1905. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1906. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1907. )
  1908. ) and
  1909. GetNextInstruction(p,hp2) and
  1910. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1911. MatchOpType(taicpu(hp2),top_reg) and
  1912. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1913. GetNextInstruction(hp2,hp3) and
  1914. MatchInstruction(hp3,A_RET,[S_NO])
  1915. )
  1916. );
  1917. end;
  1918. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1919. begin
  1920. isFoldableArithOp := False;
  1921. case hp1.opcode of
  1922. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1923. isFoldableArithOp :=
  1924. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1925. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1926. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1927. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1928. (taicpu(hp1).oper[1]^.reg = reg);
  1929. A_INC,A_DEC,A_NEG,A_NOT:
  1930. isFoldableArithOp :=
  1931. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1932. (taicpu(hp1).oper[0]^.reg = reg);
  1933. else
  1934. ;
  1935. end;
  1936. end;
  1937. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1938. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1939. var
  1940. hp2: tai;
  1941. begin
  1942. hp2 := p;
  1943. repeat
  1944. hp2 := tai(hp2.previous);
  1945. if assigned(hp2) and
  1946. (hp2.typ = ait_regalloc) and
  1947. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1948. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1949. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1950. begin
  1951. RemoveInstruction(hp2);
  1952. break;
  1953. end;
  1954. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1955. end;
  1956. begin
  1957. case current_procinfo.procdef.returndef.typ of
  1958. arraydef,recorddef,pointerdef,
  1959. stringdef,enumdef,procdef,objectdef,errordef,
  1960. filedef,setdef,procvardef,
  1961. classrefdef,forwarddef:
  1962. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1963. orddef:
  1964. if current_procinfo.procdef.returndef.size <> 0 then
  1965. begin
  1966. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1967. { for int64/qword }
  1968. if current_procinfo.procdef.returndef.size = 8 then
  1969. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1970. end;
  1971. else
  1972. ;
  1973. end;
  1974. end;
  1975. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1976. var
  1977. hp1,hp2 : tai;
  1978. begin
  1979. result:=false;
  1980. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1981. begin
  1982. { vmova* reg1,reg1
  1983. =>
  1984. <nop> }
  1985. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1986. begin
  1987. RemoveCurrentP(p);
  1988. result:=true;
  1989. exit;
  1990. end
  1991. else if GetNextInstruction(p,hp1) then
  1992. begin
  1993. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1994. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1995. begin
  1996. { vmova* reg1,reg2
  1997. vmova* reg2,reg3
  1998. dealloc reg2
  1999. =>
  2000. vmova* reg1,reg3 }
  2001. TransferUsedRegs(TmpUsedRegs);
  2002. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2003. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2004. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2005. begin
  2006. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2007. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2008. RemoveInstruction(hp1);
  2009. result:=true;
  2010. exit;
  2011. end
  2012. { special case:
  2013. vmova* reg1,<op>
  2014. vmova* <op>,reg1
  2015. =>
  2016. vmova* reg1,<op> }
  2017. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2018. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2019. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2020. ) then
  2021. begin
  2022. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2023. RemoveInstruction(hp1);
  2024. result:=true;
  2025. exit;
  2026. end
  2027. end
  2028. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2029. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2030. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2031. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2032. ) and
  2033. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2034. begin
  2035. { vmova* reg1,reg2
  2036. vmovs* reg2,<op>
  2037. dealloc reg2
  2038. =>
  2039. vmovs* reg1,reg3 }
  2040. TransferUsedRegs(TmpUsedRegs);
  2041. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2042. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2043. begin
  2044. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2045. taicpu(p).opcode:=taicpu(hp1).opcode;
  2046. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2047. RemoveInstruction(hp1);
  2048. result:=true;
  2049. exit;
  2050. end
  2051. end;
  2052. end;
  2053. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2054. begin
  2055. if MatchInstruction(hp1,[A_VFMADDPD,
  2056. A_VFMADD132PD,
  2057. A_VFMADD132PS,
  2058. A_VFMADD132SD,
  2059. A_VFMADD132SS,
  2060. A_VFMADD213PD,
  2061. A_VFMADD213PS,
  2062. A_VFMADD213SD,
  2063. A_VFMADD213SS,
  2064. A_VFMADD231PD,
  2065. A_VFMADD231PS,
  2066. A_VFMADD231SD,
  2067. A_VFMADD231SS,
  2068. A_VFMADDSUB132PD,
  2069. A_VFMADDSUB132PS,
  2070. A_VFMADDSUB213PD,
  2071. A_VFMADDSUB213PS,
  2072. A_VFMADDSUB231PD,
  2073. A_VFMADDSUB231PS,
  2074. A_VFMSUB132PD,
  2075. A_VFMSUB132PS,
  2076. A_VFMSUB132SD,
  2077. A_VFMSUB132SS,
  2078. A_VFMSUB213PD,
  2079. A_VFMSUB213PS,
  2080. A_VFMSUB213SD,
  2081. A_VFMSUB213SS,
  2082. A_VFMSUB231PD,
  2083. A_VFMSUB231PS,
  2084. A_VFMSUB231SD,
  2085. A_VFMSUB231SS,
  2086. A_VFMSUBADD132PD,
  2087. A_VFMSUBADD132PS,
  2088. A_VFMSUBADD213PD,
  2089. A_VFMSUBADD213PS,
  2090. A_VFMSUBADD231PD,
  2091. A_VFMSUBADD231PS,
  2092. A_VFNMADD132PD,
  2093. A_VFNMADD132PS,
  2094. A_VFNMADD132SD,
  2095. A_VFNMADD132SS,
  2096. A_VFNMADD213PD,
  2097. A_VFNMADD213PS,
  2098. A_VFNMADD213SD,
  2099. A_VFNMADD213SS,
  2100. A_VFNMADD231PD,
  2101. A_VFNMADD231PS,
  2102. A_VFNMADD231SD,
  2103. A_VFNMADD231SS,
  2104. A_VFNMSUB132PD,
  2105. A_VFNMSUB132PS,
  2106. A_VFNMSUB132SD,
  2107. A_VFNMSUB132SS,
  2108. A_VFNMSUB213PD,
  2109. A_VFNMSUB213PS,
  2110. A_VFNMSUB213SD,
  2111. A_VFNMSUB213SS,
  2112. A_VFNMSUB231PD,
  2113. A_VFNMSUB231PS,
  2114. A_VFNMSUB231SD,
  2115. A_VFNMSUB231SS],[S_NO]) and
  2116. { we mix single and double opperations here because we assume that the compiler
  2117. generates vmovapd only after double operations and vmovaps only after single operations }
  2118. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2119. GetNextInstruction(hp1,hp2) and
  2120. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2121. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2122. begin
  2123. TransferUsedRegs(TmpUsedRegs);
  2124. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2125. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2126. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2127. begin
  2128. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2129. RemoveCurrentP(p);
  2130. RemoveInstruction(hp2);
  2131. end;
  2132. end
  2133. else if (hp1.typ = ait_instruction) and
  2134. GetNextInstruction(hp1, hp2) and
  2135. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2136. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2137. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2138. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2139. (((taicpu(p).opcode=A_MOVAPS) and
  2140. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2141. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2142. ((taicpu(p).opcode=A_MOVAPD) and
  2143. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2144. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2145. ) then
  2146. { change
  2147. movapX reg,reg2
  2148. addsX/subsX/... reg3, reg2
  2149. movapX reg2,reg
  2150. to
  2151. addsX/subsX/... reg3,reg
  2152. }
  2153. begin
  2154. TransferUsedRegs(TmpUsedRegs);
  2155. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2156. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2157. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2158. begin
  2159. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2160. debug_op2str(taicpu(p).opcode)+' '+
  2161. debug_op2str(taicpu(hp1).opcode)+' '+
  2162. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2163. { we cannot eliminate the first move if
  2164. the operations uses the same register for source and dest }
  2165. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2166. { Remember that hp1 is not necessarily the immediate
  2167. next instruction }
  2168. RemoveCurrentP(p);
  2169. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2170. RemoveInstruction(hp2);
  2171. result:=true;
  2172. end;
  2173. end
  2174. else if (hp1.typ = ait_instruction) and
  2175. (((taicpu(p).opcode=A_VMOVAPD) and
  2176. (taicpu(hp1).opcode=A_VCOMISD)) or
  2177. ((taicpu(p).opcode=A_VMOVAPS) and
  2178. ((taicpu(hp1).opcode=A_VCOMISS))
  2179. )
  2180. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2181. { change
  2182. movapX reg,reg1
  2183. vcomisX reg1,reg1
  2184. to
  2185. vcomisX reg,reg
  2186. }
  2187. begin
  2188. TransferUsedRegs(TmpUsedRegs);
  2189. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2190. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2191. begin
  2192. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2193. debug_op2str(taicpu(p).opcode)+' '+
  2194. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2195. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2196. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2197. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2198. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2199. RemoveCurrentP(p);
  2200. result:=true;
  2201. exit;
  2202. end;
  2203. end
  2204. end;
  2205. end;
  2206. end;
  2207. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2208. var
  2209. hp1 : tai;
  2210. begin
  2211. result:=false;
  2212. { replace
  2213. V<Op>X %mreg1,%mreg2,%mreg3
  2214. VMovX %mreg3,%mreg4
  2215. dealloc %mreg3
  2216. by
  2217. V<Op>X %mreg1,%mreg2,%mreg4
  2218. ?
  2219. }
  2220. if GetNextInstruction(p,hp1) and
  2221. { we mix single and double operations here because we assume that the compiler
  2222. generates vmovapd only after double operations and vmovaps only after single operations }
  2223. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2224. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2225. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2226. begin
  2227. TransferUsedRegs(TmpUsedRegs);
  2228. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2229. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2230. begin
  2231. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2232. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2233. RemoveInstruction(hp1);
  2234. result:=true;
  2235. end;
  2236. end;
  2237. end;
  2238. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2239. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2240. begin
  2241. Result := False;
  2242. { For safety reasons, only check for exact register matches }
  2243. { Check base register }
  2244. if (ref.base = AOldReg) then
  2245. begin
  2246. ref.base := ANewReg;
  2247. Result := True;
  2248. end;
  2249. { Check index register }
  2250. if (ref.index = AOldReg) then
  2251. begin
  2252. ref.index := ANewReg;
  2253. Result := True;
  2254. end;
  2255. end;
  2256. { Replaces all references to AOldReg in an operand to ANewReg }
  2257. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2258. var
  2259. OldSupReg, NewSupReg: TSuperRegister;
  2260. OldSubReg, NewSubReg: TSubRegister;
  2261. OldRegType: TRegisterType;
  2262. ThisOper: POper;
  2263. begin
  2264. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2265. Result := False;
  2266. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2267. InternalError(2020011801);
  2268. OldSupReg := getsupreg(AOldReg);
  2269. OldSubReg := getsubreg(AOldReg);
  2270. OldRegType := getregtype(AOldReg);
  2271. NewSupReg := getsupreg(ANewReg);
  2272. NewSubReg := getsubreg(ANewReg);
  2273. if OldRegType <> getregtype(ANewReg) then
  2274. InternalError(2020011802);
  2275. if OldSubReg <> NewSubReg then
  2276. InternalError(2020011803);
  2277. case ThisOper^.typ of
  2278. top_reg:
  2279. if (
  2280. (ThisOper^.reg = AOldReg) or
  2281. (
  2282. (OldRegType = R_INTREGISTER) and
  2283. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2284. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2285. (
  2286. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2287. {$ifndef x86_64}
  2288. and (
  2289. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2290. don't have an 8-bit representation }
  2291. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2292. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2293. )
  2294. {$endif x86_64}
  2295. )
  2296. )
  2297. ) then
  2298. begin
  2299. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2300. Result := True;
  2301. end;
  2302. top_ref:
  2303. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2304. Result := True;
  2305. else
  2306. ;
  2307. end;
  2308. end;
  2309. { Replaces all references to AOldReg in an instruction to ANewReg }
  2310. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2311. const
  2312. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2313. var
  2314. OperIdx: Integer;
  2315. begin
  2316. Result := False;
  2317. for OperIdx := 0 to p.ops - 1 do
  2318. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2319. begin
  2320. { The shift and rotate instructions can only use CL }
  2321. if not (
  2322. (OperIdx = 0) and
  2323. { This second condition just helps to avoid unnecessarily
  2324. calling MatchInstruction for 10 different opcodes }
  2325. (p.oper[0]^.reg = NR_CL) and
  2326. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2327. ) then
  2328. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2329. end
  2330. else if p.oper[OperIdx]^.typ = top_ref then
  2331. { It's okay to replace registers in references that get written to }
  2332. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2333. end;
  2334. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2335. begin
  2336. Result :=
  2337. (ref^.index = NR_NO) and
  2338. (
  2339. {$ifdef x86_64}
  2340. (
  2341. (ref^.base = NR_RIP) and
  2342. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2343. ) or
  2344. {$endif x86_64}
  2345. (ref^.refaddr = addr_full) or
  2346. (ref^.base = NR_STACK_POINTER_REG) or
  2347. (ref^.base = current_procinfo.framepointer)
  2348. );
  2349. end;
  2350. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2351. var
  2352. l: asizeint;
  2353. begin
  2354. Result := False;
  2355. { Should have been checked previously }
  2356. if p.opcode <> A_LEA then
  2357. InternalError(2020072501);
  2358. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2359. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2360. not(cs_opt_size in current_settings.optimizerswitches) then
  2361. exit;
  2362. with p.oper[0]^.ref^ do
  2363. begin
  2364. if (base <> p.oper[1]^.reg) or
  2365. (index <> NR_NO) or
  2366. assigned(symbol) then
  2367. exit;
  2368. l:=offset;
  2369. if (l=1) and UseIncDec then
  2370. begin
  2371. p.opcode:=A_INC;
  2372. p.loadreg(0,p.oper[1]^.reg);
  2373. p.ops:=1;
  2374. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2375. end
  2376. else if (l=-1) and UseIncDec then
  2377. begin
  2378. p.opcode:=A_DEC;
  2379. p.loadreg(0,p.oper[1]^.reg);
  2380. p.ops:=1;
  2381. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2382. end
  2383. else
  2384. begin
  2385. if (l<0) and (l<>-2147483648) then
  2386. begin
  2387. p.opcode:=A_SUB;
  2388. p.loadConst(0,-l);
  2389. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2390. end
  2391. else
  2392. begin
  2393. p.opcode:=A_ADD;
  2394. p.loadConst(0,l);
  2395. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2396. end;
  2397. end;
  2398. end;
  2399. Result := True;
  2400. end;
  2401. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2402. var
  2403. CurrentReg, ReplaceReg: TRegister;
  2404. begin
  2405. Result := False;
  2406. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2407. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2408. case hp.opcode of
  2409. A_FSTSW, A_FNSTSW,
  2410. A_IN, A_INS, A_OUT, A_OUTS,
  2411. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2412. { These routines have explicit operands, but they are restricted in
  2413. what they can be (e.g. IN and OUT can only read from AL, AX or
  2414. EAX. }
  2415. Exit;
  2416. A_IMUL:
  2417. begin
  2418. { The 1-operand version writes to implicit registers
  2419. The 2-operand version reads from the first operator, and reads
  2420. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2421. the 3-operand version reads from a register that it doesn't write to
  2422. }
  2423. case hp.ops of
  2424. 1:
  2425. if (
  2426. (
  2427. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2428. ) or
  2429. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2430. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2431. begin
  2432. Result := True;
  2433. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2434. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2435. end;
  2436. 2:
  2437. { Only modify the first parameter }
  2438. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2439. begin
  2440. Result := True;
  2441. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2442. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2443. end;
  2444. 3:
  2445. { Only modify the second parameter }
  2446. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2447. begin
  2448. Result := True;
  2449. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2450. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2451. end;
  2452. else
  2453. InternalError(2020012901);
  2454. end;
  2455. end;
  2456. else
  2457. if (hp.ops > 0) and
  2458. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2459. begin
  2460. Result := True;
  2461. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2462. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2463. end;
  2464. end;
  2465. end;
  2466. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2467. var
  2468. hp2: tai;
  2469. p_SourceReg, p_TargetReg: TRegister;
  2470. begin
  2471. Result := False;
  2472. { Backward optimisation. If we have:
  2473. func. %reg1,%reg2
  2474. mov %reg2,%reg3
  2475. (dealloc %reg2)
  2476. Change to:
  2477. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2478. Perform similar optimisations with 1, 3 and 4-operand instructions
  2479. that only have one output.
  2480. }
  2481. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2482. begin
  2483. p_SourceReg := taicpu(p).oper[0]^.reg;
  2484. p_TargetReg := taicpu(p).oper[1]^.reg;
  2485. TransferUsedRegs(TmpUsedRegs);
  2486. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2487. GetLastInstruction(p, hp2) and
  2488. (hp2.typ = ait_instruction) and
  2489. { Have to make sure it's an instruction that only reads from
  2490. the first operands and only writes (not reads or modifies) to
  2491. the last one; in essence, a pure function such as BSR, POPCNT
  2492. or ANDN }
  2493. (
  2494. (
  2495. (taicpu(hp2).ops = 1) and
  2496. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2497. ) or
  2498. (
  2499. (taicpu(hp2).ops = 2) and
  2500. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2501. ) or
  2502. (
  2503. (taicpu(hp2).ops = 3) and
  2504. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2505. ) or
  2506. (
  2507. (taicpu(hp2).ops = 4) and
  2508. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2509. )
  2510. ) and
  2511. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2512. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2513. begin
  2514. case taicpu(hp2).opcode of
  2515. A_FSTSW, A_FNSTSW,
  2516. A_IN, A_INS, A_OUT, A_OUTS,
  2517. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2518. { These routines have explicit operands, but they are restricted in
  2519. what they can be (e.g. IN and OUT can only read from AL, AX or
  2520. EAX. }
  2521. ;
  2522. else
  2523. begin
  2524. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2525. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2526. if not RegInInstruction(p_TargetReg, hp2) then
  2527. begin
  2528. { Since we're allocating from an earlier point, we
  2529. need to remove the register from the tracking }
  2530. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2531. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2532. end;
  2533. RemoveCurrentp(p, hp1);
  2534. { If the Func was another MOV instruction, we might get
  2535. "mov %reg,%reg" that doesn't get removed in Pass 2
  2536. otherwise, so deal with it here (also do something
  2537. similar with lea (%reg),%reg}
  2538. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2539. begin
  2540. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2541. if p = hp2 then
  2542. RemoveCurrentp(p)
  2543. else
  2544. RemoveInstruction(hp2);
  2545. end;
  2546. Result := True;
  2547. Exit;
  2548. end;
  2549. end;
  2550. end;
  2551. end;
  2552. end;
  2553. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2554. var
  2555. hp1, hp2, hp3: tai;
  2556. DoOptimisation, TempBool: Boolean;
  2557. {$ifdef x86_64}
  2558. NewConst: TCGInt;
  2559. {$endif x86_64}
  2560. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2561. begin
  2562. if taicpu(hp1).opcode = signed_movop then
  2563. begin
  2564. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2565. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2566. end
  2567. else
  2568. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2569. end;
  2570. function TryConstMerge(var p1, p2: tai): Boolean;
  2571. var
  2572. ThisRef: TReference;
  2573. begin
  2574. Result := False;
  2575. ThisRef := taicpu(p2).oper[1]^.ref^;
  2576. { Only permit writes to the stack, since we can guarantee alignment with that }
  2577. if (ThisRef.index = NR_NO) and
  2578. (
  2579. (ThisRef.base = NR_STACK_POINTER_REG) or
  2580. (ThisRef.base = current_procinfo.framepointer)
  2581. ) then
  2582. begin
  2583. case taicpu(p).opsize of
  2584. S_B:
  2585. begin
  2586. { Word writes must be on a 2-byte boundary }
  2587. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2588. begin
  2589. { Reduce offset of second reference to see if it is sequential with the first }
  2590. Dec(ThisRef.offset, 1);
  2591. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2592. begin
  2593. { Make sure the constants aren't represented as a
  2594. negative number, as these won't merge properly }
  2595. taicpu(p1).opsize := S_W;
  2596. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2597. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2598. RemoveInstruction(p2);
  2599. Result := True;
  2600. end;
  2601. end;
  2602. end;
  2603. S_W:
  2604. begin
  2605. { Longword writes must be on a 4-byte boundary }
  2606. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2607. begin
  2608. { Reduce offset of second reference to see if it is sequential with the first }
  2609. Dec(ThisRef.offset, 2);
  2610. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2611. begin
  2612. { Make sure the constants aren't represented as a
  2613. negative number, as these won't merge properly }
  2614. taicpu(p1).opsize := S_L;
  2615. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2616. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2617. RemoveInstruction(p2);
  2618. Result := True;
  2619. end;
  2620. end;
  2621. end;
  2622. {$ifdef x86_64}
  2623. S_L:
  2624. begin
  2625. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2626. see if the constants can be encoded this way. }
  2627. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2628. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2629. { Quadword writes must be on an 8-byte boundary }
  2630. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2631. begin
  2632. { Reduce offset of second reference to see if it is sequential with the first }
  2633. Dec(ThisRef.offset, 4);
  2634. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2635. begin
  2636. { Make sure the constants aren't represented as a
  2637. negative number, as these won't merge properly }
  2638. taicpu(p1).opsize := S_Q;
  2639. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2640. taicpu(p1).oper[0]^.val := NewConst;
  2641. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2642. RemoveInstruction(p2);
  2643. Result := True;
  2644. end;
  2645. end;
  2646. end;
  2647. {$endif x86_64}
  2648. else
  2649. ;
  2650. end;
  2651. end;
  2652. end;
  2653. var
  2654. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2655. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2656. NewSize: topsize; NewOffset: asizeint;
  2657. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2658. SourceRef, TargetRef: TReference;
  2659. MovAligned, MovUnaligned: TAsmOp;
  2660. ThisRef: TReference;
  2661. JumpTracking: TLinkedList;
  2662. begin
  2663. Result:=false;
  2664. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2665. { remove mov reg1,reg1? }
  2666. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2667. then
  2668. begin
  2669. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2670. { take care of the register (de)allocs following p }
  2671. RemoveCurrentP(p, hp1);
  2672. Result:=true;
  2673. exit;
  2674. end;
  2675. { All the next optimisations require a next instruction }
  2676. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2677. Exit;
  2678. { Prevent compiler warnings }
  2679. p_TargetReg := NR_NO;
  2680. if taicpu(p).oper[1]^.typ = top_reg then
  2681. begin
  2682. { Saves on a large number of dereferences }
  2683. p_TargetReg := taicpu(p).oper[1]^.reg;
  2684. { Look for:
  2685. mov %reg1,%reg2
  2686. ??? %reg2,r/m
  2687. Change to:
  2688. mov %reg1,%reg2
  2689. ??? %reg1,r/m
  2690. }
  2691. if taicpu(p).oper[0]^.typ = top_reg then
  2692. begin
  2693. if RegReadByInstruction(p_TargetReg, hp1) and
  2694. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2695. begin
  2696. { A change has occurred, just not in p }
  2697. Result := True;
  2698. TransferUsedRegs(TmpUsedRegs);
  2699. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2700. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2701. { Just in case something didn't get modified (e.g. an
  2702. implicit register) }
  2703. not RegReadByInstruction(p_TargetReg, hp1) then
  2704. begin
  2705. { We can remove the original MOV }
  2706. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2707. RemoveCurrentp(p, hp1);
  2708. { UsedRegs got updated by RemoveCurrentp }
  2709. Result := True;
  2710. Exit;
  2711. end;
  2712. { If we know a MOV instruction has become a null operation, we might as well
  2713. get rid of it now to save time. }
  2714. if (taicpu(hp1).opcode = A_MOV) and
  2715. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2716. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2717. { Just being a register is enough to confirm it's a null operation }
  2718. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2719. begin
  2720. Result := True;
  2721. { Speed-up to reduce a pipeline stall... if we had something like...
  2722. movl %eax,%edx
  2723. movw %dx,%ax
  2724. ... the second instruction would change to movw %ax,%ax, but
  2725. given that it is now %ax that's active rather than %eax,
  2726. penalties might occur due to a partial register write, so instead,
  2727. change it to a MOVZX instruction when optimising for speed.
  2728. }
  2729. if not (cs_opt_size in current_settings.optimizerswitches) and
  2730. IsMOVZXAcceptable and
  2731. (taicpu(hp1).opsize < taicpu(p).opsize)
  2732. {$ifdef x86_64}
  2733. { operations already implicitly set the upper 64 bits to zero }
  2734. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2735. {$endif x86_64}
  2736. then
  2737. begin
  2738. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2739. case taicpu(p).opsize of
  2740. S_W:
  2741. if taicpu(hp1).opsize = S_B then
  2742. taicpu(hp1).opsize := S_BL
  2743. else
  2744. InternalError(2020012911);
  2745. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2746. case taicpu(hp1).opsize of
  2747. S_B:
  2748. taicpu(hp1).opsize := S_BL;
  2749. S_W:
  2750. taicpu(hp1).opsize := S_WL;
  2751. else
  2752. InternalError(2020012912);
  2753. end;
  2754. else
  2755. InternalError(2020012910);
  2756. end;
  2757. taicpu(hp1).opcode := A_MOVZX;
  2758. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2759. end
  2760. else
  2761. begin
  2762. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2763. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2764. RemoveInstruction(hp1);
  2765. { The instruction after what was hp1 is now the immediate next instruction,
  2766. so we can continue to make optimisations if it's present }
  2767. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2768. Exit;
  2769. hp1 := hp2;
  2770. end;
  2771. end;
  2772. end;
  2773. end;
  2774. end;
  2775. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2776. overwrites the original destination register. e.g.
  2777. movl ###,%reg2d
  2778. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2779. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2780. }
  2781. if (taicpu(p).oper[1]^.typ = top_reg) and
  2782. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2783. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2784. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2785. begin
  2786. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2787. begin
  2788. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2789. case taicpu(p).oper[0]^.typ of
  2790. top_const:
  2791. { We have something like:
  2792. movb $x, %regb
  2793. movzbl %regb,%regd
  2794. Change to:
  2795. movl $x, %regd
  2796. }
  2797. begin
  2798. case taicpu(hp1).opsize of
  2799. S_BW:
  2800. begin
  2801. convert_mov_value(A_MOVSX, $FF);
  2802. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2803. taicpu(p).opsize := S_W;
  2804. end;
  2805. S_BL:
  2806. begin
  2807. convert_mov_value(A_MOVSX, $FF);
  2808. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2809. taicpu(p).opsize := S_L;
  2810. end;
  2811. S_WL:
  2812. begin
  2813. convert_mov_value(A_MOVSX, $FFFF);
  2814. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2815. taicpu(p).opsize := S_L;
  2816. end;
  2817. {$ifdef x86_64}
  2818. S_BQ:
  2819. begin
  2820. convert_mov_value(A_MOVSX, $FF);
  2821. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2822. taicpu(p).opsize := S_Q;
  2823. end;
  2824. S_WQ:
  2825. begin
  2826. convert_mov_value(A_MOVSX, $FFFF);
  2827. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2828. taicpu(p).opsize := S_Q;
  2829. end;
  2830. S_LQ:
  2831. begin
  2832. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2833. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2834. taicpu(p).opsize := S_Q;
  2835. end;
  2836. {$endif x86_64}
  2837. else
  2838. { If hp1 was a MOV instruction, it should have been
  2839. optimised already }
  2840. InternalError(2020021001);
  2841. end;
  2842. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2843. RemoveInstruction(hp1);
  2844. Result := True;
  2845. Exit;
  2846. end;
  2847. top_ref:
  2848. begin
  2849. { We have something like:
  2850. movb mem, %regb
  2851. movzbl %regb,%regd
  2852. Change to:
  2853. movzbl mem, %regd
  2854. }
  2855. ThisRef := taicpu(p).oper[0]^.ref^;
  2856. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2857. begin
  2858. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2859. taicpu(hp1).loadref(0, ThisRef);
  2860. { Make sure any registers in the references are properly tracked }
  2861. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2862. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2863. if (ThisRef.index <> NR_NO) then
  2864. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2865. RemoveCurrentP(p, hp1);
  2866. Result := True;
  2867. Exit;
  2868. end;
  2869. end;
  2870. else
  2871. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2872. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2873. Exit;
  2874. end;
  2875. end
  2876. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2877. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2878. optimised }
  2879. else
  2880. begin
  2881. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2882. RemoveCurrentP(p, hp1);
  2883. Result := True;
  2884. Exit;
  2885. end;
  2886. end;
  2887. if (taicpu(hp1).opcode = A_AND) and
  2888. (taicpu(p).oper[1]^.typ = top_reg) and
  2889. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2890. begin
  2891. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2892. begin
  2893. case taicpu(p).opsize of
  2894. S_L:
  2895. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2896. begin
  2897. { Optimize out:
  2898. mov x, %reg
  2899. and ffffffffh, %reg
  2900. }
  2901. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2902. RemoveInstruction(hp1);
  2903. Result:=true;
  2904. exit;
  2905. end;
  2906. S_Q: { TODO: Confirm if this is even possible }
  2907. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2908. begin
  2909. { Optimize out:
  2910. mov x, %reg
  2911. and ffffffffffffffffh, %reg
  2912. }
  2913. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2914. RemoveInstruction(hp1);
  2915. Result:=true;
  2916. exit;
  2917. end;
  2918. else
  2919. ;
  2920. end;
  2921. if (
  2922. (taicpu(p).oper[0]^.typ=top_reg) or
  2923. (
  2924. (taicpu(p).oper[0]^.typ=top_ref) and
  2925. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2926. )
  2927. ) and
  2928. GetNextInstruction(hp1,hp2) and
  2929. MatchInstruction(hp2,A_TEST,[]) and
  2930. (
  2931. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2932. (
  2933. { If the register being tested is smaller than the one
  2934. that received a bitwise AND, permit it if the constant
  2935. fits into the smaller size }
  2936. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2937. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2938. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2939. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2940. (
  2941. (
  2942. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2943. (taicpu(hp1).oper[0]^.val <= $FF)
  2944. ) or
  2945. (
  2946. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2947. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2948. {$ifdef x86_64}
  2949. ) or
  2950. (
  2951. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2952. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2953. {$endif x86_64}
  2954. )
  2955. )
  2956. )
  2957. ) and
  2958. (
  2959. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2960. MatchOperand(taicpu(hp2).oper[0]^,-1)
  2961. ) and
  2962. GetNextInstruction(hp2,hp3) and
  2963. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2964. (taicpu(hp3).condition in [C_E,C_NE]) then
  2965. begin
  2966. TransferUsedRegs(TmpUsedRegs);
  2967. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2968. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2969. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2970. begin
  2971. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2972. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2973. taicpu(hp1).opcode:=A_TEST;
  2974. { Shrink the TEST instruction down to the smallest possible size }
  2975. case taicpu(hp1).oper[0]^.val of
  2976. 0..255:
  2977. if (taicpu(hp1).opsize <> S_B)
  2978. {$ifndef x86_64}
  2979. and (
  2980. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  2981. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  2982. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  2983. )
  2984. {$endif x86_64}
  2985. then
  2986. begin
  2987. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2988. { Only print debug message if the TEST instruction
  2989. is a different size before and after }
  2990. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  2991. taicpu(hp1).opsize := S_B;
  2992. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2993. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  2994. end;
  2995. 256..65535:
  2996. if (taicpu(hp1).opsize <> S_W) then
  2997. begin
  2998. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2999. { Only print debug message if the TEST instruction
  3000. is a different size before and after }
  3001. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3002. taicpu(hp1).opsize := S_W;
  3003. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3004. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3005. end;
  3006. {$ifdef x86_64}
  3007. 65536..$7FFFFFFF:
  3008. if (taicpu(hp1).opsize <> S_L) then
  3009. begin
  3010. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3011. { Only print debug message if the TEST instruction
  3012. is a different size before and after }
  3013. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3014. taicpu(hp1).opsize := S_L;
  3015. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3016. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3017. end;
  3018. {$endif x86_64}
  3019. else
  3020. ;
  3021. end;
  3022. RemoveInstruction(hp2);
  3023. RemoveCurrentP(p, hp1);
  3024. Result:=true;
  3025. exit;
  3026. end;
  3027. end;
  3028. end
  3029. else if IsMOVZXAcceptable and
  3030. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3031. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3032. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3033. then
  3034. begin
  3035. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3036. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3037. case taicpu(p).opsize of
  3038. S_B:
  3039. if (taicpu(hp1).oper[0]^.val = $ff) then
  3040. begin
  3041. { Convert:
  3042. movb x, %regl movb x, %regl
  3043. andw ffh, %regw andl ffh, %regd
  3044. To:
  3045. movzbw x, %regd movzbl x, %regd
  3046. (Identical registers, just different sizes)
  3047. }
  3048. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3049. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3050. case taicpu(hp1).opsize of
  3051. S_W: NewSize := S_BW;
  3052. S_L: NewSize := S_BL;
  3053. {$ifdef x86_64}
  3054. S_Q: NewSize := S_BQ;
  3055. {$endif x86_64}
  3056. else
  3057. InternalError(2018011510);
  3058. end;
  3059. end
  3060. else
  3061. NewSize := S_NO;
  3062. S_W:
  3063. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3064. begin
  3065. { Convert:
  3066. movw x, %regw
  3067. andl ffffh, %regd
  3068. To:
  3069. movzwl x, %regd
  3070. (Identical registers, just different sizes)
  3071. }
  3072. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3073. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3074. case taicpu(hp1).opsize of
  3075. S_L: NewSize := S_WL;
  3076. {$ifdef x86_64}
  3077. S_Q: NewSize := S_WQ;
  3078. {$endif x86_64}
  3079. else
  3080. InternalError(2018011511);
  3081. end;
  3082. end
  3083. else
  3084. NewSize := S_NO;
  3085. else
  3086. NewSize := S_NO;
  3087. end;
  3088. if NewSize <> S_NO then
  3089. begin
  3090. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3091. { The actual optimization }
  3092. taicpu(p).opcode := A_MOVZX;
  3093. taicpu(p).changeopsize(NewSize);
  3094. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3095. { Safeguard if "and" is followed by a conditional command }
  3096. TransferUsedRegs(TmpUsedRegs);
  3097. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3098. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3099. begin
  3100. { At this point, the "and" command is effectively equivalent to
  3101. "test %reg,%reg". This will be handled separately by the
  3102. Peephole Optimizer. [Kit] }
  3103. DebugMsg(SPeepholeOptimization + PreMessage +
  3104. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3105. end
  3106. else
  3107. begin
  3108. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3109. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3110. RemoveInstruction(hp1);
  3111. end;
  3112. Result := True;
  3113. Exit;
  3114. end;
  3115. end;
  3116. end;
  3117. if (taicpu(hp1).opcode = A_OR) and
  3118. (taicpu(p).oper[1]^.typ = top_reg) and
  3119. MatchOperand(taicpu(p).oper[0]^, 0) and
  3120. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3121. begin
  3122. { mov 0, %reg
  3123. or ###,%reg
  3124. Change to (only if the flags are not used):
  3125. mov ###,%reg
  3126. }
  3127. TransferUsedRegs(TmpUsedRegs);
  3128. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3129. DoOptimisation := True;
  3130. { Even if the flags are used, we might be able to do the optimisation
  3131. if the conditions are predictable }
  3132. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3133. begin
  3134. { Only perform if ### = %reg (the same register) or equal to 0,
  3135. so %reg is guaranteed to still have a value of zero }
  3136. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3137. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3138. begin
  3139. hp2 := hp1;
  3140. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3141. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3142. GetNextInstruction(hp2, hp3) do
  3143. begin
  3144. { Don't continue modifying if the flags state is getting changed }
  3145. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3146. Break;
  3147. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3148. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3149. begin
  3150. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3151. begin
  3152. { Condition is always true }
  3153. case taicpu(hp3).opcode of
  3154. A_Jcc:
  3155. begin
  3156. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3157. { Check for jump shortcuts before we destroy the condition }
  3158. DoJumpOptimizations(hp3, TempBool);
  3159. MakeUnconditional(taicpu(hp3));
  3160. Result := True;
  3161. end;
  3162. A_CMOVcc:
  3163. begin
  3164. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3165. taicpu(hp3).opcode := A_MOV;
  3166. taicpu(hp3).condition := C_None;
  3167. Result := True;
  3168. end;
  3169. A_SETcc:
  3170. begin
  3171. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3172. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3173. taicpu(hp3).opcode := A_MOV;
  3174. taicpu(hp3).ops := 2;
  3175. taicpu(hp3).condition := C_None;
  3176. taicpu(hp3).opsize := S_B;
  3177. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3178. taicpu(hp3).loadconst(0, 1);
  3179. Result := True;
  3180. end;
  3181. else
  3182. InternalError(2021090701);
  3183. end;
  3184. end
  3185. 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
  3186. begin
  3187. { Condition is always false }
  3188. case taicpu(hp3).opcode of
  3189. A_Jcc:
  3190. begin
  3191. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3192. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3193. RemoveInstruction(hp3);
  3194. Result := True;
  3195. { Since hp3 was deleted, hp2 must not be updated }
  3196. Continue;
  3197. end;
  3198. A_CMOVcc:
  3199. begin
  3200. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3201. RemoveInstruction(hp3);
  3202. Result := True;
  3203. { Since hp3 was deleted, hp2 must not be updated }
  3204. Continue;
  3205. end;
  3206. A_SETcc:
  3207. begin
  3208. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3209. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3210. taicpu(hp3).opcode := A_MOV;
  3211. taicpu(hp3).ops := 2;
  3212. taicpu(hp3).condition := C_None;
  3213. taicpu(hp3).opsize := S_B;
  3214. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3215. taicpu(hp3).loadconst(0, 0);
  3216. Result := True;
  3217. end;
  3218. else
  3219. InternalError(2021090702);
  3220. end;
  3221. end
  3222. else
  3223. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3224. DoOptimisation := False;
  3225. end;
  3226. hp2 := hp3;
  3227. end;
  3228. { Flags are still in use - don't optimise }
  3229. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3230. DoOptimisation := False;
  3231. end
  3232. else
  3233. DoOptimisation := False;
  3234. end;
  3235. if DoOptimisation then
  3236. begin
  3237. {$ifdef x86_64}
  3238. { OR only supports 32-bit sign-extended constants for 64-bit
  3239. instructions, so compensate for this if the constant is
  3240. encoded as a value greater than or equal to 2^31 }
  3241. if (taicpu(hp1).opsize = S_Q) and
  3242. (taicpu(hp1).oper[0]^.typ = top_const) and
  3243. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3244. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3245. {$endif x86_64}
  3246. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3247. taicpu(hp1).opcode := A_MOV;
  3248. RemoveCurrentP(p, hp1);
  3249. Result := True;
  3250. Exit;
  3251. end;
  3252. end;
  3253. { Next instruction is also a MOV ? }
  3254. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3255. begin
  3256. if MatchOpType(taicpu(p), top_const, top_ref) and
  3257. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3258. TryConstMerge(p, hp1) then
  3259. begin
  3260. Result := True;
  3261. { In case we have four byte writes in a row, check for 2 more
  3262. right now so we don't have to wait for another iteration of
  3263. pass 1
  3264. }
  3265. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3266. case taicpu(p).opsize of
  3267. S_W:
  3268. begin
  3269. if GetNextInstruction(p, hp1) and
  3270. MatchInstruction(hp1, A_MOV, [S_B]) and
  3271. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3272. GetNextInstruction(hp1, hp2) and
  3273. MatchInstruction(hp2, A_MOV, [S_B]) and
  3274. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3275. { Try to merge the two bytes }
  3276. TryConstMerge(hp1, hp2) then
  3277. { Now try to merge the two words (hp2 will get deleted) }
  3278. TryConstMerge(p, hp1);
  3279. end;
  3280. S_L:
  3281. begin
  3282. { Though this only really benefits x86_64 and not i386, it
  3283. gets a potential optimisation done faster and hence
  3284. reduces the number of times OptPass1MOV is entered }
  3285. if GetNextInstruction(p, hp1) and
  3286. MatchInstruction(hp1, A_MOV, [S_W]) and
  3287. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3288. GetNextInstruction(hp1, hp2) and
  3289. MatchInstruction(hp2, A_MOV, [S_W]) and
  3290. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3291. { Try to merge the two words }
  3292. TryConstMerge(hp1, hp2) then
  3293. { This will always fail on i386, so don't bother
  3294. calling it unless we're doing x86_64 }
  3295. {$ifdef x86_64}
  3296. { Now try to merge the two longwords (hp2 will get deleted) }
  3297. TryConstMerge(p, hp1)
  3298. {$endif x86_64}
  3299. ;
  3300. end;
  3301. else
  3302. ;
  3303. end;
  3304. Exit;
  3305. end;
  3306. if (taicpu(p).oper[1]^.typ = top_reg) and
  3307. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3308. begin
  3309. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3310. TransferUsedRegs(TmpUsedRegs);
  3311. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3312. { we have
  3313. mov x, %treg
  3314. mov %treg, y
  3315. }
  3316. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3317. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3318. { we've got
  3319. mov x, %treg
  3320. mov %treg, y
  3321. with %treg is not used after }
  3322. case taicpu(p).oper[0]^.typ Of
  3323. { top_reg is covered by DeepMOVOpt }
  3324. top_const:
  3325. begin
  3326. { change
  3327. mov const, %treg
  3328. mov %treg, y
  3329. to
  3330. mov const, y
  3331. }
  3332. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3333. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3334. begin
  3335. if taicpu(hp1).oper[1]^.typ=top_reg then
  3336. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3337. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3338. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3339. RemoveInstruction(hp1);
  3340. Result:=true;
  3341. Exit;
  3342. end;
  3343. end;
  3344. top_ref:
  3345. case taicpu(hp1).oper[1]^.typ of
  3346. top_reg:
  3347. begin
  3348. { change
  3349. mov mem, %treg
  3350. mov %treg, %reg
  3351. to
  3352. mov mem, %reg"
  3353. }
  3354. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3355. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3356. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3357. RemoveInstruction(hp1);
  3358. Result:=true;
  3359. Exit;
  3360. end;
  3361. top_ref:
  3362. begin
  3363. {$ifdef x86_64}
  3364. { Look for the following to simplify:
  3365. mov x(mem1), %reg
  3366. mov %reg, y(mem2)
  3367. mov x+8(mem1), %reg
  3368. mov %reg, y+8(mem2)
  3369. Change to:
  3370. movdqu x(mem1), %xmmreg
  3371. movdqu %xmmreg, y(mem2)
  3372. ...but only as long as the memory blocks don't overlap
  3373. }
  3374. SourceRef := taicpu(p).oper[0]^.ref^;
  3375. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3376. if (taicpu(p).opsize = S_Q) and
  3377. GetNextInstruction(hp1, hp2) and
  3378. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3379. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3380. begin
  3381. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3382. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3383. Inc(SourceRef.offset, 8);
  3384. if UseAVX then
  3385. begin
  3386. MovAligned := A_VMOVDQA;
  3387. MovUnaligned := A_VMOVDQU;
  3388. end
  3389. else
  3390. begin
  3391. MovAligned := A_MOVDQA;
  3392. MovUnaligned := A_MOVDQU;
  3393. end;
  3394. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3395. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3396. begin
  3397. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3398. Inc(TargetRef.offset, 8);
  3399. if GetNextInstruction(hp2, hp3) and
  3400. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3401. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3402. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3403. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3404. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3405. begin
  3406. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3407. if NewMMReg <> NR_NO then
  3408. begin
  3409. { Remember that the offsets are 8 ahead }
  3410. if ((SourceRef.offset mod 16) = 8) and
  3411. (
  3412. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3413. (SourceRef.base = current_procinfo.framepointer) or
  3414. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3415. ) then
  3416. taicpu(p).opcode := MovAligned
  3417. else
  3418. taicpu(p).opcode := MovUnaligned;
  3419. taicpu(p).opsize := S_XMM;
  3420. taicpu(p).oper[1]^.reg := NewMMReg;
  3421. if ((TargetRef.offset mod 16) = 8) and
  3422. (
  3423. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3424. (TargetRef.base = current_procinfo.framepointer) or
  3425. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3426. ) then
  3427. taicpu(hp1).opcode := MovAligned
  3428. else
  3429. taicpu(hp1).opcode := MovUnaligned;
  3430. taicpu(hp1).opsize := S_XMM;
  3431. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3432. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3433. RemoveInstruction(hp2);
  3434. RemoveInstruction(hp3);
  3435. Result := True;
  3436. Exit;
  3437. end;
  3438. end;
  3439. end
  3440. else
  3441. begin
  3442. { See if the next references are 8 less rather than 8 greater }
  3443. Dec(SourceRef.offset, 16); { -8 the other way }
  3444. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3445. begin
  3446. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3447. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3448. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3449. GetNextInstruction(hp2, hp3) and
  3450. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3451. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3452. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3453. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3454. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3455. begin
  3456. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3457. if NewMMReg <> NR_NO then
  3458. begin
  3459. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3460. if ((SourceRef.offset mod 16) = 0) and
  3461. (
  3462. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3463. (SourceRef.base = current_procinfo.framepointer) or
  3464. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3465. ) then
  3466. taicpu(hp2).opcode := MovAligned
  3467. else
  3468. taicpu(hp2).opcode := MovUnaligned;
  3469. taicpu(hp2).opsize := S_XMM;
  3470. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3471. if ((TargetRef.offset mod 16) = 0) and
  3472. (
  3473. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3474. (TargetRef.base = current_procinfo.framepointer) or
  3475. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3476. ) then
  3477. taicpu(hp3).opcode := MovAligned
  3478. else
  3479. taicpu(hp3).opcode := MovUnaligned;
  3480. taicpu(hp3).opsize := S_XMM;
  3481. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3482. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3483. RemoveInstruction(hp1);
  3484. RemoveCurrentP(p, hp2);
  3485. Result := True;
  3486. Exit;
  3487. end;
  3488. end;
  3489. end;
  3490. end;
  3491. end;
  3492. {$endif x86_64}
  3493. end;
  3494. else
  3495. { The write target should be a reg or a ref }
  3496. InternalError(2021091601);
  3497. end;
  3498. else
  3499. ;
  3500. end
  3501. else
  3502. { %treg is used afterwards, but all eventualities
  3503. other than the first MOV instruction being a constant
  3504. are covered by DeepMOVOpt, so only check for that }
  3505. if (taicpu(p).oper[0]^.typ = top_const) and
  3506. (
  3507. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3508. not (cs_opt_size in current_settings.optimizerswitches) or
  3509. (taicpu(hp1).opsize = S_B)
  3510. ) and
  3511. (
  3512. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3513. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3514. ) then
  3515. begin
  3516. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3517. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3518. end;
  3519. end;
  3520. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3521. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3522. { mov reg1, mem1 or mov mem1, reg1
  3523. mov mem2, reg2 mov reg2, mem2}
  3524. begin
  3525. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3526. { mov reg1, mem1 or mov mem1, reg1
  3527. mov mem2, reg1 mov reg2, mem1}
  3528. begin
  3529. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3530. { Removes the second statement from
  3531. mov reg1, mem1/reg2
  3532. mov mem1/reg2, reg1 }
  3533. begin
  3534. if taicpu(p).oper[0]^.typ=top_reg then
  3535. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3536. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3537. RemoveInstruction(hp1);
  3538. Result:=true;
  3539. exit;
  3540. end
  3541. else
  3542. begin
  3543. TransferUsedRegs(TmpUsedRegs);
  3544. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3545. if (taicpu(p).oper[1]^.typ = top_ref) and
  3546. { mov reg1, mem1
  3547. mov mem2, reg1 }
  3548. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3549. GetNextInstruction(hp1, hp2) and
  3550. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3551. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3552. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3553. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3554. { change to
  3555. mov reg1, mem1 mov reg1, mem1
  3556. mov mem2, reg1 cmp reg1, mem2
  3557. cmp mem1, reg1
  3558. }
  3559. begin
  3560. RemoveInstruction(hp2);
  3561. taicpu(hp1).opcode := A_CMP;
  3562. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3563. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3564. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3565. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3566. end;
  3567. end;
  3568. end
  3569. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3570. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3571. begin
  3572. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3573. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3574. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3575. end
  3576. else
  3577. begin
  3578. TransferUsedRegs(TmpUsedRegs);
  3579. if GetNextInstruction(hp1, hp2) and
  3580. MatchOpType(taicpu(p),top_ref,top_reg) and
  3581. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3582. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3583. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3584. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3585. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3586. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3587. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3588. { mov mem1, %reg1
  3589. mov %reg1, mem2
  3590. mov mem2, reg2
  3591. to:
  3592. mov mem1, reg2
  3593. mov reg2, mem2}
  3594. begin
  3595. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3596. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3597. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3598. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3599. RemoveInstruction(hp2);
  3600. Result := True;
  3601. end
  3602. {$ifdef i386}
  3603. { this is enabled for i386 only, as the rules to create the reg sets below
  3604. are too complicated for x86-64, so this makes this code too error prone
  3605. on x86-64
  3606. }
  3607. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3608. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3609. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3610. { mov mem1, reg1 mov mem1, reg1
  3611. mov reg1, mem2 mov reg1, mem2
  3612. mov mem2, reg2 mov mem2, reg1
  3613. to: to:
  3614. mov mem1, reg1 mov mem1, reg1
  3615. mov mem1, reg2 mov reg1, mem2
  3616. mov reg1, mem2
  3617. or (if mem1 depends on reg1
  3618. and/or if mem2 depends on reg2)
  3619. to:
  3620. mov mem1, reg1
  3621. mov reg1, mem2
  3622. mov reg1, reg2
  3623. }
  3624. begin
  3625. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3626. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3627. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3628. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3629. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3630. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3631. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3632. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3633. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3634. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3635. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3636. end
  3637. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3638. begin
  3639. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3640. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3641. end
  3642. else
  3643. begin
  3644. RemoveInstruction(hp2);
  3645. end
  3646. {$endif i386}
  3647. ;
  3648. end;
  3649. end
  3650. { movl [mem1],reg1
  3651. movl [mem1],reg2
  3652. to
  3653. movl [mem1],reg1
  3654. movl reg1,reg2
  3655. }
  3656. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3657. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3658. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3659. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3660. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3661. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3662. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3663. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3664. begin
  3665. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3666. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3667. end;
  3668. { movl const1,[mem1]
  3669. movl [mem1],reg1
  3670. to
  3671. movl const1,reg1
  3672. movl reg1,[mem1]
  3673. }
  3674. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3675. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3676. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3677. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3678. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3679. begin
  3680. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3681. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3682. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3683. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3684. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3685. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3686. Result:=true;
  3687. exit;
  3688. end;
  3689. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3690. { Change:
  3691. movl %reg1,%reg2
  3692. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3693. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3694. To:
  3695. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3696. movl x(%reg1),%reg1
  3697. movl %reg1,%regX
  3698. }
  3699. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3700. begin
  3701. p_SourceReg := taicpu(p).oper[0]^.reg;
  3702. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3703. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3704. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3705. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3706. GetNextInstruction(hp1, hp2) and
  3707. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3708. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3709. begin
  3710. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3711. if RegInRef(p_TargetReg, SourceRef) and
  3712. { If %reg1 also appears in the second reference, then it will
  3713. not refer to the same memory block as the first reference }
  3714. not RegInRef(p_SourceReg, SourceRef) then
  3715. begin
  3716. { Check to see if the references match if %reg2 is changed to %reg1 }
  3717. if SourceRef.base = p_TargetReg then
  3718. SourceRef.base := p_SourceReg;
  3719. if SourceRef.index = p_TargetReg then
  3720. SourceRef.index := p_SourceReg;
  3721. { RefsEqual also checks to ensure both references are non-volatile }
  3722. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3723. begin
  3724. taicpu(hp2).loadreg(0, p_SourceReg);
  3725. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3726. Result := True;
  3727. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3728. begin
  3729. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3730. RemoveCurrentP(p, hp1);
  3731. Exit;
  3732. end
  3733. else
  3734. begin
  3735. { Check to see if %reg2 is no longer in use }
  3736. TransferUsedRegs(TmpUsedRegs);
  3737. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3738. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3739. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3740. begin
  3741. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3742. RemoveCurrentP(p, hp1);
  3743. Exit;
  3744. end;
  3745. end;
  3746. { If we reach this point, p and hp1 weren't actually modified,
  3747. so we can do a bit more work on this pass }
  3748. end;
  3749. end;
  3750. end;
  3751. end;
  3752. end;
  3753. {$ifdef x86_64}
  3754. { Change:
  3755. movl %reg1l,%reg2l
  3756. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3757. To:
  3758. movl %reg1l,%reg2l
  3759. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3760. If %reg1 = %reg3, convert to:
  3761. movl %reg1l,%reg2l
  3762. andl %reg1l,%reg1l
  3763. }
  3764. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3765. MatchOpType(taicpu(p), top_reg, top_reg) and
  3766. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3767. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3768. begin
  3769. TransferUsedRegs(TmpUsedRegs);
  3770. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3771. taicpu(hp1).opsize := S_L;
  3772. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3773. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3774. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3775. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3776. begin
  3777. { %reg1 = %reg3 }
  3778. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3779. taicpu(hp1).opcode := A_AND;
  3780. end
  3781. else
  3782. begin
  3783. { %reg1 <> %reg3 }
  3784. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3785. end;
  3786. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3787. begin
  3788. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3789. RemoveCurrentP(p, hp1);
  3790. Result := True;
  3791. Exit;
  3792. end
  3793. else
  3794. begin
  3795. { Initial instruction wasn't actually changed }
  3796. Include(OptsToCheck, aoc_ForceNewIteration);
  3797. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3798. appears below since %reg1 has technically changed }
  3799. if taicpu(hp1).opcode = A_AND then
  3800. Exit;
  3801. end;
  3802. end;
  3803. {$endif x86_64}
  3804. { search further than the next instruction for a mov (as long as it's not a jump) }
  3805. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3806. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3807. (taicpu(p).oper[1]^.typ = top_reg) and
  3808. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3809. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3810. begin
  3811. { we work with hp2 here, so hp1 can be still used later on when
  3812. checking for GetNextInstruction_p }
  3813. hp3 := hp1;
  3814. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3815. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3816. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3817. TransferUsedRegs(TmpUsedRegs);
  3818. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3819. if NotFirstIteration then
  3820. JumpTracking := TLinkedList.Create
  3821. else
  3822. JumpTracking := nil;
  3823. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3824. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3825. (hp2.typ=ait_instruction) do
  3826. begin
  3827. case taicpu(hp2).opcode of
  3828. A_POP:
  3829. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3830. begin
  3831. if not CrossJump and
  3832. not RegUsedBetween(p_TargetReg, p, hp2) then
  3833. begin
  3834. { We can remove the original MOV since the register
  3835. wasn't used between it and its popping from the stack }
  3836. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3837. RemoveCurrentp(p, hp1);
  3838. Result := True;
  3839. JumpTracking.Free;
  3840. Exit;
  3841. end;
  3842. { Can't go any further }
  3843. Break;
  3844. end;
  3845. A_MOV:
  3846. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3847. ((taicpu(p).oper[0]^.typ=top_const) or
  3848. ((taicpu(p).oper[0]^.typ=top_reg) and
  3849. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3850. )
  3851. ) then
  3852. begin
  3853. { we have
  3854. mov x, %treg
  3855. mov %treg, y
  3856. }
  3857. { We don't need to call UpdateUsedRegs for every instruction between
  3858. p and hp2 because the register we're concerned about will not
  3859. become deallocated (otherwise GetNextInstructionUsingReg would
  3860. have stopped at an earlier instruction). [Kit] }
  3861. TempRegUsed :=
  3862. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3863. RegReadByInstruction(p_TargetReg, hp3) or
  3864. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3865. case taicpu(p).oper[0]^.typ Of
  3866. top_reg:
  3867. begin
  3868. { change
  3869. mov %reg, %treg
  3870. mov %treg, y
  3871. to
  3872. mov %reg, y
  3873. }
  3874. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3875. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3876. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3877. begin
  3878. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3879. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3880. if TempRegUsed then
  3881. begin
  3882. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3883. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3884. { Set the start of the next GetNextInstructionUsingRegCond search
  3885. to start at the entry right before hp2 (which is about to be removed) }
  3886. hp3 := tai(hp2.Previous);
  3887. RemoveInstruction(hp2);
  3888. { See if there's more we can optimise }
  3889. Continue;
  3890. end
  3891. else
  3892. begin
  3893. RemoveInstruction(hp2);
  3894. { We can remove the original MOV too }
  3895. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3896. RemoveCurrentP(p, hp1);
  3897. Result:=true;
  3898. JumpTracking.Free;
  3899. Exit;
  3900. end;
  3901. end
  3902. else
  3903. begin
  3904. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3905. taicpu(hp2).loadReg(0, p_SourceReg);
  3906. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3907. { Check to see if the register also appears in the reference }
  3908. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3909. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3910. { Don't remove the first instruction if the temporary register is in use }
  3911. if not TempRegUsed and
  3912. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3913. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3914. begin
  3915. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3916. RemoveCurrentP(p, hp1);
  3917. Result:=true;
  3918. JumpTracking.Free;
  3919. Exit;
  3920. end;
  3921. { No need to set Result to True here. If there's another instruction later
  3922. on that can be optimised, it will be detected when the main Pass 1 loop
  3923. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3924. end;
  3925. end;
  3926. top_const:
  3927. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3928. begin
  3929. { change
  3930. mov const, %treg
  3931. mov %treg, y
  3932. to
  3933. mov const, y
  3934. }
  3935. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3936. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3937. begin
  3938. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3939. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3940. if TempRegUsed then
  3941. begin
  3942. { Don't remove the first instruction if the temporary register is in use }
  3943. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3944. { No need to set Result to True. If there's another instruction later on
  3945. that can be optimised, it will be detected when the main Pass 1 loop
  3946. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3947. end
  3948. else
  3949. begin
  3950. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3951. RemoveCurrentP(p, hp1);
  3952. Result:=true;
  3953. Exit;
  3954. end;
  3955. end;
  3956. end;
  3957. else
  3958. Internalerror(2019103001);
  3959. end;
  3960. end
  3961. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3962. begin
  3963. if not CrossJump and
  3964. not RegUsedBetween(p_TargetReg, p, hp2) and
  3965. not RegReadByInstruction(p_TargetReg, hp2) then
  3966. begin
  3967. { Register is not used before it is overwritten }
  3968. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3969. RemoveCurrentp(p, hp1);
  3970. Result := True;
  3971. Exit;
  3972. end;
  3973. if (taicpu(p).oper[0]^.typ = top_const) and
  3974. (taicpu(hp2).oper[0]^.typ = top_const) then
  3975. begin
  3976. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3977. begin
  3978. { Same value - register hasn't changed }
  3979. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3980. RemoveInstruction(hp2);
  3981. Result := True;
  3982. { See if there's more we can optimise }
  3983. Continue;
  3984. end;
  3985. end;
  3986. {$ifdef x86_64}
  3987. end
  3988. { Change:
  3989. movl %reg1l,%reg2l
  3990. ...
  3991. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3992. To:
  3993. movl %reg1l,%reg2l
  3994. ...
  3995. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3996. If %reg1 = %reg3, convert to:
  3997. movl %reg1l,%reg2l
  3998. ...
  3999. andl %reg1l,%reg1l
  4000. }
  4001. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4002. (taicpu(p).oper[0]^.typ = top_reg) and
  4003. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4004. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4005. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4006. begin
  4007. TempRegUsed :=
  4008. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4009. RegReadByInstruction(p_TargetReg, hp3) or
  4010. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4011. taicpu(hp2).opsize := S_L;
  4012. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4013. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4014. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4015. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4016. begin
  4017. { %reg1 = %reg3 }
  4018. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4019. taicpu(hp2).opcode := A_AND;
  4020. end
  4021. else
  4022. begin
  4023. { %reg1 <> %reg3 }
  4024. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4025. end;
  4026. if not TempRegUsed then
  4027. begin
  4028. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4029. RemoveCurrentP(p, hp1);
  4030. Result := True;
  4031. Exit;
  4032. end
  4033. else
  4034. begin
  4035. { Initial instruction wasn't actually changed }
  4036. Include(OptsToCheck, aoc_ForceNewIteration);
  4037. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4038. appears below since %reg1 has technically changed }
  4039. if taicpu(hp2).opcode = A_AND then
  4040. Break;
  4041. end;
  4042. {$endif x86_64}
  4043. end;
  4044. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4045. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4046. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4047. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4048. begin
  4049. {
  4050. Change from:
  4051. mov ###, %reg
  4052. ...
  4053. movs/z %reg,%reg (Same register, just different sizes)
  4054. To:
  4055. movs/z ###, %reg (Longer version)
  4056. ...
  4057. (remove)
  4058. }
  4059. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4060. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4061. { Keep the first instruction as mov if ### is a constant }
  4062. if taicpu(p).oper[0]^.typ = top_const then
  4063. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4064. else
  4065. begin
  4066. taicpu(p).opcode := taicpu(hp2).opcode;
  4067. taicpu(p).opsize := taicpu(hp2).opsize;
  4068. end;
  4069. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4070. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4071. RemoveInstruction(hp2);
  4072. Result := True;
  4073. JumpTracking.Free;
  4074. Exit;
  4075. end;
  4076. else
  4077. { Move down to the if-block below };
  4078. end;
  4079. { Also catches MOV/S/Z instructions that aren't modified }
  4080. if taicpu(p).oper[0]^.typ = top_reg then
  4081. begin
  4082. p_SourceReg := taicpu(p).oper[0]^.reg;
  4083. if
  4084. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4085. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4086. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4087. begin
  4088. Result := True;
  4089. { Just in case something didn't get modified (e.g. an
  4090. implicit register). Also, if it does read from this
  4091. register, then there's no longer an advantage to
  4092. changing the register on subsequent instructions.}
  4093. if not RegReadByInstruction(p_TargetReg, hp2) then
  4094. begin
  4095. { If a conditional jump was crossed, do not delete
  4096. the original MOV no matter what }
  4097. if not CrossJump and
  4098. { RegEndOfLife returns True if the register is
  4099. deallocated before the next instruction or has
  4100. been loaded with a new value }
  4101. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4102. begin
  4103. { We can remove the original MOV }
  4104. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4105. RemoveCurrentp(p, hp1);
  4106. JumpTracking.Free;
  4107. Result := True;
  4108. Exit;
  4109. end;
  4110. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4111. begin
  4112. { See if there's more we can optimise }
  4113. hp3 := hp2;
  4114. Continue;
  4115. end;
  4116. end;
  4117. end;
  4118. end;
  4119. { Break out of the while loop under normal circumstances }
  4120. Break;
  4121. end;
  4122. JumpTracking.Free;
  4123. end;
  4124. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4125. (taicpu(p).oper[1]^.typ = top_reg) and
  4126. (taicpu(p).opsize = S_L) and
  4127. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4128. (hp2.typ = ait_instruction) and
  4129. (taicpu(hp2).opcode = A_AND) and
  4130. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4131. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4132. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4133. ) then
  4134. begin
  4135. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4136. begin
  4137. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4138. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4139. begin
  4140. { Optimize out:
  4141. mov x, %reg
  4142. and ffffffffh, %reg
  4143. }
  4144. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4145. RemoveInstruction(hp2);
  4146. Result:=true;
  4147. exit;
  4148. end;
  4149. end;
  4150. end;
  4151. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4152. x >= RetOffset) as it doesn't do anything (it writes either to a
  4153. parameter or to the temporary storage room for the function
  4154. result)
  4155. }
  4156. if IsExitCode(hp1) and
  4157. (taicpu(p).oper[1]^.typ = top_ref) and
  4158. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4159. (
  4160. (
  4161. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4162. not (
  4163. assigned(current_procinfo.procdef.funcretsym) and
  4164. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4165. )
  4166. ) or
  4167. { Also discard writes to the stack that are below the base pointer,
  4168. as this is temporary storage rather than a function result on the
  4169. stack, say. }
  4170. (
  4171. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4172. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4173. )
  4174. ) then
  4175. begin
  4176. RemoveCurrentp(p, hp1);
  4177. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4178. RemoveLastDeallocForFuncRes(p);
  4179. Result:=true;
  4180. exit;
  4181. end;
  4182. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4183. begin
  4184. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4185. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4186. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4187. begin
  4188. { change
  4189. mov reg1, mem1
  4190. test/cmp x, mem1
  4191. to
  4192. mov reg1, mem1
  4193. test/cmp x, reg1
  4194. }
  4195. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4196. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4197. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4198. Result := True;
  4199. Exit;
  4200. end;
  4201. if DoMovCmpMemOpt(p, hp1, True) then
  4202. begin
  4203. Result := True;
  4204. Exit;
  4205. end;
  4206. end;
  4207. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4208. { If the flags register is in use, don't change the instruction to an
  4209. ADD otherwise this will scramble the flags. [Kit] }
  4210. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4211. begin
  4212. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4213. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4214. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4215. ) or
  4216. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4217. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4218. )
  4219. ) then
  4220. { mov reg1,ref
  4221. lea reg2,[reg1,reg2]
  4222. to
  4223. add reg2,ref}
  4224. begin
  4225. TransferUsedRegs(TmpUsedRegs);
  4226. { reg1 may not be used afterwards }
  4227. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4228. begin
  4229. Taicpu(hp1).opcode:=A_ADD;
  4230. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4231. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4232. RemoveCurrentp(p, hp1);
  4233. result:=true;
  4234. exit;
  4235. end;
  4236. end;
  4237. { If the LEA instruction can be converted into an arithmetic instruction,
  4238. it may be possible to then fold it in the next optimisation, otherwise
  4239. there's nothing more that can be optimised here. }
  4240. if not ConvertLEA(taicpu(hp1)) then
  4241. Exit;
  4242. end;
  4243. if (taicpu(p).oper[1]^.typ = top_reg) and
  4244. (hp1.typ = ait_instruction) and
  4245. GetNextInstruction(hp1, hp2) and
  4246. MatchInstruction(hp2,A_MOV,[]) and
  4247. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4248. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4249. (
  4250. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4251. {$ifdef x86_64}
  4252. or
  4253. (
  4254. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4255. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4256. )
  4257. {$endif x86_64}
  4258. ) then
  4259. begin
  4260. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4261. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4262. { change movsX/movzX reg/ref, reg2
  4263. add/sub/or/... reg3/$const, reg2
  4264. mov reg2 reg/ref
  4265. dealloc reg2
  4266. to
  4267. add/sub/or/... reg3/$const, reg/ref }
  4268. begin
  4269. TransferUsedRegs(TmpUsedRegs);
  4270. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4271. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4272. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4273. begin
  4274. { by example:
  4275. movswl %si,%eax movswl %si,%eax p
  4276. decl %eax addl %edx,%eax hp1
  4277. movw %ax,%si movw %ax,%si hp2
  4278. ->
  4279. movswl %si,%eax movswl %si,%eax p
  4280. decw %eax addw %edx,%eax hp1
  4281. movw %ax,%si movw %ax,%si hp2
  4282. }
  4283. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4284. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4285. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4286. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4287. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4288. {
  4289. ->
  4290. movswl %si,%eax movswl %si,%eax p
  4291. decw %si addw %dx,%si hp1
  4292. movw %ax,%si movw %ax,%si hp2
  4293. }
  4294. case taicpu(hp1).ops of
  4295. 1:
  4296. begin
  4297. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4298. if taicpu(hp1).oper[0]^.typ=top_reg then
  4299. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4300. end;
  4301. 2:
  4302. begin
  4303. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4304. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4305. (taicpu(hp1).opcode<>A_SHL) and
  4306. (taicpu(hp1).opcode<>A_SHR) and
  4307. (taicpu(hp1).opcode<>A_SAR) then
  4308. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4309. end;
  4310. else
  4311. internalerror(2008042701);
  4312. end;
  4313. {
  4314. ->
  4315. decw %si addw %dx,%si p
  4316. }
  4317. RemoveInstruction(hp2);
  4318. RemoveCurrentP(p, hp1);
  4319. Result:=True;
  4320. Exit;
  4321. end;
  4322. end;
  4323. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4324. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4325. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4326. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4327. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4328. )
  4329. {$ifdef i386}
  4330. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4331. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4332. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4333. {$endif i386}
  4334. then
  4335. { change movsX/movzX reg/ref, reg2
  4336. add/sub/or/... regX/$const, reg2
  4337. mov reg2, reg3
  4338. dealloc reg2
  4339. to
  4340. movsX/movzX reg/ref, reg3
  4341. add/sub/or/... reg3/$const, reg3
  4342. }
  4343. begin
  4344. TransferUsedRegs(TmpUsedRegs);
  4345. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4346. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4347. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4348. begin
  4349. { by example:
  4350. movswl %si,%eax movswl %si,%eax p
  4351. decl %eax addl %edx,%eax hp1
  4352. movw %ax,%si movw %ax,%si hp2
  4353. ->
  4354. movswl %si,%eax movswl %si,%eax p
  4355. decw %eax addw %edx,%eax hp1
  4356. movw %ax,%si movw %ax,%si hp2
  4357. }
  4358. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4359. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4360. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4361. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4362. { limit size of constants as well to avoid assembler errors, but
  4363. check opsize to avoid overflow when left shifting the 1 }
  4364. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4365. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4366. {$ifdef x86_64}
  4367. { Be careful of, for example:
  4368. movl %reg1,%reg2
  4369. addl %reg3,%reg2
  4370. movq %reg2,%reg4
  4371. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4372. }
  4373. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4374. begin
  4375. taicpu(hp2).changeopsize(S_L);
  4376. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4377. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4378. end;
  4379. {$endif x86_64}
  4380. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4381. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4382. if taicpu(p).oper[0]^.typ=top_reg then
  4383. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4384. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4385. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4386. {
  4387. ->
  4388. movswl %si,%eax movswl %si,%eax p
  4389. decw %si addw %dx,%si hp1
  4390. movw %ax,%si movw %ax,%si hp2
  4391. }
  4392. case taicpu(hp1).ops of
  4393. 1:
  4394. begin
  4395. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4396. if taicpu(hp1).oper[0]^.typ=top_reg then
  4397. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4398. end;
  4399. 2:
  4400. begin
  4401. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4402. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4403. (taicpu(hp1).opcode<>A_SHL) and
  4404. (taicpu(hp1).opcode<>A_SHR) and
  4405. (taicpu(hp1).opcode<>A_SAR) then
  4406. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4407. end;
  4408. else
  4409. internalerror(2018111801);
  4410. end;
  4411. {
  4412. ->
  4413. decw %si addw %dx,%si p
  4414. }
  4415. RemoveInstruction(hp2);
  4416. end;
  4417. end;
  4418. end;
  4419. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4420. GetNextInstruction(hp1, hp2) and
  4421. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4422. MatchOperand(Taicpu(p).oper[0]^,0) and
  4423. (Taicpu(p).oper[1]^.typ = top_reg) and
  4424. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4425. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4426. { mov reg1,0
  4427. bts reg1,operand1 --> mov reg1,operand2
  4428. or reg1,operand2 bts reg1,operand1}
  4429. begin
  4430. Taicpu(hp2).opcode:=A_MOV;
  4431. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4432. asml.remove(hp1);
  4433. insertllitem(hp2,hp2.next,hp1);
  4434. RemoveCurrentp(p, hp1);
  4435. Result:=true;
  4436. exit;
  4437. end;
  4438. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4439. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4440. GetNextInstruction(hp1, hp2) and
  4441. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4442. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4443. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4444. { change
  4445. mov reg1,reg2
  4446. sub reg3,reg2
  4447. cmp reg3,reg1
  4448. into
  4449. mov reg1,reg2
  4450. sub reg3,reg2
  4451. }
  4452. begin
  4453. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4454. RemoveInstruction(hp2);
  4455. Result:=true;
  4456. exit;
  4457. end;
  4458. {
  4459. mov ref,reg0
  4460. <op> reg0,reg1
  4461. dealloc reg0
  4462. to
  4463. <op> ref,reg1
  4464. }
  4465. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4466. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4467. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4468. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4469. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4470. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4471. begin
  4472. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4473. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4474. RemoveCurrentp(p, hp1);
  4475. Result:=true;
  4476. exit;
  4477. end;
  4478. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4479. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4480. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4481. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4482. begin
  4483. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4484. {$ifdef x86_64}
  4485. { Convert:
  4486. movq x(ref),%reg64
  4487. shrq y,%reg64
  4488. To:
  4489. movl x+4(ref),%reg32
  4490. shrl y-32,%reg32 (Remove if y = 32)
  4491. }
  4492. if (taicpu(p).opsize = S_Q) and
  4493. (taicpu(hp1).opcode = A_SHR) and
  4494. (taicpu(hp1).oper[0]^.val >= 32) then
  4495. begin
  4496. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4497. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4498. { Convert to 32-bit }
  4499. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4500. taicpu(p).opsize := S_L;
  4501. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4502. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4503. if (taicpu(hp1).oper[0]^.val = 32) then
  4504. begin
  4505. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4506. RemoveInstruction(hp1);
  4507. end
  4508. else
  4509. begin
  4510. { This will potentially open up more arithmetic operations since
  4511. the peephole optimizer now has a big hint that only the lower
  4512. 32 bits are currently in use (and opcodes are smaller in size) }
  4513. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4514. taicpu(hp1).opsize := S_L;
  4515. Dec(taicpu(hp1).oper[0]^.val, 32);
  4516. DebugMsg(SPeepholeOptimization + PreMessage +
  4517. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4518. end;
  4519. Result := True;
  4520. Exit;
  4521. end;
  4522. {$endif x86_64}
  4523. { Convert:
  4524. movl x(ref),%reg
  4525. shrl $24,%reg
  4526. To:
  4527. movzbl x+3(ref),%reg
  4528. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4529. Also accept sar instead of shr, but convert to movsx instead of movzx
  4530. }
  4531. if taicpu(hp1).opcode = A_SHR then
  4532. MovUnaligned := A_MOVZX
  4533. else
  4534. MovUnaligned := A_MOVSX;
  4535. NewSize := S_NO;
  4536. NewOffset := 0;
  4537. case taicpu(p).opsize of
  4538. S_B:
  4539. { No valid combinations };
  4540. S_W:
  4541. if (taicpu(hp1).oper[0]^.val = 8) then
  4542. begin
  4543. NewSize := S_BW;
  4544. NewOffset := 1;
  4545. end;
  4546. S_L:
  4547. case taicpu(hp1).oper[0]^.val of
  4548. 16:
  4549. begin
  4550. NewSize := S_WL;
  4551. NewOffset := 2;
  4552. end;
  4553. 24:
  4554. begin
  4555. NewSize := S_BL;
  4556. NewOffset := 3;
  4557. end;
  4558. else
  4559. ;
  4560. end;
  4561. {$ifdef x86_64}
  4562. S_Q:
  4563. case taicpu(hp1).oper[0]^.val of
  4564. 32:
  4565. begin
  4566. if taicpu(hp1).opcode = A_SAR then
  4567. begin
  4568. { 32-bit to 64-bit is a distinct instruction }
  4569. MovUnaligned := A_MOVSXD;
  4570. NewSize := S_LQ;
  4571. NewOffset := 4;
  4572. end
  4573. else
  4574. { Should have been handled by MovShr2Mov above }
  4575. InternalError(2022081811);
  4576. end;
  4577. 48:
  4578. begin
  4579. NewSize := S_WQ;
  4580. NewOffset := 6;
  4581. end;
  4582. 56:
  4583. begin
  4584. NewSize := S_BQ;
  4585. NewOffset := 7;
  4586. end;
  4587. else
  4588. ;
  4589. end;
  4590. {$endif x86_64}
  4591. else
  4592. InternalError(2022081810);
  4593. end;
  4594. if (NewSize <> S_NO) and
  4595. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4596. begin
  4597. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4598. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4599. debug_op2str(MovUnaligned);
  4600. {$ifdef x86_64}
  4601. if MovUnaligned <> A_MOVSXD then
  4602. { Don't add size suffix for MOVSXD }
  4603. {$endif x86_64}
  4604. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4605. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4606. taicpu(p).opcode := MovUnaligned;
  4607. taicpu(p).opsize := NewSize;
  4608. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4609. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4610. RemoveInstruction(hp1);
  4611. Result := True;
  4612. Exit;
  4613. end;
  4614. end;
  4615. { Backward optimisation shared with OptPass2MOV }
  4616. if FuncMov2Func(p, hp1) then
  4617. begin
  4618. Result := True;
  4619. Exit;
  4620. end;
  4621. end;
  4622. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4623. var
  4624. hp1 : tai;
  4625. begin
  4626. Result:=false;
  4627. if taicpu(p).ops <> 2 then
  4628. exit;
  4629. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4630. GetNextInstruction(p,hp1) then
  4631. begin
  4632. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4633. (taicpu(hp1).ops = 2) then
  4634. begin
  4635. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4636. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4637. { movXX reg1, mem1 or movXX mem1, reg1
  4638. movXX mem2, reg2 movXX reg2, mem2}
  4639. begin
  4640. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4641. { movXX reg1, mem1 or movXX mem1, reg1
  4642. movXX mem2, reg1 movXX reg2, mem1}
  4643. begin
  4644. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4645. begin
  4646. { Removes the second statement from
  4647. movXX reg1, mem1/reg2
  4648. movXX mem1/reg2, reg1
  4649. }
  4650. if taicpu(p).oper[0]^.typ=top_reg then
  4651. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4652. { Removes the second statement from
  4653. movXX mem1/reg1, reg2
  4654. movXX reg2, mem1/reg1
  4655. }
  4656. if (taicpu(p).oper[1]^.typ=top_reg) and
  4657. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4658. begin
  4659. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4660. RemoveInstruction(hp1);
  4661. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4662. Result:=true;
  4663. exit;
  4664. end
  4665. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4666. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4667. begin
  4668. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4669. RemoveInstruction(hp1);
  4670. Result:=true;
  4671. exit;
  4672. end;
  4673. end
  4674. end;
  4675. end;
  4676. end;
  4677. end;
  4678. end;
  4679. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4680. var
  4681. hp1 : tai;
  4682. begin
  4683. result:=false;
  4684. { replace
  4685. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4686. MovX %mreg2,%mreg1
  4687. dealloc %mreg2
  4688. by
  4689. <Op>X %mreg2,%mreg1
  4690. ?
  4691. }
  4692. if GetNextInstruction(p,hp1) and
  4693. { we mix single and double opperations here because we assume that the compiler
  4694. generates vmovapd only after double operations and vmovaps only after single operations }
  4695. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4696. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4697. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4698. (taicpu(p).oper[0]^.typ=top_reg) then
  4699. begin
  4700. TransferUsedRegs(TmpUsedRegs);
  4701. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4702. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4703. begin
  4704. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4705. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4706. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4707. RemoveInstruction(hp1);
  4708. result:=true;
  4709. end;
  4710. end;
  4711. end;
  4712. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4713. var
  4714. hp1, p_label, p_dist, hp1_dist: tai;
  4715. JumpLabel, JumpLabel_dist: TAsmLabel;
  4716. FirstValue, SecondValue: TCGInt;
  4717. TempBool: Boolean;
  4718. begin
  4719. Result := False;
  4720. if (taicpu(p).oper[0]^.typ = top_const) and
  4721. (taicpu(p).oper[0]^.val <> -1) then
  4722. begin
  4723. { Convert unsigned maximum constants to -1 to aid optimisation }
  4724. case taicpu(p).opsize of
  4725. S_B:
  4726. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4727. begin
  4728. taicpu(p).oper[0]^.val := -1;
  4729. Result := True;
  4730. Exit;
  4731. end;
  4732. S_W:
  4733. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4734. begin
  4735. taicpu(p).oper[0]^.val := -1;
  4736. Result := True;
  4737. Exit;
  4738. end;
  4739. S_L:
  4740. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4741. begin
  4742. taicpu(p).oper[0]^.val := -1;
  4743. Result := True;
  4744. Exit;
  4745. end;
  4746. {$ifdef x86_64}
  4747. S_Q:
  4748. { Storing anything greater than $7FFFFFFF is not possible so do
  4749. nothing };
  4750. {$endif x86_64}
  4751. else
  4752. InternalError(2021121001);
  4753. end;
  4754. end;
  4755. if GetNextInstruction(p, hp1) and
  4756. TrySwapMovCmp(p, hp1) then
  4757. begin
  4758. Result := True;
  4759. Exit;
  4760. end;
  4761. if MatchInstruction(hp1, A_Jcc, []) then
  4762. begin
  4763. TempBool := True;
  4764. if DoJumpOptimizations(hp1, TempBool) or
  4765. not TempBool then
  4766. begin
  4767. Result := True;
  4768. if Assigned(hp1) then
  4769. begin
  4770. if (hp1.typ in [ait_align]) then
  4771. SkipAligns(hp1, hp1);
  4772. { CollapseZeroDistJump will be set to the label after the
  4773. jump if it optimises, whether or not it's live or dead }
  4774. if (hp1.typ in [ait_label]) and
  4775. not (tai_label(hp1).labsym.is_used) then
  4776. GetNextInstruction(hp1, hp1);
  4777. end;
  4778. TransferUsedRegs(TmpUsedRegs);
  4779. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4780. if not Assigned(hp1) or
  4781. (
  4782. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4783. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4784. ) then
  4785. begin
  4786. { No more conditional jumps; conditional statement is no longer required }
  4787. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4788. RemoveCurrentP(p);
  4789. end;
  4790. Exit;
  4791. end;
  4792. end;
  4793. { Search for:
  4794. test $x,(reg/ref)
  4795. jne @lbl1
  4796. test $y,(reg/ref) (same register or reference)
  4797. jne @lbl1
  4798. Change to:
  4799. test $(x or y),(reg/ref)
  4800. jne @lbl1
  4801. (Note, this doesn't work with je instead of jne)
  4802. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4803. Also search for:
  4804. test $x,(reg/ref)
  4805. je @lbl1
  4806. test $y,(reg/ref)
  4807. je/jne @lbl2
  4808. If (x or y) = x, then the second jump is deterministic
  4809. }
  4810. if (
  4811. (
  4812. (taicpu(p).oper[0]^.typ = top_const) or
  4813. (
  4814. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4815. (taicpu(p).oper[0]^.typ = top_reg) and
  4816. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4817. )
  4818. ) and
  4819. MatchInstruction(hp1, A_JCC, [])
  4820. ) then
  4821. begin
  4822. if (taicpu(p).oper[0]^.typ = top_reg) and
  4823. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4824. FirstValue := -1
  4825. else
  4826. FirstValue := taicpu(p).oper[0]^.val;
  4827. { If we have several test/jne's in a row, it might be the case that
  4828. the second label doesn't go to the same location, but the one
  4829. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4830. so accommodate for this with a while loop.
  4831. }
  4832. hp1_dist := hp1;
  4833. if GetNextInstruction(hp1, p_dist) and
  4834. (p_dist.typ = ait_instruction) and
  4835. (
  4836. (
  4837. (taicpu(p_dist).opcode = A_TEST) and
  4838. (
  4839. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4840. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4841. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4842. )
  4843. ) or
  4844. (
  4845. { cmp 0,%reg = test %reg,%reg }
  4846. (taicpu(p_dist).opcode = A_CMP) and
  4847. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4848. )
  4849. ) and
  4850. { Make sure the destination operands are actually the same }
  4851. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4852. GetNextInstruction(p_dist, hp1_dist) and
  4853. MatchInstruction(hp1_dist, A_JCC, []) then
  4854. begin
  4855. if
  4856. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4857. (
  4858. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4859. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4860. ) then
  4861. SecondValue := -1
  4862. else
  4863. SecondValue := taicpu(p_dist).oper[0]^.val;
  4864. { If both of the TEST constants are identical, delete the second
  4865. TEST that is unnecessary. }
  4866. if (FirstValue = SecondValue) then
  4867. begin
  4868. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4869. RemoveInstruction(p_dist);
  4870. { Don't let the flags register become deallocated and reallocated between the jumps }
  4871. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4872. Result := True;
  4873. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4874. begin
  4875. { Since the second jump's condition is a subset of the first, we
  4876. know it will never branch because the first jump dominates it.
  4877. Get it out of the way now rather than wait for the jump
  4878. optimisations for a speed boost. }
  4879. if IsJumpToLabel(taicpu(hp1_dist)) then
  4880. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4881. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4882. RemoveInstruction(hp1_dist);
  4883. end
  4884. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4885. begin
  4886. { If the inverse of the first condition is a subset of the second,
  4887. the second one will definitely branch if the first one doesn't }
  4888. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4889. MakeUnconditional(taicpu(hp1_dist));
  4890. RemoveDeadCodeAfterJump(hp1_dist);
  4891. end;
  4892. Exit;
  4893. end;
  4894. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4895. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4896. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4897. then the second jump will never branch, so it can also be
  4898. removed regardless of where it goes }
  4899. (
  4900. (FirstValue = -1) or
  4901. (SecondValue = -1) or
  4902. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4903. ) then
  4904. begin
  4905. { Same jump location... can be a register since nothing's changed }
  4906. { If any of the entries are equivalent to test %reg,%reg, then the
  4907. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4908. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4909. if IsJumpToLabel(taicpu(hp1_dist)) then
  4910. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4911. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4912. RemoveInstruction(hp1_dist);
  4913. { Only remove the second test if no jumps or other conditional instructions follow }
  4914. TransferUsedRegs(TmpUsedRegs);
  4915. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4916. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4917. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4918. RemoveInstruction(p_dist);
  4919. Result := True;
  4920. Exit;
  4921. end;
  4922. end;
  4923. end;
  4924. { Search for:
  4925. test %reg,%reg
  4926. j(c1) @lbl1
  4927. ...
  4928. @lbl:
  4929. test %reg,%reg (same register)
  4930. j(c2) @lbl2
  4931. If c2 is a subset of c1, change to:
  4932. test %reg,%reg
  4933. j(c1) @lbl2
  4934. (@lbl1 may become a dead label as a result)
  4935. }
  4936. if (taicpu(p).oper[1]^.typ = top_reg) and
  4937. (taicpu(p).oper[0]^.typ = top_reg) and
  4938. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4939. MatchInstruction(hp1, A_JCC, []) and
  4940. IsJumpToLabel(taicpu(hp1)) then
  4941. begin
  4942. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4943. p_label := nil;
  4944. if Assigned(JumpLabel) then
  4945. p_label := getlabelwithsym(JumpLabel);
  4946. if Assigned(p_label) and
  4947. GetNextInstruction(p_label, p_dist) and
  4948. MatchInstruction(p_dist, A_TEST, []) and
  4949. { It's fine if the second test uses smaller sub-registers }
  4950. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4951. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4952. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4953. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4954. GetNextInstruction(p_dist, hp1_dist) and
  4955. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4956. begin
  4957. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4958. if JumpLabel = JumpLabel_dist then
  4959. { This is an infinite loop }
  4960. Exit;
  4961. { Best optimisation when the first condition is a subset (or equal) of the second }
  4962. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4963. begin
  4964. { Any registers used here will already be allocated }
  4965. if Assigned(JumpLabel) then
  4966. JumpLabel.DecRefs;
  4967. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4968. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4969. Result := True;
  4970. Exit;
  4971. end;
  4972. end;
  4973. end;
  4974. end;
  4975. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4976. var
  4977. hp1, hp2: tai;
  4978. ActiveReg: TRegister;
  4979. OldOffset: asizeint;
  4980. ThisConst: TCGInt;
  4981. function RegDeallocated: Boolean;
  4982. begin
  4983. TransferUsedRegs(TmpUsedRegs);
  4984. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4985. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4986. end;
  4987. begin
  4988. result:=false;
  4989. hp1 := nil;
  4990. { replace
  4991. addX const,%reg1
  4992. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4993. dealloc %reg1
  4994. by
  4995. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4996. }
  4997. if MatchOpType(taicpu(p),top_const,top_reg) then
  4998. begin
  4999. ActiveReg := taicpu(p).oper[1]^.reg;
  5000. { Ensures the entire register was updated }
  5001. if (taicpu(p).opsize >= S_L) and
  5002. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5003. MatchInstruction(hp1,A_LEA,[]) and
  5004. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5005. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5006. (
  5007. { Cover the case where the register in the reference is also the destination register }
  5008. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5009. (
  5010. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5011. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5012. RegDeallocated
  5013. )
  5014. ) then
  5015. begin
  5016. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5017. {$push}
  5018. {$R-}{$Q-}
  5019. { Explicitly disable overflow checking for these offset calculation
  5020. as those do not matter for the final result }
  5021. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5022. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5023. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5024. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5025. {$pop}
  5026. {$ifdef x86_64}
  5027. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5028. begin
  5029. { Overflow; abort }
  5030. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5031. end
  5032. else
  5033. {$endif x86_64}
  5034. begin
  5035. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5036. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5037. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5038. RemoveCurrentP(p, hp1)
  5039. else
  5040. RemoveCurrentP(p);
  5041. result:=true;
  5042. Exit;
  5043. end;
  5044. end;
  5045. if (
  5046. { Save calling GetNextInstructionUsingReg again }
  5047. Assigned(hp1) or
  5048. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5049. ) and
  5050. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5051. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5052. begin
  5053. if taicpu(hp1).oper[0]^.typ = top_const then
  5054. begin
  5055. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5056. if taicpu(hp1).opcode = A_ADD then
  5057. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5058. else
  5059. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5060. Result := True;
  5061. { Handle any overflows }
  5062. case taicpu(p).opsize of
  5063. S_B:
  5064. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5065. S_W:
  5066. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5067. S_L:
  5068. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5069. {$ifdef x86_64}
  5070. S_Q:
  5071. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5072. { Overflow; abort }
  5073. Result := False
  5074. else
  5075. taicpu(p).oper[0]^.val := ThisConst;
  5076. {$endif x86_64}
  5077. else
  5078. InternalError(2021102610);
  5079. end;
  5080. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5081. if Result then
  5082. begin
  5083. if (taicpu(p).oper[0]^.val < 0) and
  5084. (
  5085. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5086. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5087. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5088. ) then
  5089. begin
  5090. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5091. taicpu(p).opcode := A_SUB;
  5092. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5093. end
  5094. else
  5095. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5096. RemoveInstruction(hp1);
  5097. end;
  5098. end
  5099. else
  5100. begin
  5101. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5102. TransferUsedRegs(TmpUsedRegs);
  5103. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5104. hp2 := p;
  5105. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5106. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5107. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5108. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5109. begin
  5110. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5111. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5112. Asml.Remove(p);
  5113. Asml.InsertAfter(p, hp1);
  5114. p := hp1;
  5115. Result := True;
  5116. Exit;
  5117. end;
  5118. end;
  5119. end;
  5120. if DoArithCombineOpt(p) then
  5121. Result:=true;
  5122. end;
  5123. end;
  5124. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5125. var
  5126. hp1: tai;
  5127. ref: Integer;
  5128. saveref: treference;
  5129. Multiple: TCGInt;
  5130. Adjacent: Boolean;
  5131. begin
  5132. Result:=false;
  5133. { play save and throw an error if LEA uses a seg register prefix,
  5134. this is most likely an error somewhere else }
  5135. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5136. internalerror(2022022001);
  5137. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5138. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5139. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5140. (
  5141. { do not mess with leas accessing the stack pointer
  5142. unless it's a null operation }
  5143. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5144. (
  5145. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5146. (taicpu(p).oper[0]^.ref^.offset = 0)
  5147. )
  5148. ) and
  5149. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5150. begin
  5151. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5152. begin
  5153. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5154. begin
  5155. taicpu(p).opcode := A_MOV;
  5156. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5157. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5158. end
  5159. else
  5160. begin
  5161. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5162. RemoveCurrentP(p);
  5163. end;
  5164. Result:=true;
  5165. exit;
  5166. end
  5167. else if (
  5168. { continue to use lea to adjust the stack pointer,
  5169. it is the recommended way, but only if not optimizing for size }
  5170. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5171. (cs_opt_size in current_settings.optimizerswitches)
  5172. ) and
  5173. { If the flags register is in use, don't change the instruction
  5174. to an ADD otherwise this will scramble the flags. [Kit] }
  5175. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5176. ConvertLEA(taicpu(p)) then
  5177. begin
  5178. Result:=true;
  5179. exit;
  5180. end;
  5181. end;
  5182. { Don't optimise if the stack or frame pointer is the destination register }
  5183. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5184. Exit;
  5185. if GetNextInstruction(p,hp1) and
  5186. (hp1.typ=ait_instruction) then
  5187. begin
  5188. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5189. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5190. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5191. begin
  5192. TransferUsedRegs(TmpUsedRegs);
  5193. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5194. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5195. begin
  5196. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5197. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5198. RemoveInstruction(hp1);
  5199. result:=true;
  5200. exit;
  5201. end;
  5202. end;
  5203. { changes
  5204. lea <ref1>, reg1
  5205. <op> ...,<ref. with reg1>,...
  5206. to
  5207. <op> ...,<ref1>,... }
  5208. { find a reference which uses reg1 }
  5209. 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
  5210. ref:=0
  5211. 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
  5212. ref:=1
  5213. else
  5214. ref:=-1;
  5215. if (ref<>-1) and
  5216. { reg1 must be either the base or the index }
  5217. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5218. begin
  5219. { reg1 can be removed from the reference }
  5220. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5221. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5222. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5223. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5224. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5225. else
  5226. Internalerror(2019111201);
  5227. { check if the can insert all data of the lea into the second instruction }
  5228. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5229. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5230. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5231. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5232. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5233. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5234. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5235. {$ifdef x86_64}
  5236. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5237. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5238. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5239. )
  5240. {$endif x86_64}
  5241. then
  5242. begin
  5243. { reg1 might not used by the second instruction after it is remove from the reference }
  5244. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5245. begin
  5246. TransferUsedRegs(TmpUsedRegs);
  5247. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5248. { reg1 is not updated so it might not be used afterwards }
  5249. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5250. begin
  5251. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5252. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5253. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5254. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5255. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5256. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5257. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5258. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5259. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5260. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5261. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5262. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5263. RemoveCurrentP(p, hp1);
  5264. result:=true;
  5265. exit;
  5266. end
  5267. end;
  5268. end;
  5269. { recover }
  5270. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5271. end;
  5272. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5273. if Adjacent or
  5274. { Check further ahead (up to 2 instructions ahead for -O2) }
  5275. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5276. begin
  5277. { Check common LEA/LEA conditions }
  5278. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5279. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  5280. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5281. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5282. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5283. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5284. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5285. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5286. (
  5287. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5288. calling it (since it calls GetNextInstruction) }
  5289. Adjacent or
  5290. (
  5291. (
  5292. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5293. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5294. ) and (
  5295. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5296. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5297. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5298. )
  5299. )
  5300. ) then
  5301. begin
  5302. { changes
  5303. lea (regX,scale), reg1
  5304. lea offset(reg1,reg1), reg1
  5305. to
  5306. lea offset(regX,scale*2), reg1
  5307. and
  5308. lea (regX,scale1), reg1
  5309. lea offset(reg1,scale2), reg1
  5310. to
  5311. lea offset(regX,scale1*scale2), reg1
  5312. ... so long as the final scale does not exceed 8
  5313. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5314. }
  5315. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5316. (taicpu(p).oper[0]^.ref^.offset = 0) and
  5317. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5318. (
  5319. (
  5320. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5321. ) or (
  5322. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5323. (
  5324. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5325. (
  5326. { RegUsedBetween always returns False if p and hp1 are adjacent }
  5327. Adjacent or
  5328. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  5329. )
  5330. )
  5331. )
  5332. ) and (
  5333. (
  5334. { lea (reg1,scale2), reg1 variant }
  5335. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  5336. (
  5337. (
  5338. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5339. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5340. ) or (
  5341. { lea (regX,regX), reg1 variant }
  5342. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5343. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5344. )
  5345. )
  5346. ) or (
  5347. { lea (reg1,reg1), reg1 variant }
  5348. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5349. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5350. )
  5351. ) then
  5352. begin
  5353. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5354. { Make everything homogeneous to make calculations easier }
  5355. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5356. begin
  5357. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5358. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5359. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5360. else
  5361. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5362. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5363. end;
  5364. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  5365. begin
  5366. { Just to prevent miscalculations }
  5367. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5368. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5369. else
  5370. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  5371. end
  5372. else
  5373. begin
  5374. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5375. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5376. end;
  5377. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5378. RemoveCurrentP(p);
  5379. result:=true;
  5380. exit;
  5381. end
  5382. { changes
  5383. lea offset1(regX), reg1
  5384. lea offset2(reg1), reg1
  5385. to
  5386. lea offset1+offset2(regX), reg1 }
  5387. else if
  5388. (
  5389. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5390. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5391. ) or (
  5392. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5393. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5394. (
  5395. (
  5396. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5397. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5398. ) or (
  5399. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5400. (
  5401. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5402. (
  5403. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5404. (
  5405. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5406. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5407. )
  5408. )
  5409. )
  5410. )
  5411. )
  5412. ) then
  5413. begin
  5414. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5415. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5416. begin
  5417. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5418. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5419. { if the register is used as index and base, we have to increase for base as well
  5420. and adapt base }
  5421. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5422. begin
  5423. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5424. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5425. end;
  5426. end
  5427. else
  5428. begin
  5429. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5430. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5431. end;
  5432. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5433. begin
  5434. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5435. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5436. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5437. end;
  5438. RemoveCurrentP(p);
  5439. result:=true;
  5440. exit;
  5441. end;
  5442. end;
  5443. { Change:
  5444. leal/q $x(%reg1),%reg2
  5445. ...
  5446. shll/q $y,%reg2
  5447. To:
  5448. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5449. }
  5450. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5451. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5452. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5453. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5454. (taicpu(hp1).oper[0]^.val <= 3) then
  5455. begin
  5456. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5457. TransferUsedRegs(TmpUsedRegs);
  5458. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5459. if
  5460. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5461. (this works even if scalefactor is zero) }
  5462. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5463. { Ensure offset doesn't go out of bounds }
  5464. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5465. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5466. (
  5467. (
  5468. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5469. (
  5470. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5471. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5472. (
  5473. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5474. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5475. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5476. )
  5477. )
  5478. ) or (
  5479. (
  5480. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5481. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5482. ) and
  5483. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5484. )
  5485. ) then
  5486. begin
  5487. repeat
  5488. with taicpu(p).oper[0]^.ref^ do
  5489. begin
  5490. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5491. if index = base then
  5492. begin
  5493. if Multiple > 4 then
  5494. { Optimisation will no longer work because resultant
  5495. scale factor will exceed 8 }
  5496. Break;
  5497. base := NR_NO;
  5498. scalefactor := 2;
  5499. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5500. end
  5501. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5502. begin
  5503. { Scale factor only works on the index register }
  5504. index := base;
  5505. base := NR_NO;
  5506. end;
  5507. { For safety }
  5508. if scalefactor <= 1 then
  5509. begin
  5510. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5511. scalefactor := Multiple;
  5512. end
  5513. else
  5514. begin
  5515. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5516. scalefactor := scalefactor * Multiple;
  5517. end;
  5518. offset := offset * Multiple;
  5519. end;
  5520. RemoveInstruction(hp1);
  5521. Result := True;
  5522. Exit;
  5523. { This repeat..until loop exists for the benefit of Break }
  5524. until True;
  5525. end;
  5526. end;
  5527. end;
  5528. end;
  5529. end;
  5530. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5531. var
  5532. hp1 : tai;
  5533. SubInstr: Boolean;
  5534. ThisConst: TCGInt;
  5535. const
  5536. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5537. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5538. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5539. begin
  5540. Result := False;
  5541. if taicpu(p).oper[0]^.typ <> top_const then
  5542. { Should have been confirmed before calling }
  5543. InternalError(2021102601);
  5544. SubInstr := (taicpu(p).opcode = A_SUB);
  5545. if GetLastInstruction(p, hp1) and
  5546. (hp1.typ = ait_instruction) and
  5547. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5548. begin
  5549. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5550. { Bad size }
  5551. InternalError(2022042001);
  5552. case taicpu(hp1).opcode Of
  5553. A_INC:
  5554. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5555. begin
  5556. if SubInstr then
  5557. ThisConst := taicpu(p).oper[0]^.val - 1
  5558. else
  5559. ThisConst := taicpu(p).oper[0]^.val + 1;
  5560. end
  5561. else
  5562. Exit;
  5563. A_DEC:
  5564. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5565. begin
  5566. if SubInstr then
  5567. ThisConst := taicpu(p).oper[0]^.val + 1
  5568. else
  5569. ThisConst := taicpu(p).oper[0]^.val - 1;
  5570. end
  5571. else
  5572. Exit;
  5573. A_SUB:
  5574. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5575. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5576. begin
  5577. if SubInstr then
  5578. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5579. else
  5580. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5581. end
  5582. else
  5583. Exit;
  5584. A_ADD:
  5585. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5586. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5587. begin
  5588. if SubInstr then
  5589. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5590. else
  5591. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5592. end
  5593. else
  5594. Exit;
  5595. else
  5596. Exit;
  5597. end;
  5598. { Check that the values are in range }
  5599. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5600. { Overflow; abort }
  5601. Exit;
  5602. if (ThisConst = 0) then
  5603. begin
  5604. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5605. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5606. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5607. RemoveInstruction(hp1);
  5608. hp1 := tai(p.next);
  5609. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5610. if not GetLastInstruction(hp1, p) then
  5611. p := hp1;
  5612. end
  5613. else
  5614. begin
  5615. if taicpu(hp1).opercnt=1 then
  5616. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5617. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5618. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5619. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5620. else
  5621. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5622. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5623. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5624. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5625. RemoveInstruction(hp1);
  5626. taicpu(p).loadconst(0, ThisConst);
  5627. end;
  5628. Result := True;
  5629. end;
  5630. end;
  5631. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5632. begin
  5633. Result := False;
  5634. if UpdateTmpUsedRegs then
  5635. TransferUsedRegs(TmpUsedRegs);
  5636. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5637. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5638. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5639. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5640. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5641. (
  5642. (
  5643. (taicpu(hp1).opcode = A_TEST)
  5644. ) or (
  5645. (taicpu(hp1).opcode = A_CMP) and
  5646. { A sanity check more than anything }
  5647. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5648. )
  5649. ) then
  5650. begin
  5651. { change
  5652. mov mem, %reg
  5653. cmp/test x, %reg / test %reg,%reg
  5654. (reg deallocated)
  5655. to
  5656. cmp/test x, mem / cmp 0, mem
  5657. }
  5658. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5659. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5660. begin
  5661. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5662. if (taicpu(hp1).opcode = A_TEST) and
  5663. (
  5664. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5665. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5666. ) then
  5667. begin
  5668. taicpu(hp1).opcode := A_CMP;
  5669. taicpu(hp1).loadconst(0, 0);
  5670. end;
  5671. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5672. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5673. RemoveCurrentP(p, hp1);
  5674. Result := True;
  5675. Exit;
  5676. end;
  5677. end;
  5678. end;
  5679. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5680. var
  5681. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5682. ThisReg, SecondReg: TRegister;
  5683. JumpLoc: TAsmLabel;
  5684. NewSize: TOpSize;
  5685. begin
  5686. Result := False;
  5687. {
  5688. Convert:
  5689. j<c> .L1
  5690. .L2:
  5691. mov 1,reg
  5692. jmp .L3 (or ret, although it might not be a RET yet)
  5693. .L1:
  5694. mov 0,reg
  5695. jmp .L3 (or ret)
  5696. ( As long as .L3 <> .L1 or .L2)
  5697. To:
  5698. mov 0,reg
  5699. set<not(c)> reg
  5700. jmp .L3 (or ret)
  5701. .L2:
  5702. mov 1,reg
  5703. jmp .L3 (or ret)
  5704. .L1:
  5705. mov 0,reg
  5706. jmp .L3 (or ret)
  5707. }
  5708. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5709. Exit;
  5710. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5711. if GetNextInstruction(hp_label, hp2) and
  5712. MatchInstruction(hp2,A_MOV,[]) and
  5713. (taicpu(hp2).oper[0]^.typ = top_const) and
  5714. (
  5715. (
  5716. (taicpu(hp2).oper[1]^.typ = top_reg)
  5717. {$ifdef i386}
  5718. { Under i386, ESI, EDI, EBP and ESP
  5719. don't have an 8-bit representation }
  5720. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5721. {$endif i386}
  5722. ) or (
  5723. {$ifdef i386}
  5724. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5725. {$endif i386}
  5726. (taicpu(hp2).opsize = S_B)
  5727. )
  5728. ) and
  5729. GetNextInstruction(hp2, hp3) and
  5730. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5731. (
  5732. (taicpu(hp3).opcode=A_RET) or
  5733. (
  5734. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5735. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5736. )
  5737. ) and
  5738. GetNextInstruction(hp3, hp4) and
  5739. SkipAligns(hp4, hp4) and
  5740. (hp4.typ=ait_label) and
  5741. (tai_label(hp4).labsym=JumpLoc) and
  5742. (
  5743. not (cs_opt_size in current_settings.optimizerswitches) or
  5744. { If the initial jump is the label's only reference, then it will
  5745. become a dead label if the other conditions are met and hence
  5746. remove at least 2 instructions, including a jump }
  5747. (JumpLoc.getrefs = 1)
  5748. ) and
  5749. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5750. that will be optimised out }
  5751. GetNextInstruction(hp4, hp5) and
  5752. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5753. (taicpu(hp5).oper[0]^.typ = top_const) and
  5754. (
  5755. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5756. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5757. ) and
  5758. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5759. GetNextInstruction(hp5,hp6) and
  5760. (
  5761. (hp6.typ<>ait_label) or
  5762. SkipLabels(hp6, hp6)
  5763. ) and
  5764. (hp6.typ=ait_instruction) then
  5765. begin
  5766. { First, let's look at the two jumps that are hp3 and hp6 }
  5767. if not
  5768. (
  5769. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5770. (
  5771. (taicpu(hp6).opcode=A_RET) or
  5772. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5773. )
  5774. ) then
  5775. { If condition is False, then the JMP/RET instructions matched conventionally }
  5776. begin
  5777. { See if one of the jumps can be instantly converted into a RET }
  5778. if (taicpu(hp3).opcode=A_JMP) then
  5779. begin
  5780. { Reuse hp5 }
  5781. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5782. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5783. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5784. Exit;
  5785. if MatchInstruction(hp5, A_RET, []) then
  5786. begin
  5787. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5788. ConvertJumpToRET(hp3, hp5);
  5789. Result := True;
  5790. end
  5791. else
  5792. Exit;
  5793. end;
  5794. if (taicpu(hp6).opcode=A_JMP) then
  5795. begin
  5796. { Reuse hp5 }
  5797. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5798. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5799. Exit;
  5800. if MatchInstruction(hp5, A_RET, []) then
  5801. begin
  5802. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5803. ConvertJumpToRET(hp6, hp5);
  5804. Result := True;
  5805. end
  5806. else
  5807. Exit;
  5808. end;
  5809. if not
  5810. (
  5811. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5812. (
  5813. (taicpu(hp6).opcode=A_RET) or
  5814. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5815. )
  5816. ) then
  5817. { Still doesn't match }
  5818. Exit;
  5819. end;
  5820. if (taicpu(hp2).oper[0]^.val = 1) then
  5821. begin
  5822. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5823. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5824. end
  5825. else
  5826. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5827. if taicpu(hp2).opsize=S_B then
  5828. begin
  5829. if taicpu(hp2).oper[1]^.typ = top_reg then
  5830. begin
  5831. SecondReg := taicpu(hp2).oper[1]^.reg;
  5832. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  5833. end
  5834. else
  5835. begin
  5836. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5837. SecondReg := NR_NO;
  5838. end;
  5839. hp_pos := p;
  5840. hp_allocstart := hp4;
  5841. end
  5842. else
  5843. begin
  5844. { Will be a register because the size can't be S_B otherwise }
  5845. SecondReg:=taicpu(hp2).oper[1]^.reg;
  5846. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  5847. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5848. if (cs_opt_size in current_settings.optimizerswitches) then
  5849. begin
  5850. { Favour using MOVZX when optimising for size }
  5851. case taicpu(hp2).opsize of
  5852. S_W:
  5853. NewSize := S_BW;
  5854. S_L:
  5855. NewSize := S_BL;
  5856. {$ifdef x86_64}
  5857. S_Q:
  5858. begin
  5859. NewSize := S_BL;
  5860. { Will implicitly zero-extend to 64-bit }
  5861. setsubreg(SecondReg, R_SUBD);
  5862. end;
  5863. {$endif x86_64}
  5864. else
  5865. InternalError(2022101301);
  5866. end;
  5867. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  5868. { Inserting it right before p will guarantee that the flags are also tracked }
  5869. Asml.InsertBefore(hp5, p);
  5870. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  5871. hp_pos := hp5;
  5872. hp_allocstart := hp4;
  5873. end
  5874. else
  5875. begin
  5876. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  5877. { Inserting it right before p will guarantee that the flags are also tracked }
  5878. Asml.InsertBefore(hp5, p);
  5879. hp_pos := p;
  5880. hp_allocstart := hp5;
  5881. end;
  5882. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  5883. end;
  5884. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  5885. taicpu(hp4).condition := taicpu(p).condition;
  5886. asml.InsertBefore(hp4, hp_pos);
  5887. if taicpu(hp3).is_jmp then
  5888. begin
  5889. JumpLoc.decrefs;
  5890. MakeUnconditional(taicpu(p));
  5891. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5892. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5893. end
  5894. else
  5895. ConvertJumpToRET(p, hp3);
  5896. if SecondReg <> NR_NO then
  5897. { Ensure the destination register is allocated over this region }
  5898. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  5899. if (JumpLoc.getrefs = 0) then
  5900. RemoveDeadCodeAfterJump(hp3);
  5901. Result:=true;
  5902. exit;
  5903. end;
  5904. end;
  5905. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5906. var
  5907. hp1, hp2: tai;
  5908. ActiveReg: TRegister;
  5909. OldOffset: asizeint;
  5910. ThisConst: TCGInt;
  5911. function RegDeallocated: Boolean;
  5912. begin
  5913. TransferUsedRegs(TmpUsedRegs);
  5914. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5915. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5916. end;
  5917. begin
  5918. Result:=false;
  5919. hp1 := nil;
  5920. { replace
  5921. subX const,%reg1
  5922. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5923. dealloc %reg1
  5924. by
  5925. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5926. }
  5927. if MatchOpType(taicpu(p),top_const,top_reg) then
  5928. begin
  5929. ActiveReg := taicpu(p).oper[1]^.reg;
  5930. { Ensures the entire register was updated }
  5931. if (taicpu(p).opsize >= S_L) and
  5932. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5933. MatchInstruction(hp1,A_LEA,[]) and
  5934. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5935. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5936. (
  5937. { Cover the case where the register in the reference is also the destination register }
  5938. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5939. (
  5940. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5941. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5942. RegDeallocated
  5943. )
  5944. ) then
  5945. begin
  5946. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5947. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5948. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5949. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5950. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5951. {$ifdef x86_64}
  5952. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5953. begin
  5954. { Overflow; abort }
  5955. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5956. end
  5957. else
  5958. {$endif x86_64}
  5959. begin
  5960. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5961. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5962. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5963. RemoveCurrentP(p, hp1)
  5964. else
  5965. RemoveCurrentP(p);
  5966. result:=true;
  5967. Exit;
  5968. end;
  5969. end;
  5970. if (
  5971. { Save calling GetNextInstructionUsingReg again }
  5972. Assigned(hp1) or
  5973. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5974. ) and
  5975. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5976. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5977. begin
  5978. if taicpu(hp1).oper[0]^.typ = top_const then
  5979. begin
  5980. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5981. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5982. Result := True;
  5983. { Handle any overflows }
  5984. case taicpu(p).opsize of
  5985. S_B:
  5986. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5987. S_W:
  5988. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5989. S_L:
  5990. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5991. {$ifdef x86_64}
  5992. S_Q:
  5993. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5994. { Overflow; abort }
  5995. Result := False
  5996. else
  5997. taicpu(p).oper[0]^.val := ThisConst;
  5998. {$endif x86_64}
  5999. else
  6000. InternalError(2021102611);
  6001. end;
  6002. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6003. if Result then
  6004. begin
  6005. if (taicpu(p).oper[0]^.val < 0) and
  6006. (
  6007. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6008. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6009. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6010. ) then
  6011. begin
  6012. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6013. taicpu(p).opcode := A_SUB;
  6014. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6015. end
  6016. else
  6017. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6018. RemoveInstruction(hp1);
  6019. end;
  6020. end
  6021. else
  6022. begin
  6023. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6024. TransferUsedRegs(TmpUsedRegs);
  6025. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6026. hp2 := p;
  6027. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6028. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6029. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6030. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6031. begin
  6032. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6033. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6034. Asml.Remove(p);
  6035. Asml.InsertAfter(p, hp1);
  6036. p := hp1;
  6037. Result := True;
  6038. Exit;
  6039. end;
  6040. end;
  6041. end;
  6042. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6043. { * change "sub/add const1, reg" or "dec reg" followed by
  6044. "sub const2, reg" to one "sub ..., reg" }
  6045. {$ifdef i386}
  6046. if (taicpu(p).oper[0]^.val = 2) and
  6047. (ActiveReg = NR_ESP) and
  6048. { Don't do the sub/push optimization if the sub }
  6049. { comes from setting up the stack frame (JM) }
  6050. (not(GetLastInstruction(p,hp1)) or
  6051. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6052. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6053. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6054. begin
  6055. hp1 := tai(p.next);
  6056. while Assigned(hp1) and
  6057. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6058. not RegReadByInstruction(NR_ESP,hp1) and
  6059. not RegModifiedByInstruction(NR_ESP,hp1) do
  6060. hp1 := tai(hp1.next);
  6061. if Assigned(hp1) and
  6062. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6063. begin
  6064. taicpu(hp1).changeopsize(S_L);
  6065. if taicpu(hp1).oper[0]^.typ=top_reg then
  6066. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6067. hp1 := tai(p.next);
  6068. RemoveCurrentp(p, hp1);
  6069. Result:=true;
  6070. exit;
  6071. end;
  6072. end;
  6073. {$endif i386}
  6074. if DoArithCombineOpt(p) then
  6075. Result:=true;
  6076. end;
  6077. end;
  6078. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6079. var
  6080. TmpBool1,TmpBool2 : Boolean;
  6081. tmpref : treference;
  6082. hp1,hp2: tai;
  6083. mask, shiftval: tcgint;
  6084. begin
  6085. Result:=false;
  6086. { All these optimisations work on "shl/sal const,%reg" }
  6087. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6088. Exit;
  6089. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6090. (taicpu(p).oper[0]^.val <= 3) then
  6091. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6092. begin
  6093. { should we check the next instruction? }
  6094. TmpBool1 := True;
  6095. { have we found an add/sub which could be
  6096. integrated in the lea? }
  6097. TmpBool2 := False;
  6098. reference_reset(tmpref,2,[]);
  6099. TmpRef.index := taicpu(p).oper[1]^.reg;
  6100. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6101. while TmpBool1 and
  6102. GetNextInstruction(p, hp1) and
  6103. (tai(hp1).typ = ait_instruction) and
  6104. ((((taicpu(hp1).opcode = A_ADD) or
  6105. (taicpu(hp1).opcode = A_SUB)) and
  6106. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6107. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6108. (((taicpu(hp1).opcode = A_INC) or
  6109. (taicpu(hp1).opcode = A_DEC)) and
  6110. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6111. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6112. ((taicpu(hp1).opcode = A_LEA) and
  6113. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6114. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6115. (not GetNextInstruction(hp1,hp2) or
  6116. not instrReadsFlags(hp2)) Do
  6117. begin
  6118. TmpBool1 := False;
  6119. if taicpu(hp1).opcode=A_LEA then
  6120. begin
  6121. if (TmpRef.base = NR_NO) and
  6122. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6123. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6124. { Segment register isn't a concern here }
  6125. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6126. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6127. begin
  6128. TmpBool1 := True;
  6129. TmpBool2 := True;
  6130. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6131. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6132. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6133. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6134. RemoveInstruction(hp1);
  6135. end
  6136. end
  6137. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6138. begin
  6139. TmpBool1 := True;
  6140. TmpBool2 := True;
  6141. case taicpu(hp1).opcode of
  6142. A_ADD:
  6143. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6144. A_SUB:
  6145. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6146. else
  6147. internalerror(2019050536);
  6148. end;
  6149. RemoveInstruction(hp1);
  6150. end
  6151. else
  6152. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6153. (((taicpu(hp1).opcode = A_ADD) and
  6154. (TmpRef.base = NR_NO)) or
  6155. (taicpu(hp1).opcode = A_INC) or
  6156. (taicpu(hp1).opcode = A_DEC)) then
  6157. begin
  6158. TmpBool1 := True;
  6159. TmpBool2 := True;
  6160. case taicpu(hp1).opcode of
  6161. A_ADD:
  6162. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6163. A_INC:
  6164. inc(TmpRef.offset);
  6165. A_DEC:
  6166. dec(TmpRef.offset);
  6167. else
  6168. internalerror(2019050535);
  6169. end;
  6170. RemoveInstruction(hp1);
  6171. end;
  6172. end;
  6173. if TmpBool2
  6174. {$ifndef x86_64}
  6175. or
  6176. ((current_settings.optimizecputype < cpu_Pentium2) and
  6177. (taicpu(p).oper[0]^.val <= 3) and
  6178. not(cs_opt_size in current_settings.optimizerswitches))
  6179. {$endif x86_64}
  6180. then
  6181. begin
  6182. if not(TmpBool2) and
  6183. (taicpu(p).oper[0]^.val=1) then
  6184. begin
  6185. taicpu(p).opcode := A_ADD;
  6186. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6187. end
  6188. else
  6189. begin
  6190. taicpu(p).opcode := A_LEA;
  6191. taicpu(p).loadref(0, TmpRef);
  6192. end;
  6193. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6194. Result := True;
  6195. end;
  6196. end
  6197. {$ifndef x86_64}
  6198. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6199. begin
  6200. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6201. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6202. (unlike shl, which is only Tairable in the U pipe) }
  6203. if taicpu(p).oper[0]^.val=1 then
  6204. begin
  6205. taicpu(p).opcode := A_ADD;
  6206. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6207. Result := True;
  6208. end
  6209. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6210. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6211. else if (taicpu(p).opsize = S_L) and
  6212. (taicpu(p).oper[0]^.val<= 3) then
  6213. begin
  6214. reference_reset(tmpref,2,[]);
  6215. TmpRef.index := taicpu(p).oper[1]^.reg;
  6216. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6217. taicpu(p).opcode := A_LEA;
  6218. taicpu(p).loadref(0, TmpRef);
  6219. Result := True;
  6220. end;
  6221. end
  6222. {$endif x86_64}
  6223. else if
  6224. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6225. (
  6226. (
  6227. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6228. SetAndTest(hp1, hp2)
  6229. {$ifdef x86_64}
  6230. ) or
  6231. (
  6232. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6233. GetNextInstruction(hp1, hp2) and
  6234. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6235. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6236. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6237. {$endif x86_64}
  6238. )
  6239. ) and
  6240. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6241. begin
  6242. { Change:
  6243. shl x, %reg1
  6244. mov -(1<<x), %reg2
  6245. and %reg2, %reg1
  6246. Or:
  6247. shl x, %reg1
  6248. and -(1<<x), %reg1
  6249. To just:
  6250. shl x, %reg1
  6251. Since the and operation only zeroes bits that are already zero from the shl operation
  6252. }
  6253. case taicpu(p).oper[0]^.val of
  6254. 8:
  6255. mask:=$FFFFFFFFFFFFFF00;
  6256. 16:
  6257. mask:=$FFFFFFFFFFFF0000;
  6258. 32:
  6259. mask:=$FFFFFFFF00000000;
  6260. 63:
  6261. { Constant pre-calculated to prevent overflow errors with Int64 }
  6262. mask:=$8000000000000000;
  6263. else
  6264. begin
  6265. if taicpu(p).oper[0]^.val >= 64 then
  6266. { Shouldn't happen realistically, since the register
  6267. is guaranteed to be set to zero at this point }
  6268. mask := 0
  6269. else
  6270. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6271. end;
  6272. end;
  6273. if taicpu(hp1).oper[0]^.val = mask then
  6274. begin
  6275. { Everything checks out, perform the optimisation, as long as
  6276. the FLAGS register isn't being used}
  6277. TransferUsedRegs(TmpUsedRegs);
  6278. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6279. {$ifdef x86_64}
  6280. if (hp1 <> hp2) then
  6281. begin
  6282. { "shl/mov/and" version }
  6283. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6284. { Don't do the optimisation if the FLAGS register is in use }
  6285. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6286. begin
  6287. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6288. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6289. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6290. begin
  6291. RemoveInstruction(hp1);
  6292. Result := True;
  6293. end;
  6294. { Only set Result to True if the 'mov' instruction was removed }
  6295. RemoveInstruction(hp2);
  6296. end;
  6297. end
  6298. else
  6299. {$endif x86_64}
  6300. begin
  6301. { "shl/and" version }
  6302. { Don't do the optimisation if the FLAGS register is in use }
  6303. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6304. begin
  6305. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6306. RemoveInstruction(hp1);
  6307. Result := True;
  6308. end;
  6309. end;
  6310. Exit;
  6311. end
  6312. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6313. begin
  6314. { Even if the mask doesn't allow for its removal, we might be
  6315. able to optimise the mask for the "shl/and" version, which
  6316. may permit other peephole optimisations }
  6317. {$ifdef DEBUG_AOPTCPU}
  6318. mask := taicpu(hp1).oper[0]^.val and mask;
  6319. if taicpu(hp1).oper[0]^.val <> mask then
  6320. begin
  6321. DebugMsg(
  6322. SPeepholeOptimization +
  6323. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6324. ' to $' + debug_tostr(mask) +
  6325. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6326. taicpu(hp1).oper[0]^.val := mask;
  6327. end;
  6328. {$else DEBUG_AOPTCPU}
  6329. { If debugging is off, just set the operand even if it's the same }
  6330. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6331. {$endif DEBUG_AOPTCPU}
  6332. end;
  6333. end;
  6334. {
  6335. change
  6336. shl/sal const,reg
  6337. <op> ...(...,reg,1),...
  6338. into
  6339. <op> ...(...,reg,1 shl const),...
  6340. if const in 1..3
  6341. }
  6342. if MatchOpType(taicpu(p), top_const, top_reg) and
  6343. (taicpu(p).oper[0]^.val in [1..3]) and
  6344. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6345. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6346. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6347. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6348. MatchOpType(taicpu(hp1),top_ref))
  6349. ) and
  6350. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6351. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6352. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6353. begin
  6354. TransferUsedRegs(TmpUsedRegs);
  6355. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6356. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6357. begin
  6358. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6359. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6360. RemoveCurrentP(p);
  6361. Result:=true;
  6362. exit;
  6363. end;
  6364. end;
  6365. if MatchOpType(taicpu(p), top_const, top_reg) and
  6366. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6367. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6368. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6369. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6370. begin
  6371. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6372. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6373. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6374. {$ifdef x86_64}
  6375. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6376. {$endif x86_64}
  6377. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6378. begin
  6379. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6380. taicpu(hp1).opcode:=A_MOV;
  6381. taicpu(hp1).oper[0]^.val:=0;
  6382. end
  6383. else
  6384. begin
  6385. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6386. taicpu(hp1).oper[0]^.val:=shiftval;
  6387. end;
  6388. RemoveCurrentP(p);
  6389. Result:=true;
  6390. exit;
  6391. end;
  6392. end;
  6393. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6394. begin
  6395. case shr_size of
  6396. S_B:
  6397. { No valid combinations }
  6398. Result := False;
  6399. S_W:
  6400. Result := (Shift >= 8) and (movz_size = S_BW);
  6401. S_L:
  6402. Result :=
  6403. (Shift >= 24) { Any opsize is valid for this shift } or
  6404. ((Shift >= 16) and (movz_size = S_WL));
  6405. {$ifdef x86_64}
  6406. S_Q:
  6407. Result :=
  6408. (Shift >= 56) { Any opsize is valid for this shift } or
  6409. ((Shift >= 48) and (movz_size = S_WL));
  6410. {$endif x86_64}
  6411. else
  6412. InternalError(2022081510);
  6413. end;
  6414. end;
  6415. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6416. var
  6417. hp1, hp2: tai;
  6418. Shift: TCGInt;
  6419. LimitSize: Topsize;
  6420. DoNotMerge: Boolean;
  6421. begin
  6422. Result := False;
  6423. { All these optimisations work on "shr const,%reg" }
  6424. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6425. Exit;
  6426. DoNotMerge := False;
  6427. Shift := taicpu(p).oper[0]^.val;
  6428. LimitSize := taicpu(p).opsize;
  6429. hp1 := p;
  6430. repeat
  6431. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6432. Exit;
  6433. case taicpu(hp1).opcode of
  6434. A_TEST, A_CMP, A_Jcc:
  6435. { Skip over conditional jumps and relevant comparisons }
  6436. Continue;
  6437. A_MOVZX:
  6438. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6439. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6440. begin
  6441. { Since the original register is being read as is, subsequent
  6442. SHRs must not be merged at this point }
  6443. DoNotMerge := True;
  6444. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6445. begin
  6446. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6447. begin
  6448. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6449. taicpu(hp1).opcode := A_MOV;
  6450. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6451. case taicpu(hp1).opsize of
  6452. S_BW:
  6453. taicpu(hp1).opsize := S_W;
  6454. S_BL, S_WL:
  6455. taicpu(hp1).opsize := S_L;
  6456. else
  6457. InternalError(2022081503);
  6458. end;
  6459. { p itself hasn't changed, so no need to set Result to True }
  6460. Include(OptsToCheck, aoc_ForceNewIteration);
  6461. { See if there's anything afterwards that can be
  6462. optimised, since the input register hasn't changed }
  6463. Continue;
  6464. end;
  6465. { NOTE: If the MOVZX instruction reads and writes the same
  6466. register, defer this to the post-peephole optimisation stage }
  6467. Exit;
  6468. end;
  6469. end;
  6470. A_SHL, A_SAL, A_SHR:
  6471. if (taicpu(hp1).opsize <= LimitSize) and
  6472. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6473. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6474. begin
  6475. { Make sure the sizes don't exceed the register size limit
  6476. (measured by the shift value falling below the limit) }
  6477. if taicpu(hp1).opsize < LimitSize then
  6478. LimitSize := taicpu(hp1).opsize;
  6479. if taicpu(hp1).opcode = A_SHR then
  6480. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6481. else
  6482. begin
  6483. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6484. DoNotMerge := True;
  6485. end;
  6486. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6487. Exit;
  6488. { Since we've established that the combined shift is within
  6489. limits, we can actually combine the adjacent SHR
  6490. instructions even if they're different sizes }
  6491. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6492. begin
  6493. hp2 := tai(hp1.Previous);
  6494. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6495. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6496. RemoveInstruction(hp1);
  6497. hp1 := hp2;
  6498. { Though p has changed, only the constant has, and its
  6499. effects can still be detected on the next iteration of
  6500. the repeat..until loop }
  6501. Include(OptsToCheck, aoc_ForceNewIteration);
  6502. end;
  6503. { Move onto the next instruction }
  6504. Continue;
  6505. end;
  6506. else
  6507. ;
  6508. end;
  6509. Break;
  6510. until False;
  6511. end;
  6512. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6513. var
  6514. CurrentRef: TReference;
  6515. FullReg: TRegister;
  6516. hp1, hp2: tai;
  6517. begin
  6518. Result := False;
  6519. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6520. Exit;
  6521. { We assume you've checked if the operand is actually a reference by
  6522. this point. If it isn't, you'll most likely get an access violation }
  6523. CurrentRef := first_mov.oper[1]^.ref^;
  6524. { Memory must be aligned }
  6525. if (CurrentRef.offset mod 4) <> 0 then
  6526. Exit;
  6527. Inc(CurrentRef.offset);
  6528. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6529. if MatchOperand(second_mov.oper[0]^, 0) and
  6530. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6531. GetNextInstruction(second_mov, hp1) and
  6532. (hp1.typ = ait_instruction) and
  6533. (taicpu(hp1).opcode = A_MOV) and
  6534. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6535. (taicpu(hp1).oper[0]^.val = 0) then
  6536. begin
  6537. Inc(CurrentRef.offset);
  6538. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6539. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6540. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6541. begin
  6542. case taicpu(hp1).opsize of
  6543. S_B:
  6544. if GetNextInstruction(hp1, hp2) and
  6545. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6546. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6547. (taicpu(hp2).oper[0]^.val = 0) then
  6548. begin
  6549. Inc(CurrentRef.offset);
  6550. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6551. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6552. (taicpu(hp2).opsize = S_B) then
  6553. begin
  6554. RemoveInstruction(hp1);
  6555. RemoveInstruction(hp2);
  6556. first_mov.opsize := S_L;
  6557. if first_mov.oper[0]^.typ = top_reg then
  6558. begin
  6559. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6560. { Reuse second_mov as a MOVZX instruction }
  6561. second_mov.opcode := A_MOVZX;
  6562. second_mov.opsize := S_BL;
  6563. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6564. second_mov.loadreg(1, FullReg);
  6565. first_mov.oper[0]^.reg := FullReg;
  6566. asml.Remove(second_mov);
  6567. asml.InsertBefore(second_mov, first_mov);
  6568. end
  6569. else
  6570. { It's a value }
  6571. begin
  6572. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6573. RemoveInstruction(second_mov);
  6574. end;
  6575. Result := True;
  6576. Exit;
  6577. end;
  6578. end;
  6579. S_W:
  6580. begin
  6581. RemoveInstruction(hp1);
  6582. first_mov.opsize := S_L;
  6583. if first_mov.oper[0]^.typ = top_reg then
  6584. begin
  6585. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6586. { Reuse second_mov as a MOVZX instruction }
  6587. second_mov.opcode := A_MOVZX;
  6588. second_mov.opsize := S_BL;
  6589. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6590. second_mov.loadreg(1, FullReg);
  6591. first_mov.oper[0]^.reg := FullReg;
  6592. asml.Remove(second_mov);
  6593. asml.InsertBefore(second_mov, first_mov);
  6594. end
  6595. else
  6596. { It's a value }
  6597. begin
  6598. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6599. RemoveInstruction(second_mov);
  6600. end;
  6601. Result := True;
  6602. Exit;
  6603. end;
  6604. else
  6605. ;
  6606. end;
  6607. end;
  6608. end;
  6609. end;
  6610. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6611. { returns true if a "continue" should be done after this optimization }
  6612. var
  6613. hp1, hp2, hp3: tai;
  6614. begin
  6615. Result := false;
  6616. hp3 := nil;
  6617. if MatchOpType(taicpu(p),top_ref) and
  6618. GetNextInstruction(p, hp1) and
  6619. (hp1.typ = ait_instruction) and
  6620. (((taicpu(hp1).opcode = A_FLD) and
  6621. (taicpu(p).opcode = A_FSTP)) or
  6622. ((taicpu(p).opcode = A_FISTP) and
  6623. (taicpu(hp1).opcode = A_FILD))) and
  6624. MatchOpType(taicpu(hp1),top_ref) and
  6625. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6626. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6627. begin
  6628. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6629. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6630. GetNextInstruction(hp1, hp2) and
  6631. (((hp2.typ = ait_instruction) and
  6632. IsExitCode(hp2) and
  6633. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6634. not(assigned(current_procinfo.procdef.funcretsym) and
  6635. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6636. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6637. { fstp <temp>
  6638. fld <temp>
  6639. <dealloc> <temp>
  6640. }
  6641. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6642. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6643. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6644. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6645. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6646. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6647. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6648. )
  6649. )
  6650. ) then
  6651. begin
  6652. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6653. RemoveInstruction(hp1);
  6654. RemoveCurrentP(p, hp2);
  6655. { first case: exit code }
  6656. if hp2.typ = ait_instruction then
  6657. RemoveLastDeallocForFuncRes(p);
  6658. Result := true;
  6659. end
  6660. else
  6661. { we can do this only in fast math mode as fstp is rounding ...
  6662. ... still disabled as it breaks the compiler and/or rtl }
  6663. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6664. { ... or if another fstp equal to the first one follows }
  6665. GetNextInstruction(hp1,hp2) and
  6666. (hp2.typ = ait_instruction) and
  6667. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6668. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6669. begin
  6670. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6671. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6672. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6673. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6674. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6675. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6676. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6677. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6678. ) then
  6679. begin
  6680. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6681. RemoveCurrentP(p,hp2);
  6682. RemoveInstruction(hp1);
  6683. Result := true;
  6684. end
  6685. else if { fst can't store an extended/comp value }
  6686. (taicpu(p).opsize <> S_FX) and
  6687. (taicpu(p).opsize <> S_IQ) then
  6688. begin
  6689. if (taicpu(p).opcode = A_FSTP) then
  6690. taicpu(p).opcode := A_FST
  6691. else
  6692. taicpu(p).opcode := A_FIST;
  6693. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6694. RemoveInstruction(hp1);
  6695. Result := true;
  6696. end;
  6697. end;
  6698. end;
  6699. end;
  6700. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6701. var
  6702. hp1, hp2, hp3: tai;
  6703. begin
  6704. result:=false;
  6705. if MatchOpType(taicpu(p),top_reg) and
  6706. GetNextInstruction(p, hp1) and
  6707. (hp1.typ = Ait_Instruction) and
  6708. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6709. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6710. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6711. { change to
  6712. fld reg fxxx reg,st
  6713. fxxxp st, st1 (hp1)
  6714. Remark: non commutative operations must be reversed!
  6715. }
  6716. begin
  6717. case taicpu(hp1).opcode Of
  6718. A_FMULP,A_FADDP,
  6719. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6720. begin
  6721. case taicpu(hp1).opcode Of
  6722. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6723. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6724. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6725. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6726. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6727. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6728. else
  6729. internalerror(2019050534);
  6730. end;
  6731. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6732. taicpu(hp1).oper[1]^.reg := NR_ST;
  6733. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6734. RemoveCurrentP(p, hp1);
  6735. Result:=true;
  6736. exit;
  6737. end;
  6738. else
  6739. ;
  6740. end;
  6741. end
  6742. else
  6743. if MatchOpType(taicpu(p),top_ref) and
  6744. GetNextInstruction(p, hp2) and
  6745. (hp2.typ = Ait_Instruction) and
  6746. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6747. (taicpu(p).opsize in [S_FS, S_FL]) and
  6748. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6749. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6750. if GetLastInstruction(p, hp1) and
  6751. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6752. MatchOpType(taicpu(hp1),top_ref) and
  6753. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6754. if ((taicpu(hp2).opcode = A_FMULP) or
  6755. (taicpu(hp2).opcode = A_FADDP)) then
  6756. { change to
  6757. fld/fst mem1 (hp1) fld/fst mem1
  6758. fld mem1 (p) fadd/
  6759. faddp/ fmul st, st
  6760. fmulp st, st1 (hp2) }
  6761. begin
  6762. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6763. RemoveCurrentP(p, hp1);
  6764. if (taicpu(hp2).opcode = A_FADDP) then
  6765. taicpu(hp2).opcode := A_FADD
  6766. else
  6767. taicpu(hp2).opcode := A_FMUL;
  6768. taicpu(hp2).oper[1]^.reg := NR_ST;
  6769. end
  6770. else
  6771. { change to
  6772. fld/fst mem1 (hp1) fld/fst mem1
  6773. fld mem1 (p) fld st
  6774. }
  6775. begin
  6776. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6777. taicpu(p).changeopsize(S_FL);
  6778. taicpu(p).loadreg(0,NR_ST);
  6779. end
  6780. else
  6781. begin
  6782. case taicpu(hp2).opcode Of
  6783. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6784. { change to
  6785. fld/fst mem1 (hp1) fld/fst mem1
  6786. fld mem2 (p) fxxx mem2
  6787. fxxxp st, st1 (hp2) }
  6788. begin
  6789. case taicpu(hp2).opcode Of
  6790. A_FADDP: taicpu(p).opcode := A_FADD;
  6791. A_FMULP: taicpu(p).opcode := A_FMUL;
  6792. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6793. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6794. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6795. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6796. else
  6797. internalerror(2019050533);
  6798. end;
  6799. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6800. RemoveInstruction(hp2);
  6801. end
  6802. else
  6803. ;
  6804. end
  6805. end
  6806. end;
  6807. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6808. begin
  6809. Result := condition_in(cond1, cond2) or
  6810. { Not strictly subsets due to the actual flags checked, but because we're
  6811. comparing integers, E is a subset of AE and GE and their aliases }
  6812. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6813. end;
  6814. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6815. var
  6816. v: TCGInt;
  6817. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6818. FirstMatch, TempBool: Boolean;
  6819. NewReg: TRegister;
  6820. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6821. begin
  6822. Result:=false;
  6823. { All these optimisations need a next instruction }
  6824. if not GetNextInstruction(p, hp1) then
  6825. Exit;
  6826. { Search for:
  6827. cmp ###,###
  6828. j(c1) @lbl1
  6829. ...
  6830. @lbl:
  6831. cmp ###,### (same comparison as above)
  6832. j(c2) @lbl2
  6833. If c1 is a subset of c2, change to:
  6834. cmp ###,###
  6835. j(c1) @lbl2
  6836. (@lbl1 may become a dead label as a result)
  6837. }
  6838. { Also handle cases where there are multiple jumps in a row }
  6839. p_jump := hp1;
  6840. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6841. begin
  6842. if IsJumpToLabel(taicpu(p_jump)) then
  6843. begin
  6844. { Do jump optimisations first in case the condition becomes
  6845. unnecessary }
  6846. TempBool := True;
  6847. if DoJumpOptimizations(p_jump, TempBool) or
  6848. not TempBool then
  6849. begin
  6850. if Assigned(p_jump) then
  6851. begin
  6852. hp1 := p_jump;
  6853. if (p_jump.typ in [ait_align]) then
  6854. SkipAligns(p_jump, p_jump);
  6855. { CollapseZeroDistJump will be set to the label after the
  6856. jump if it optimises, whether or not it's live or dead }
  6857. if (p_jump.typ in [ait_label]) and
  6858. not (tai_label(p_jump).labsym.is_used) then
  6859. GetNextInstruction(p_jump, p_jump);
  6860. end;
  6861. TransferUsedRegs(TmpUsedRegs);
  6862. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6863. if not Assigned(p_jump) or
  6864. (
  6865. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  6866. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  6867. ) then
  6868. begin
  6869. { No more conditional jumps; conditional statement is no longer required }
  6870. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  6871. RemoveCurrentP(p);
  6872. Result := True;
  6873. Exit;
  6874. end;
  6875. hp1 := p_jump;
  6876. Include(OptsToCheck, aoc_ForceNewIteration);
  6877. Continue;
  6878. end;
  6879. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6880. if GetNextInstruction(p_jump, hp2) and
  6881. (
  6882. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  6883. not TempBool
  6884. ) then
  6885. begin
  6886. hp1 := p_jump;
  6887. Include(OptsToCheck, aoc_ForceNewIteration);
  6888. Continue;
  6889. end;
  6890. p_label := nil;
  6891. if Assigned(JumpLabel) then
  6892. p_label := getlabelwithsym(JumpLabel);
  6893. if Assigned(p_label) and
  6894. GetNextInstruction(p_label, p_dist) and
  6895. MatchInstruction(p_dist, A_CMP, []) and
  6896. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6897. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6898. GetNextInstruction(p_dist, hp1_dist) and
  6899. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6900. begin
  6901. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6902. if JumpLabel = JumpLabel_dist then
  6903. { This is an infinite loop }
  6904. Exit;
  6905. { Best optimisation when the first condition is a subset (or equal) of the second }
  6906. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6907. begin
  6908. { Any registers used here will already be allocated }
  6909. if Assigned(JumpLabel) then
  6910. JumpLabel.DecRefs;
  6911. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6912. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6913. Result := True;
  6914. { Don't exit yet. Since p and p_jump haven't actually been
  6915. removed, we can check for more on this iteration }
  6916. end
  6917. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6918. GetNextInstruction(hp1_dist, hp1_label) and
  6919. SkipAligns(hp1_label, hp1_label) and
  6920. (hp1_label.typ = ait_label) then
  6921. begin
  6922. JumpLabel_far := tai_label(hp1_label).labsym;
  6923. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6924. { This is an infinite loop }
  6925. Exit;
  6926. if Assigned(JumpLabel_far) then
  6927. begin
  6928. { In this situation, if the first jump branches, the second one will never,
  6929. branch so change the destination label to after the second jump }
  6930. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6931. if Assigned(JumpLabel) then
  6932. JumpLabel.DecRefs;
  6933. JumpLabel_far.IncRefs;
  6934. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6935. Result := True;
  6936. { Don't exit yet. Since p and p_jump haven't actually been
  6937. removed, we can check for more on this iteration }
  6938. Continue;
  6939. end;
  6940. end;
  6941. end;
  6942. end;
  6943. { Search for:
  6944. cmp ###,###
  6945. j(c1) @lbl1
  6946. cmp ###,### (same as first)
  6947. Remove second cmp
  6948. }
  6949. if GetNextInstruction(p_jump, hp2) and
  6950. (
  6951. (
  6952. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6953. (
  6954. (
  6955. MatchOpType(taicpu(p), top_const, top_reg) and
  6956. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6957. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6958. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6959. ) or (
  6960. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6961. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6962. )
  6963. )
  6964. ) or (
  6965. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6966. MatchOperand(taicpu(p).oper[0]^, 0) and
  6967. (taicpu(p).oper[1]^.typ = top_reg) and
  6968. MatchInstruction(hp2, A_TEST, []) and
  6969. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6970. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6971. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6972. )
  6973. ) then
  6974. begin
  6975. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6976. RemoveInstruction(hp2);
  6977. Result := True;
  6978. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6979. end;
  6980. GetNextInstruction(p_jump, p_jump);
  6981. end;
  6982. if (
  6983. { Don't call GetNextInstruction again if we already have it }
  6984. (hp1 = p_jump) or
  6985. GetNextInstruction(p, hp1)
  6986. ) and
  6987. MatchInstruction(hp1, A_Jcc, []) and
  6988. IsJumpToLabel(taicpu(hp1)) and
  6989. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  6990. GetNextInstruction(hp1, hp2) then
  6991. begin
  6992. {
  6993. cmp x, y (or "cmp y, x")
  6994. je @lbl
  6995. mov x, y
  6996. @lbl:
  6997. (x and y can be constants, registers or references)
  6998. Change to:
  6999. mov x, y (x and y will always be equal in the end)
  7000. @lbl: (may beceome a dead label)
  7001. Also:
  7002. cmp x, y (or "cmp y, x")
  7003. jne @lbl
  7004. mov x, y
  7005. @lbl:
  7006. (x and y can be constants, registers or references)
  7007. Change to:
  7008. Absolutely nothing! (Except @lbl if it's still live)
  7009. }
  7010. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7011. (
  7012. (
  7013. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7014. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7015. ) or (
  7016. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7017. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7018. )
  7019. ) and
  7020. GetNextInstruction(hp2, hp1_label) and
  7021. SkipAligns(hp1_label, hp1_label) and
  7022. (hp1_label.typ = ait_label) and
  7023. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7024. begin
  7025. tai_label(hp1_label).labsym.DecRefs;
  7026. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7027. begin
  7028. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7029. RemoveInstruction(hp2);
  7030. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7031. end
  7032. else
  7033. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7034. RemoveInstruction(hp1);
  7035. RemoveCurrentp(p, hp2);
  7036. Result := True;
  7037. Exit;
  7038. end;
  7039. {
  7040. Try to optimise the following:
  7041. cmp $x,### ($x and $y can be registers or constants)
  7042. je @lbl1 (only reference)
  7043. cmp $y,### (### are identical)
  7044. @Lbl:
  7045. sete %reg1
  7046. Change to:
  7047. cmp $x,###
  7048. sete %reg2 (allocate new %reg2)
  7049. cmp $y,###
  7050. sete %reg1
  7051. orb %reg2,%reg1
  7052. (dealloc %reg2)
  7053. This adds an instruction (so don't perform under -Os), but it removes
  7054. a conditional branch.
  7055. }
  7056. if not (cs_opt_size in current_settings.optimizerswitches) and
  7057. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7058. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7059. { The first operand of CMP instructions can only be a register or
  7060. immediate anyway, so no need to check }
  7061. GetNextInstruction(hp2, p_label) and
  7062. (p_label.typ = ait_label) and
  7063. (tai_label(p_label).labsym.getrefs = 1) and
  7064. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7065. GetNextInstruction(p_label, p_dist) and
  7066. MatchInstruction(p_dist, A_SETcc, []) and
  7067. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7068. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7069. begin
  7070. TransferUsedRegs(TmpUsedRegs);
  7071. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7072. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7073. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7074. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7075. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7076. { Get the instruction after the SETcc instruction so we can
  7077. allocate a new register over the entire range }
  7078. GetNextInstruction(p_dist, hp1_dist) then
  7079. begin
  7080. { Register can appear in p if it's not used afterwards, so only
  7081. allocate between hp1 and hp1_dist }
  7082. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7083. if NewReg <> NR_NO then
  7084. begin
  7085. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7086. { Change the jump instruction into a SETcc instruction }
  7087. taicpu(hp1).opcode := A_SETcc;
  7088. taicpu(hp1).opsize := S_B;
  7089. taicpu(hp1).loadreg(0, NewReg);
  7090. { This is now a dead label }
  7091. tai_label(p_label).labsym.decrefs;
  7092. { Prefer adding before the next instruction so the FLAGS
  7093. register is deallicated first }
  7094. AsmL.InsertBefore(
  7095. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7096. hp1_dist
  7097. );
  7098. Result := True;
  7099. { Don't exit yet, as p wasn't changed and hp1, while
  7100. modified, is still intact and might be optimised by the
  7101. SETcc optimisation below }
  7102. end;
  7103. end;
  7104. end;
  7105. end;
  7106. if taicpu(p).oper[0]^.typ = top_const then
  7107. begin
  7108. if (taicpu(p).oper[0]^.val = 0) and
  7109. (taicpu(p).oper[1]^.typ = top_reg) and
  7110. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7111. begin
  7112. hp2 := p;
  7113. FirstMatch := True;
  7114. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7115. anything meaningful once it's converted to "test %reg,%reg";
  7116. additionally, some jumps will always (or never) branch, so
  7117. evaluate every jump immediately following the
  7118. comparison, optimising the conditions if possible.
  7119. Similarly with SETcc... those that are always set to 0 or 1
  7120. are changed to MOV instructions }
  7121. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7122. (
  7123. GetNextInstruction(hp2, hp1) and
  7124. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7125. ) do
  7126. begin
  7127. FirstMatch := False;
  7128. case taicpu(hp1).condition of
  7129. C_B, C_C, C_NAE, C_O:
  7130. { For B/NAE:
  7131. Will never branch since an unsigned integer can never be below zero
  7132. For C/O:
  7133. Result cannot overflow because 0 is being subtracted
  7134. }
  7135. begin
  7136. if taicpu(hp1).opcode = A_Jcc then
  7137. begin
  7138. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7139. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7140. RemoveInstruction(hp1);
  7141. { Since hp1 was deleted, hp2 must not be updated }
  7142. Continue;
  7143. end
  7144. else
  7145. begin
  7146. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7147. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7148. taicpu(hp1).opcode := A_MOV;
  7149. taicpu(hp1).ops := 2;
  7150. taicpu(hp1).condition := C_None;
  7151. taicpu(hp1).opsize := S_B;
  7152. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7153. taicpu(hp1).loadconst(0, 0);
  7154. end;
  7155. end;
  7156. C_BE, C_NA:
  7157. begin
  7158. { Will only branch if equal to zero }
  7159. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7160. taicpu(hp1).condition := C_E;
  7161. end;
  7162. C_A, C_NBE:
  7163. begin
  7164. { Will only branch if not equal to zero }
  7165. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7166. taicpu(hp1).condition := C_NE;
  7167. end;
  7168. C_AE, C_NB, C_NC, C_NO:
  7169. begin
  7170. { Will always branch }
  7171. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7172. if taicpu(hp1).opcode = A_Jcc then
  7173. begin
  7174. MakeUnconditional(taicpu(hp1));
  7175. { Any jumps/set that follow will now be dead code }
  7176. RemoveDeadCodeAfterJump(taicpu(hp1));
  7177. Break;
  7178. end
  7179. else
  7180. begin
  7181. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7182. taicpu(hp1).opcode := A_MOV;
  7183. taicpu(hp1).ops := 2;
  7184. taicpu(hp1).condition := C_None;
  7185. taicpu(hp1).opsize := S_B;
  7186. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7187. taicpu(hp1).loadconst(0, 1);
  7188. end;
  7189. end;
  7190. C_None:
  7191. InternalError(2020012201);
  7192. C_P, C_PE, C_NP, C_PO:
  7193. { We can't handle parity checks and they should never be generated
  7194. after a general-purpose CMP (it's used in some floating-point
  7195. comparisons that don't use CMP) }
  7196. InternalError(2020012202);
  7197. else
  7198. { Zero/Equality, Sign, their complements and all of the
  7199. signed comparisons do not need to be converted };
  7200. end;
  7201. hp2 := hp1;
  7202. end;
  7203. { Convert the instruction to a TEST }
  7204. taicpu(p).opcode := A_TEST;
  7205. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7206. Result := True;
  7207. Exit;
  7208. end
  7209. else if (taicpu(p).oper[0]^.val = 1) and
  7210. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7211. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7212. begin
  7213. { Convert; To:
  7214. cmp $1,r/m cmp $0,r/m
  7215. jl @lbl jle @lbl
  7216. (Also do inverted conditions)
  7217. }
  7218. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7219. taicpu(p).oper[0]^.val := 0;
  7220. if taicpu(hp1).condition in [C_L, C_NGE] then
  7221. taicpu(hp1).condition := C_LE
  7222. else
  7223. taicpu(hp1).condition := C_NLE;
  7224. { If the instruction is now "cmp $0,%reg", convert it to a
  7225. TEST (and effectively do the work of the "cmp $0,%reg" in
  7226. the block above)
  7227. }
  7228. if (taicpu(p).oper[1]^.typ = top_reg) then
  7229. begin
  7230. taicpu(p).opcode := A_TEST;
  7231. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7232. end;
  7233. Result := True;
  7234. Exit;
  7235. end
  7236. else if (taicpu(p).oper[1]^.typ = top_reg)
  7237. {$ifdef x86_64}
  7238. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7239. {$endif x86_64}
  7240. then
  7241. begin
  7242. { cmp register,$8000 neg register
  7243. je target --> jo target
  7244. .... only if register is deallocated before jump.}
  7245. case Taicpu(p).opsize of
  7246. S_B: v:=$80;
  7247. S_W: v:=$8000;
  7248. S_L: v:=qword($80000000);
  7249. else
  7250. internalerror(2013112905);
  7251. end;
  7252. if (taicpu(p).oper[0]^.val=v) and
  7253. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7254. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7255. begin
  7256. TransferUsedRegs(TmpUsedRegs);
  7257. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7258. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7259. begin
  7260. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7261. Taicpu(p).opcode:=A_NEG;
  7262. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7263. Taicpu(p).clearop(1);
  7264. Taicpu(p).ops:=1;
  7265. if Taicpu(hp1).condition=C_E then
  7266. Taicpu(hp1).condition:=C_O
  7267. else
  7268. Taicpu(hp1).condition:=C_NO;
  7269. Result:=true;
  7270. exit;
  7271. end;
  7272. end;
  7273. end;
  7274. end;
  7275. if TrySwapMovCmp(p, hp1) then
  7276. begin
  7277. Result := True;
  7278. Exit;
  7279. end;
  7280. end;
  7281. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7282. var
  7283. hp1: tai;
  7284. begin
  7285. {
  7286. remove the second (v)pxor from
  7287. pxor reg,reg
  7288. ...
  7289. pxor reg,reg
  7290. }
  7291. Result:=false;
  7292. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7293. MatchOpType(taicpu(p),top_reg,top_reg) and
  7294. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7295. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7296. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7297. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7298. begin
  7299. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7300. RemoveInstruction(hp1);
  7301. Result:=true;
  7302. Exit;
  7303. end
  7304. {
  7305. replace
  7306. pxor reg1,reg1
  7307. movapd/s reg1,reg2
  7308. dealloc reg1
  7309. by
  7310. pxor reg2,reg2
  7311. }
  7312. else if GetNextInstruction(p,hp1) and
  7313. { we mix single and double opperations here because we assume that the compiler
  7314. generates vmovapd only after double operations and vmovaps only after single operations }
  7315. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7316. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7317. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7318. (taicpu(p).oper[0]^.typ=top_reg) then
  7319. begin
  7320. TransferUsedRegs(TmpUsedRegs);
  7321. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7322. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7323. begin
  7324. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7325. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7326. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7327. RemoveInstruction(hp1);
  7328. result:=true;
  7329. end;
  7330. end;
  7331. end;
  7332. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7333. var
  7334. hp1: tai;
  7335. begin
  7336. {
  7337. remove the second (v)pxor from
  7338. (v)pxor reg,reg
  7339. ...
  7340. (v)pxor reg,reg
  7341. }
  7342. Result:=false;
  7343. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7344. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7345. begin
  7346. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7347. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7348. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7349. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7350. begin
  7351. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7352. RemoveInstruction(hp1);
  7353. Result:=true;
  7354. Exit;
  7355. end;
  7356. {$ifdef x86_64}
  7357. {
  7358. replace
  7359. vpxor reg1,reg1,reg1
  7360. vmov reg,mem
  7361. by
  7362. movq $0,mem
  7363. }
  7364. if GetNextInstruction(p,hp1) and
  7365. MatchInstruction(hp1,A_VMOVSD,[]) and
  7366. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7367. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7368. begin
  7369. TransferUsedRegs(TmpUsedRegs);
  7370. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7371. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7372. begin
  7373. taicpu(hp1).loadconst(0,0);
  7374. taicpu(hp1).opcode:=A_MOV;
  7375. taicpu(hp1).opsize:=S_Q;
  7376. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7377. RemoveCurrentP(p);
  7378. result:=true;
  7379. Exit;
  7380. end;
  7381. end;
  7382. {$endif x86_64}
  7383. end
  7384. {
  7385. replace
  7386. vpxor reg1,reg1,reg2
  7387. by
  7388. vpxor reg2,reg2,reg2
  7389. to avoid unncessary data dependencies
  7390. }
  7391. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7392. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7393. begin
  7394. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7395. { avoid unncessary data dependency }
  7396. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7397. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7398. result:=true;
  7399. exit;
  7400. end;
  7401. Result:=OptPass1VOP(p);
  7402. end;
  7403. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7404. var
  7405. hp1 : tai;
  7406. begin
  7407. result:=false;
  7408. { replace
  7409. IMul const,%mreg1,%mreg2
  7410. Mov %reg2,%mreg3
  7411. dealloc %mreg3
  7412. by
  7413. Imul const,%mreg1,%mreg23
  7414. }
  7415. if (taicpu(p).ops=3) and
  7416. GetNextInstruction(p,hp1) and
  7417. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7418. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7419. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7420. begin
  7421. TransferUsedRegs(TmpUsedRegs);
  7422. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7423. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7424. begin
  7425. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7426. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7427. RemoveInstruction(hp1);
  7428. result:=true;
  7429. end;
  7430. end;
  7431. end;
  7432. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7433. var
  7434. hp1 : tai;
  7435. begin
  7436. result:=false;
  7437. { replace
  7438. IMul %reg0,%reg1,%reg2
  7439. Mov %reg2,%reg3
  7440. dealloc %reg2
  7441. by
  7442. Imul %reg0,%reg1,%reg3
  7443. }
  7444. if GetNextInstruction(p,hp1) and
  7445. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7446. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7447. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7448. begin
  7449. TransferUsedRegs(TmpUsedRegs);
  7450. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7451. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7452. begin
  7453. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7454. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7455. RemoveInstruction(hp1);
  7456. result:=true;
  7457. end;
  7458. end;
  7459. end;
  7460. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7461. var
  7462. hp1: tai;
  7463. begin
  7464. Result:=false;
  7465. { get rid of
  7466. (v)cvtss2sd reg0,<reg1,>reg2
  7467. (v)cvtss2sd reg2,<reg2,>reg0
  7468. }
  7469. if GetNextInstruction(p,hp1) and
  7470. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7471. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7472. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7473. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7474. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7475. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7476. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7477. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7478. )
  7479. ) then
  7480. begin
  7481. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7482. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7483. begin
  7484. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7485. RemoveCurrentP(p);
  7486. RemoveInstruction(hp1);
  7487. end
  7488. else
  7489. begin
  7490. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7491. if taicpu(hp1).opcode=A_CVTSD2SS then
  7492. begin
  7493. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7494. taicpu(p).opcode:=A_MOVAPS;
  7495. end
  7496. else
  7497. begin
  7498. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7499. taicpu(p).opcode:=A_VMOVAPS;
  7500. end;
  7501. taicpu(p).ops:=2;
  7502. RemoveInstruction(hp1);
  7503. end;
  7504. Result:=true;
  7505. Exit;
  7506. end;
  7507. end;
  7508. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7509. var
  7510. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7511. ThisReg: TRegister;
  7512. begin
  7513. Result := False;
  7514. if not GetNextInstruction(p,hp1) then
  7515. Exit;
  7516. {
  7517. convert
  7518. j<c> .L1
  7519. mov 1,reg
  7520. jmp .L2
  7521. .L1
  7522. mov 0,reg
  7523. .L2
  7524. into
  7525. mov 0,reg
  7526. set<not(c)> reg
  7527. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7528. would destroy the flag contents
  7529. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7530. executed at the same time as a previous comparison.
  7531. set<not(c)> reg
  7532. movzx reg, reg
  7533. }
  7534. if MatchInstruction(hp1,A_MOV,[]) and
  7535. (taicpu(hp1).oper[0]^.typ = top_const) and
  7536. (
  7537. (
  7538. (taicpu(hp1).oper[1]^.typ = top_reg)
  7539. {$ifdef i386}
  7540. { Under i386, ESI, EDI, EBP and ESP
  7541. don't have an 8-bit representation }
  7542. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7543. {$endif i386}
  7544. ) or (
  7545. {$ifdef i386}
  7546. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7547. {$endif i386}
  7548. (taicpu(hp1).opsize = S_B)
  7549. )
  7550. ) and
  7551. GetNextInstruction(hp1,hp2) and
  7552. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7553. GetNextInstruction(hp2,hp3) and
  7554. SkipAligns(hp3, hp3) and
  7555. (hp3.typ=ait_label) and
  7556. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7557. GetNextInstruction(hp3,hp4) and
  7558. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7559. (taicpu(hp4).oper[0]^.typ = top_const) and
  7560. (
  7561. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7562. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7563. ) and
  7564. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7565. GetNextInstruction(hp4,hp5) and
  7566. SkipAligns(hp5, hp5) and
  7567. (hp5.typ=ait_label) and
  7568. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7569. begin
  7570. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7571. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7572. tai_label(hp3).labsym.DecRefs;
  7573. { If this isn't the only reference to the middle label, we can
  7574. still make a saving - only that the first jump and everything
  7575. that follows will remain. }
  7576. if (tai_label(hp3).labsym.getrefs = 0) then
  7577. begin
  7578. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7579. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7580. else
  7581. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7582. { remove jump, first label and second MOV (also catching any aligns) }
  7583. repeat
  7584. if not GetNextInstruction(hp2, hp3) then
  7585. InternalError(2021040810);
  7586. RemoveInstruction(hp2);
  7587. hp2 := hp3;
  7588. until hp2 = hp5;
  7589. { Don't decrement reference count before the removal loop
  7590. above, otherwise GetNextInstruction won't stop on the
  7591. the label }
  7592. tai_label(hp5).labsym.DecRefs;
  7593. end
  7594. else
  7595. begin
  7596. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7597. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7598. else
  7599. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7600. end;
  7601. taicpu(p).opcode:=A_SETcc;
  7602. taicpu(p).opsize:=S_B;
  7603. taicpu(p).is_jmp:=False;
  7604. if taicpu(hp1).opsize=S_B then
  7605. begin
  7606. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7607. if taicpu(hp1).oper[1]^.typ = top_reg then
  7608. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7609. RemoveInstruction(hp1);
  7610. end
  7611. else
  7612. begin
  7613. { Will be a register because the size can't be S_B otherwise }
  7614. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7615. taicpu(p).loadreg(0, ThisReg);
  7616. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7617. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7618. begin
  7619. case taicpu(hp1).opsize of
  7620. S_W:
  7621. taicpu(hp1).opsize := S_BW;
  7622. S_L:
  7623. taicpu(hp1).opsize := S_BL;
  7624. {$ifdef x86_64}
  7625. S_Q:
  7626. begin
  7627. taicpu(hp1).opsize := S_BL;
  7628. { Change the destination register to 32-bit }
  7629. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7630. end;
  7631. {$endif x86_64}
  7632. else
  7633. InternalError(2021040820);
  7634. end;
  7635. taicpu(hp1).opcode := A_MOVZX;
  7636. taicpu(hp1).loadreg(0, ThisReg);
  7637. end
  7638. else
  7639. begin
  7640. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7641. { hp1 is already a MOV instruction with the correct register }
  7642. taicpu(hp1).loadconst(0, 0);
  7643. { Inserting it right before p will guarantee that the flags are also tracked }
  7644. asml.Remove(hp1);
  7645. asml.InsertBefore(hp1, p);
  7646. end;
  7647. end;
  7648. Result:=true;
  7649. exit;
  7650. end
  7651. else if (hp1.typ = ait_label) then
  7652. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7653. end;
  7654. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7655. var
  7656. hp1, hp2, hp3: tai;
  7657. SourceRef, TargetRef: TReference;
  7658. CurrentReg: TRegister;
  7659. begin
  7660. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7661. if not UseAVX then
  7662. InternalError(2021100501);
  7663. Result := False;
  7664. { Look for the following to simplify:
  7665. vmovdqa/u x(mem1), %xmmreg
  7666. vmovdqa/u %xmmreg, y(mem2)
  7667. vmovdqa/u x+16(mem1), %xmmreg
  7668. vmovdqa/u %xmmreg, y+16(mem2)
  7669. Change to:
  7670. vmovdqa/u x(mem1), %ymmreg
  7671. vmovdqa/u %ymmreg, y(mem2)
  7672. vpxor %ymmreg, %ymmreg, %ymmreg
  7673. ( The VPXOR instruction is to zero the upper half, thus removing the
  7674. need to call the potentially expensive VZEROUPPER instruction. Other
  7675. peephole optimisations can remove VPXOR if it's unnecessary )
  7676. }
  7677. TransferUsedRegs(TmpUsedRegs);
  7678. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7679. { NOTE: In the optimisations below, if the references dictate that an
  7680. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7681. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7682. if (taicpu(p).opsize = S_XMM) and
  7683. MatchOpType(taicpu(p), top_ref, top_reg) and
  7684. GetNextInstruction(p, hp1) and
  7685. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7686. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7687. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7688. begin
  7689. SourceRef := taicpu(p).oper[0]^.ref^;
  7690. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7691. if GetNextInstruction(hp1, hp2) and
  7692. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7693. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7694. begin
  7695. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7696. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7697. Inc(SourceRef.offset, 16);
  7698. { Reuse the register in the first block move }
  7699. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7700. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7701. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7702. begin
  7703. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7704. Inc(TargetRef.offset, 16);
  7705. if GetNextInstruction(hp2, hp3) and
  7706. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7707. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7708. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7709. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7710. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7711. begin
  7712. { Update the register tracking to the new size }
  7713. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7714. { Remember that the offsets are 16 ahead }
  7715. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7716. if not (
  7717. ((SourceRef.offset mod 32) = 16) and
  7718. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7719. ) then
  7720. taicpu(p).opcode := A_VMOVDQU;
  7721. taicpu(p).opsize := S_YMM;
  7722. taicpu(p).oper[1]^.reg := CurrentReg;
  7723. if not (
  7724. ((TargetRef.offset mod 32) = 16) and
  7725. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7726. ) then
  7727. taicpu(hp1).opcode := A_VMOVDQU;
  7728. taicpu(hp1).opsize := S_YMM;
  7729. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7730. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7731. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7732. if (pi_uses_ymm in current_procinfo.flags) then
  7733. RemoveInstruction(hp2)
  7734. else
  7735. begin
  7736. taicpu(hp2).opcode := A_VPXOR;
  7737. taicpu(hp2).opsize := S_YMM;
  7738. taicpu(hp2).loadreg(0, CurrentReg);
  7739. taicpu(hp2).loadreg(1, CurrentReg);
  7740. taicpu(hp2).loadreg(2, CurrentReg);
  7741. taicpu(hp2).ops := 3;
  7742. end;
  7743. RemoveInstruction(hp3);
  7744. Result := True;
  7745. Exit;
  7746. end;
  7747. end
  7748. else
  7749. begin
  7750. { See if the next references are 16 less rather than 16 greater }
  7751. Dec(SourceRef.offset, 32); { -16 the other way }
  7752. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7753. begin
  7754. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7755. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7756. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7757. GetNextInstruction(hp2, hp3) and
  7758. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7759. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7760. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7761. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7762. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7763. begin
  7764. { Update the register tracking to the new size }
  7765. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7766. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7767. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7768. if not(
  7769. ((SourceRef.offset mod 32) = 0) and
  7770. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7771. ) then
  7772. taicpu(hp2).opcode := A_VMOVDQU;
  7773. taicpu(hp2).opsize := S_YMM;
  7774. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7775. if not (
  7776. ((TargetRef.offset mod 32) = 0) and
  7777. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7778. ) then
  7779. taicpu(hp3).opcode := A_VMOVDQU;
  7780. taicpu(hp3).opsize := S_YMM;
  7781. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7782. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7783. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7784. if (pi_uses_ymm in current_procinfo.flags) then
  7785. RemoveInstruction(hp1)
  7786. else
  7787. begin
  7788. taicpu(hp1).opcode := A_VPXOR;
  7789. taicpu(hp1).opsize := S_YMM;
  7790. taicpu(hp1).loadreg(0, CurrentReg);
  7791. taicpu(hp1).loadreg(1, CurrentReg);
  7792. taicpu(hp1).loadreg(2, CurrentReg);
  7793. taicpu(hp1).ops := 3;
  7794. Asml.Remove(hp1);
  7795. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7796. end;
  7797. RemoveCurrentP(p, hp2);
  7798. Result := True;
  7799. Exit;
  7800. end;
  7801. end;
  7802. end;
  7803. end;
  7804. end;
  7805. end;
  7806. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7807. var
  7808. hp2, hp3, first_assignment: tai;
  7809. IncCount, OperIdx: Integer;
  7810. OrigLabel: TAsmLabel;
  7811. begin
  7812. Count := 0;
  7813. Result := False;
  7814. first_assignment := nil;
  7815. if (LoopCount >= 20) then
  7816. begin
  7817. { Guard against infinite loops }
  7818. Exit;
  7819. end;
  7820. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7821. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7822. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7823. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7824. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7825. Exit;
  7826. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7827. {
  7828. change
  7829. jmp .L1
  7830. ...
  7831. .L1:
  7832. mov ##, ## ( multiple movs possible )
  7833. jmp/ret
  7834. into
  7835. mov ##, ##
  7836. jmp/ret
  7837. }
  7838. if not Assigned(hp1) then
  7839. begin
  7840. hp1 := GetLabelWithSym(OrigLabel);
  7841. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7842. Exit;
  7843. end;
  7844. hp2 := hp1;
  7845. while Assigned(hp2) do
  7846. begin
  7847. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7848. SkipLabels(hp2,hp2);
  7849. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7850. Break;
  7851. case taicpu(hp2).opcode of
  7852. A_MOVSD:
  7853. begin
  7854. if taicpu(hp2).ops = 0 then
  7855. { Wrong MOVSD }
  7856. Break;
  7857. Inc(Count);
  7858. if Count >= 5 then
  7859. { Too many to be worthwhile }
  7860. Break;
  7861. GetNextInstruction(hp2, hp2);
  7862. Continue;
  7863. end;
  7864. A_MOV,
  7865. A_MOVD,
  7866. A_MOVQ,
  7867. A_MOVSX,
  7868. {$ifdef x86_64}
  7869. A_MOVSXD,
  7870. {$endif x86_64}
  7871. A_MOVZX,
  7872. A_MOVAPS,
  7873. A_MOVUPS,
  7874. A_MOVSS,
  7875. A_MOVAPD,
  7876. A_MOVUPD,
  7877. A_MOVDQA,
  7878. A_MOVDQU,
  7879. A_VMOVSS,
  7880. A_VMOVAPS,
  7881. A_VMOVUPS,
  7882. A_VMOVSD,
  7883. A_VMOVAPD,
  7884. A_VMOVUPD,
  7885. A_VMOVDQA,
  7886. A_VMOVDQU:
  7887. begin
  7888. Inc(Count);
  7889. if Count >= 5 then
  7890. { Too many to be worthwhile }
  7891. Break;
  7892. GetNextInstruction(hp2, hp2);
  7893. Continue;
  7894. end;
  7895. A_JMP:
  7896. begin
  7897. { Guard against infinite loops }
  7898. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7899. Exit;
  7900. { Analyse this jump first in case it also duplicates assignments }
  7901. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7902. begin
  7903. { Something did change! }
  7904. Result := True;
  7905. Inc(Count, IncCount);
  7906. if Count >= 5 then
  7907. begin
  7908. { Too many to be worthwhile }
  7909. Exit;
  7910. end;
  7911. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7912. Break;
  7913. end;
  7914. Result := True;
  7915. Break;
  7916. end;
  7917. A_RET:
  7918. begin
  7919. Result := True;
  7920. Break;
  7921. end;
  7922. else
  7923. Break;
  7924. end;
  7925. end;
  7926. if Result then
  7927. begin
  7928. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7929. if Count = 0 then
  7930. begin
  7931. Result := False;
  7932. Exit;
  7933. end;
  7934. hp3 := p;
  7935. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7936. while True do
  7937. begin
  7938. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7939. SkipLabels(hp1,hp1);
  7940. if (hp1.typ <> ait_instruction) then
  7941. InternalError(2021040720);
  7942. case taicpu(hp1).opcode of
  7943. A_JMP:
  7944. begin
  7945. { Change the original jump to the new destination }
  7946. OrigLabel.decrefs;
  7947. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7948. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7949. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7950. if not Assigned(first_assignment) then
  7951. InternalError(2021040810)
  7952. else
  7953. p := first_assignment;
  7954. Exit;
  7955. end;
  7956. A_RET:
  7957. begin
  7958. { Now change the jump into a RET instruction }
  7959. ConvertJumpToRET(p, hp1);
  7960. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7961. if not Assigned(first_assignment) then
  7962. InternalError(2021040811)
  7963. else
  7964. p := first_assignment;
  7965. Exit;
  7966. end;
  7967. else
  7968. begin
  7969. { Duplicate the MOV instruction }
  7970. hp3:=tai(hp1.getcopy);
  7971. if first_assignment = nil then
  7972. first_assignment := hp3;
  7973. asml.InsertBefore(hp3, p);
  7974. { Make sure the compiler knows about any final registers written here }
  7975. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7976. with taicpu(hp3).oper[OperIdx]^ do
  7977. begin
  7978. case typ of
  7979. top_ref:
  7980. begin
  7981. if (ref^.base <> NR_NO) and
  7982. (getsupreg(ref^.base) <> RS_ESP) and
  7983. (getsupreg(ref^.base) <> RS_EBP)
  7984. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7985. then
  7986. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7987. if (ref^.index <> NR_NO) and
  7988. (getsupreg(ref^.index) <> RS_ESP) and
  7989. (getsupreg(ref^.index) <> RS_EBP)
  7990. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7991. (ref^.index <> ref^.base) then
  7992. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7993. end;
  7994. top_reg:
  7995. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7996. else
  7997. ;
  7998. end;
  7999. end;
  8000. end;
  8001. end;
  8002. if not GetNextInstruction(hp1, hp1) then
  8003. { Should have dropped out earlier }
  8004. InternalError(2021040710);
  8005. end;
  8006. end;
  8007. end;
  8008. const
  8009. WriteOp: array[0..3] of set of TInsChange = (
  8010. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8011. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8012. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8013. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8014. RegWriteFlags: array[0..7] of set of TInsChange = (
  8015. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8016. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8017. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8018. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8019. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8020. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8021. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8022. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8023. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8024. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8025. var
  8026. hp2: tai;
  8027. X: Integer;
  8028. begin
  8029. { If we have something like:
  8030. op ###,###
  8031. mov ###,###
  8032. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8033. interfere in regards to what they write to.
  8034. NOTE: p must be a 2-operand instruction
  8035. }
  8036. Result := False;
  8037. if (hp1.typ <> ait_instruction) or
  8038. taicpu(hp1).is_jmp or
  8039. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8040. Exit;
  8041. { NOP is a pipeline fence, likely marking the beginning of the function
  8042. epilogue, so drop out. Similarly, drop out if POP or RET are
  8043. encountered }
  8044. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8045. Exit;
  8046. if (taicpu(hp1).opcode = A_MOVSD) and
  8047. (taicpu(hp1).ops = 0) then
  8048. { Wrong MOVSD }
  8049. Exit;
  8050. { Check for writes to specific registers first }
  8051. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8052. for X := 0 to 7 do
  8053. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8054. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8055. Exit;
  8056. for X := 0 to taicpu(hp1).ops - 1 do
  8057. begin
  8058. { Check to see if this operand writes to something }
  8059. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8060. { And matches something in the CMP/TEST instruction }
  8061. (
  8062. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8063. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8064. (
  8065. { If it's a register, make sure the register written to doesn't
  8066. appear in the cmp instruction as part of a reference }
  8067. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8068. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8069. )
  8070. ) then
  8071. Exit;
  8072. end;
  8073. { Check p to make sure it doesn't write to something that affects hp1 }
  8074. { Check for writes to specific registers first }
  8075. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8076. for X := 0 to 7 do
  8077. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8078. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8079. Exit;
  8080. for X := 0 to taicpu(p).ops - 1 do
  8081. begin
  8082. { Check to see if this operand writes to something }
  8083. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8084. { And matches something in hp1 }
  8085. (taicpu(p).oper[X]^.typ = top_reg) and
  8086. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8087. Exit;
  8088. end;
  8089. { The instruction can be safely moved }
  8090. asml.Remove(hp1);
  8091. { Try to insert after the last instructions where the FLAGS register is not
  8092. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8093. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8094. asml.InsertBefore(hp1, hp2)
  8095. { Failing that, try to insert after the last instructions where the
  8096. FLAGS register is not yet in use }
  8097. else if GetLastInstruction(p, hp2) and
  8098. (
  8099. (hp2.typ <> ait_instruction) or
  8100. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8101. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8102. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8103. ) then
  8104. asml.InsertAfter(hp1, hp2)
  8105. else
  8106. { Note, if p.Previous is nil (even if it should logically never be the
  8107. case), FindRegAllocBackward immediately exits with False and so we
  8108. safely land here (we can't just pass p because FindRegAllocBackward
  8109. immediately exits on an instruction). [Kit] }
  8110. asml.InsertBefore(hp1, p);
  8111. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8112. { We can't trust UsedRegs because we're looking backwards, although we
  8113. know the registers are allocated after p at the very least, so manually
  8114. create tai_regalloc objects if needed }
  8115. for X := 0 to taicpu(hp1).ops - 1 do
  8116. case taicpu(hp1).oper[X]^.typ of
  8117. top_reg:
  8118. begin
  8119. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8120. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8121. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8122. end;
  8123. top_ref:
  8124. begin
  8125. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8126. begin
  8127. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8128. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8129. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8130. end;
  8131. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8132. begin
  8133. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8134. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8135. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8136. end;
  8137. end;
  8138. else
  8139. ;
  8140. end;
  8141. Result := True;
  8142. end;
  8143. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8144. var
  8145. hp2: tai;
  8146. X: Integer;
  8147. begin
  8148. { If we have something like:
  8149. cmp ###,%reg1
  8150. mov 0,%reg2
  8151. And no modified registers are shared, move the instruction to before
  8152. the comparison as this means it can be optimised without worrying
  8153. about the FLAGS register. (CMP/MOV is generated by
  8154. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8155. As long as the second instruction doesn't use the flags or one of the
  8156. registers used by CMP or TEST (also check any references that use the
  8157. registers), then it can be moved prior to the comparison.
  8158. }
  8159. Result := False;
  8160. if not TrySwapMovOp(p, hp1) then
  8161. Exit;
  8162. if taicpu(hp1).opcode = A_LEA then
  8163. { The flags will be overwritten by the CMP/TEST instruction }
  8164. ConvertLEA(taicpu(hp1));
  8165. Result := True;
  8166. { Can we move it one further back? }
  8167. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8168. { Check to see if CMP/TEST is a comparison against zero }
  8169. (
  8170. (
  8171. (taicpu(p).opcode = A_CMP) and
  8172. MatchOperand(taicpu(p).oper[0]^, 0)
  8173. ) or
  8174. (
  8175. (taicpu(p).opcode = A_TEST) and
  8176. (
  8177. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8178. MatchOperand(taicpu(p).oper[0]^, -1)
  8179. )
  8180. )
  8181. ) and
  8182. { These instructions set the zero flag if the result is zero }
  8183. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8184. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8185. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8186. TrySwapMovOp(hp2, hp1);
  8187. end;
  8188. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8189. function IsXCHGAcceptable: Boolean; inline;
  8190. begin
  8191. { Always accept if optimising for size }
  8192. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8193. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8194. than 3, so it becomes a saving compared to three MOVs with two of
  8195. them able to execute simultaneously. [Kit] }
  8196. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8197. end;
  8198. var
  8199. NewRef: TReference;
  8200. hp1, hp2, hp3, hp4: Tai;
  8201. {$ifndef x86_64}
  8202. OperIdx: Integer;
  8203. {$endif x86_64}
  8204. NewInstr : Taicpu;
  8205. NewAligh : Tai_align;
  8206. DestLabel: TAsmLabel;
  8207. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8208. var
  8209. NextInstr: tai;
  8210. begin
  8211. Result := False;
  8212. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8213. if not GetNextInstruction(InputInstr, NextInstr) or
  8214. (
  8215. { The FLAGS register isn't always tracked properly, so do not
  8216. perform this optimisation if a conditional statement follows }
  8217. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8218. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8219. ) then
  8220. begin
  8221. reference_reset(NewRef, 1, []);
  8222. NewRef.base := taicpu(p).oper[0]^.reg;
  8223. NewRef.scalefactor := 1;
  8224. if taicpu(InputInstr).opcode = A_ADD then
  8225. begin
  8226. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8227. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8228. end
  8229. else
  8230. begin
  8231. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8232. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8233. end;
  8234. taicpu(p).opcode := A_LEA;
  8235. taicpu(p).loadref(0, NewRef);
  8236. RemoveInstruction(InputInstr);
  8237. Result := True;
  8238. end;
  8239. end;
  8240. begin
  8241. Result:=false;
  8242. { This optimisation adds an instruction, so only do it for speed }
  8243. if not (cs_opt_size in current_settings.optimizerswitches) and
  8244. MatchOpType(taicpu(p), top_const, top_reg) and
  8245. (taicpu(p).oper[0]^.val = 0) then
  8246. begin
  8247. { To avoid compiler warning }
  8248. DestLabel := nil;
  8249. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8250. InternalError(2021040750);
  8251. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8252. Exit;
  8253. case hp1.typ of
  8254. ait_align,
  8255. ait_label:
  8256. begin
  8257. { Change:
  8258. mov $0,%reg mov $0,%reg
  8259. @Lbl1: @Lbl1:
  8260. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8261. je @Lbl2 jne @Lbl2
  8262. To: To:
  8263. mov $0,%reg mov $0,%reg
  8264. jmp @Lbl2 jmp @Lbl3
  8265. (align) (align)
  8266. @Lbl1: @Lbl1:
  8267. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8268. je @Lbl2 je @Lbl2
  8269. @Lbl3: <-- Only if label exists
  8270. (Not if it's optimised for size)
  8271. }
  8272. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8273. Exit;
  8274. if (hp2.typ = ait_instruction) and
  8275. (
  8276. { Register sizes must exactly match }
  8277. (
  8278. (taicpu(hp2).opcode = A_CMP) and
  8279. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8280. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8281. ) or (
  8282. (taicpu(hp2).opcode = A_TEST) and
  8283. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8284. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8285. )
  8286. ) and GetNextInstruction(hp2, hp3) and
  8287. (hp3.typ = ait_instruction) and
  8288. (taicpu(hp3).opcode = A_JCC) and
  8289. (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
  8290. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8291. begin
  8292. { Check condition of jump }
  8293. { Always true? }
  8294. if condition_in(C_E, taicpu(hp3).condition) then
  8295. begin
  8296. { Copy label symbol and obtain matching label entry for the
  8297. conditional jump, as this will be our destination}
  8298. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8299. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8300. Result := True;
  8301. end
  8302. { Always false? }
  8303. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8304. begin
  8305. { This is only worth it if there's a jump to take }
  8306. case hp2.typ of
  8307. ait_instruction:
  8308. begin
  8309. if taicpu(hp2).opcode = A_JMP then
  8310. begin
  8311. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8312. { An unconditional jump follows the conditional jump which will always be false,
  8313. so use this jump's destination for the new jump }
  8314. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8315. Result := True;
  8316. end
  8317. else if taicpu(hp2).opcode = A_JCC then
  8318. begin
  8319. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8320. if condition_in(C_E, taicpu(hp2).condition) then
  8321. begin
  8322. { A second conditional jump follows the conditional jump which will always be false,
  8323. while the second jump is always True, so use this jump's destination for the new jump }
  8324. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8325. Result := True;
  8326. end;
  8327. { Don't risk it if the jump isn't always true (Result remains False) }
  8328. end;
  8329. end;
  8330. else
  8331. { If anything else don't optimise };
  8332. end;
  8333. end;
  8334. if Result then
  8335. begin
  8336. { Just so we have something to insert as a paremeter}
  8337. reference_reset(NewRef, 1, []);
  8338. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8339. { Now actually load the correct parameter (this also
  8340. increases the reference count) }
  8341. NewInstr.loadsymbol(0, DestLabel, 0);
  8342. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8343. begin
  8344. { Get instruction before original label (may not be p under -O3) }
  8345. if not GetLastInstruction(hp1, hp2) then
  8346. { Shouldn't fail here }
  8347. InternalError(2021040701);
  8348. { Before the aligns too }
  8349. while (hp2.typ = ait_align) do
  8350. if not GetLastInstruction(hp2, hp2) then
  8351. { Shouldn't fail here }
  8352. InternalError(2021040702);
  8353. end
  8354. else
  8355. hp2 := p;
  8356. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8357. AsmL.InsertAfter(NewInstr, hp2);
  8358. { Add new alignment field }
  8359. (* AsmL.InsertAfter(
  8360. cai_align.create_max(
  8361. current_settings.alignment.jumpalign,
  8362. current_settings.alignment.jumpalignskipmax
  8363. ),
  8364. NewInstr
  8365. ); *)
  8366. end;
  8367. Exit;
  8368. end;
  8369. end;
  8370. else
  8371. ;
  8372. end;
  8373. end;
  8374. if not GetNextInstruction(p, hp1) then
  8375. Exit;
  8376. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8377. and DoMovCmpMemOpt(p, hp1, True) then
  8378. begin
  8379. Result := True;
  8380. Exit;
  8381. end
  8382. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8383. begin
  8384. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8385. further, but we can't just put this jump optimisation in pass 1
  8386. because it tends to perform worse when conditional jumps are
  8387. nearby (e.g. when converting CMOV instructions). [Kit] }
  8388. if OptPass2JMP(hp1) then
  8389. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8390. Result := OptPass1MOV(p)
  8391. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8392. returned True and the instruction is still a MOV, thus checking
  8393. the optimisations below }
  8394. { If OptPass2JMP returned False, no optimisations were done to
  8395. the jump and there are no further optimisations that can be done
  8396. to the MOV instruction on this pass }
  8397. end
  8398. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8399. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8400. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8401. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8402. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8403. begin
  8404. { Change:
  8405. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8406. addl/q $x,%reg2 subl/q $x,%reg2
  8407. To:
  8408. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8409. }
  8410. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8411. { be lazy, checking separately for sub would be slightly better }
  8412. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8413. begin
  8414. TransferUsedRegs(TmpUsedRegs);
  8415. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8416. if TryMovArith2Lea(hp1) then
  8417. begin
  8418. Result := True;
  8419. Exit;
  8420. end
  8421. end
  8422. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8423. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8424. { Same as above, but also adds or subtracts to %reg2 in between.
  8425. It's still valid as long as the flags aren't in use }
  8426. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8427. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8428. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8429. { be lazy, checking separately for sub would be slightly better }
  8430. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8431. begin
  8432. TransferUsedRegs(TmpUsedRegs);
  8433. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8434. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8435. if TryMovArith2Lea(hp2) then
  8436. begin
  8437. Result := True;
  8438. Exit;
  8439. end;
  8440. end;
  8441. end
  8442. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8443. {$ifdef x86_64}
  8444. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8445. {$else x86_64}
  8446. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8447. {$endif x86_64}
  8448. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8449. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8450. { mov reg1, reg2 mov reg1, reg2
  8451. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8452. begin
  8453. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8454. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8455. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8456. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8457. TransferUsedRegs(TmpUsedRegs);
  8458. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8459. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8460. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8461. then
  8462. begin
  8463. RemoveCurrentP(p, hp1);
  8464. Result:=true;
  8465. end;
  8466. exit;
  8467. end
  8468. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8469. IsXCHGAcceptable and
  8470. { XCHG doesn't support 8-byte registers }
  8471. (taicpu(p).opsize <> S_B) and
  8472. MatchInstruction(hp1, A_MOV, []) and
  8473. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8474. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8475. GetNextInstruction(hp1, hp2) and
  8476. MatchInstruction(hp2, A_MOV, []) and
  8477. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8478. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8479. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8480. begin
  8481. { mov %reg1,%reg2
  8482. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8483. mov %reg2,%reg3
  8484. (%reg2 not used afterwards)
  8485. Note that xchg takes 3 cycles to execute, and generally mov's take
  8486. only one cycle apiece, but the first two mov's can be executed in
  8487. parallel, only taking 2 cycles overall. Older processors should
  8488. therefore only optimise for size. [Kit]
  8489. }
  8490. TransferUsedRegs(TmpUsedRegs);
  8491. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8492. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8493. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8494. begin
  8495. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8496. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8497. taicpu(hp1).opcode := A_XCHG;
  8498. RemoveCurrentP(p, hp1);
  8499. RemoveInstruction(hp2);
  8500. Result := True;
  8501. Exit;
  8502. end;
  8503. end
  8504. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8505. MatchInstruction(hp1, A_SAR, []) then
  8506. begin
  8507. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8508. begin
  8509. { the use of %edx also covers the opsize being S_L }
  8510. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8511. begin
  8512. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8513. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8514. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8515. begin
  8516. { Change:
  8517. movl %eax,%edx
  8518. sarl $31,%edx
  8519. To:
  8520. cltd
  8521. }
  8522. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8523. RemoveInstruction(hp1);
  8524. taicpu(p).opcode := A_CDQ;
  8525. taicpu(p).opsize := S_NO;
  8526. taicpu(p).clearop(1);
  8527. taicpu(p).clearop(0);
  8528. taicpu(p).ops:=0;
  8529. Result := True;
  8530. end
  8531. else if (cs_opt_size in current_settings.optimizerswitches) and
  8532. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8533. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8534. begin
  8535. { Change:
  8536. movl %edx,%eax
  8537. sarl $31,%edx
  8538. To:
  8539. movl %edx,%eax
  8540. cltd
  8541. Note that this creates a dependency between the two instructions,
  8542. so only perform if optimising for size.
  8543. }
  8544. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8545. taicpu(hp1).opcode := A_CDQ;
  8546. taicpu(hp1).opsize := S_NO;
  8547. taicpu(hp1).clearop(1);
  8548. taicpu(hp1).clearop(0);
  8549. taicpu(hp1).ops:=0;
  8550. end;
  8551. {$ifndef x86_64}
  8552. end
  8553. { Don't bother if CMOV is supported, because a more optimal
  8554. sequence would have been generated for the Abs() intrinsic }
  8555. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8556. { the use of %eax also covers the opsize being S_L }
  8557. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8558. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8559. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8560. GetNextInstruction(hp1, hp2) and
  8561. MatchInstruction(hp2, A_XOR, [S_L]) and
  8562. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8563. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8564. GetNextInstruction(hp2, hp3) and
  8565. MatchInstruction(hp3, A_SUB, [S_L]) and
  8566. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8567. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8568. begin
  8569. { Change:
  8570. movl %eax,%edx
  8571. sarl $31,%eax
  8572. xorl %eax,%edx
  8573. subl %eax,%edx
  8574. (Instruction that uses %edx)
  8575. (%eax deallocated)
  8576. (%edx deallocated)
  8577. To:
  8578. cltd
  8579. xorl %edx,%eax <-- Note the registers have swapped
  8580. subl %edx,%eax
  8581. (Instruction that uses %eax) <-- %eax rather than %edx
  8582. }
  8583. TransferUsedRegs(TmpUsedRegs);
  8584. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8585. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8586. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8587. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8588. begin
  8589. if GetNextInstruction(hp3, hp4) and
  8590. not RegModifiedByInstruction(NR_EDX, hp4) and
  8591. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8592. begin
  8593. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8594. taicpu(p).opcode := A_CDQ;
  8595. taicpu(p).clearop(1);
  8596. taicpu(p).clearop(0);
  8597. taicpu(p).ops:=0;
  8598. RemoveInstruction(hp1);
  8599. taicpu(hp2).loadreg(0, NR_EDX);
  8600. taicpu(hp2).loadreg(1, NR_EAX);
  8601. taicpu(hp3).loadreg(0, NR_EDX);
  8602. taicpu(hp3).loadreg(1, NR_EAX);
  8603. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8604. { Convert references in the following instruction (hp4) from %edx to %eax }
  8605. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8606. with taicpu(hp4).oper[OperIdx]^ do
  8607. case typ of
  8608. top_reg:
  8609. if getsupreg(reg) = RS_EDX then
  8610. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8611. top_ref:
  8612. begin
  8613. if getsupreg(reg) = RS_EDX then
  8614. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8615. if getsupreg(reg) = RS_EDX then
  8616. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8617. end;
  8618. else
  8619. ;
  8620. end;
  8621. end;
  8622. end;
  8623. {$else x86_64}
  8624. end;
  8625. end
  8626. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8627. { the use of %rdx also covers the opsize being S_Q }
  8628. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8629. begin
  8630. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8631. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8632. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8633. begin
  8634. { Change:
  8635. movq %rax,%rdx
  8636. sarq $63,%rdx
  8637. To:
  8638. cqto
  8639. }
  8640. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8641. RemoveInstruction(hp1);
  8642. taicpu(p).opcode := A_CQO;
  8643. taicpu(p).opsize := S_NO;
  8644. taicpu(p).clearop(1);
  8645. taicpu(p).clearop(0);
  8646. taicpu(p).ops:=0;
  8647. Result := True;
  8648. end
  8649. else if (cs_opt_size in current_settings.optimizerswitches) and
  8650. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8651. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8652. begin
  8653. { Change:
  8654. movq %rdx,%rax
  8655. sarq $63,%rdx
  8656. To:
  8657. movq %rdx,%rax
  8658. cqto
  8659. Note that this creates a dependency between the two instructions,
  8660. so only perform if optimising for size.
  8661. }
  8662. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8663. taicpu(hp1).opcode := A_CQO;
  8664. taicpu(hp1).opsize := S_NO;
  8665. taicpu(hp1).clearop(1);
  8666. taicpu(hp1).clearop(0);
  8667. taicpu(hp1).ops:=0;
  8668. {$endif x86_64}
  8669. end;
  8670. end;
  8671. end
  8672. else if MatchInstruction(hp1, A_MOV, []) and
  8673. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8674. { Though "GetNextInstruction" could be factored out, along with
  8675. the instructions that depend on hp2, it is an expensive call that
  8676. should be delayed for as long as possible, hence we do cheaper
  8677. checks first that are likely to be False. [Kit] }
  8678. begin
  8679. if (
  8680. (
  8681. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8682. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8683. (
  8684. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8685. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8686. )
  8687. ) or
  8688. (
  8689. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8690. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8691. (
  8692. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8693. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8694. )
  8695. )
  8696. ) and
  8697. GetNextInstruction(hp1, hp2) and
  8698. MatchInstruction(hp2, A_SAR, []) and
  8699. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8700. begin
  8701. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8702. begin
  8703. { Change:
  8704. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8705. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8706. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8707. To:
  8708. movl r/m,%eax <- Note the change in register
  8709. cltd
  8710. }
  8711. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8712. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8713. taicpu(p).loadreg(1, NR_EAX);
  8714. taicpu(hp1).opcode := A_CDQ;
  8715. taicpu(hp1).clearop(1);
  8716. taicpu(hp1).clearop(0);
  8717. taicpu(hp1).ops:=0;
  8718. RemoveInstruction(hp2);
  8719. (*
  8720. {$ifdef x86_64}
  8721. end
  8722. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8723. { This code sequence does not get generated - however it might become useful
  8724. if and when 128-bit signed integer types make an appearance, so the code
  8725. is kept here for when it is eventually needed. [Kit] }
  8726. (
  8727. (
  8728. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8729. (
  8730. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8731. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8732. )
  8733. ) or
  8734. (
  8735. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8736. (
  8737. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8738. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8739. )
  8740. )
  8741. ) and
  8742. GetNextInstruction(hp1, hp2) and
  8743. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8744. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8745. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8746. begin
  8747. { Change:
  8748. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8749. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8750. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8751. To:
  8752. movq r/m,%rax <- Note the change in register
  8753. cqto
  8754. }
  8755. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8756. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8757. taicpu(p).loadreg(1, NR_RAX);
  8758. taicpu(hp1).opcode := A_CQO;
  8759. taicpu(hp1).clearop(1);
  8760. taicpu(hp1).clearop(0);
  8761. taicpu(hp1).ops:=0;
  8762. RemoveInstruction(hp2);
  8763. {$endif x86_64}
  8764. *)
  8765. end;
  8766. end;
  8767. {$ifdef x86_64}
  8768. end
  8769. else if (taicpu(p).opsize = S_L) and
  8770. (taicpu(p).oper[1]^.typ = top_reg) and
  8771. (
  8772. MatchInstruction(hp1, A_MOV,[]) and
  8773. (taicpu(hp1).opsize = S_L) and
  8774. (taicpu(hp1).oper[1]^.typ = top_reg)
  8775. ) and (
  8776. GetNextInstruction(hp1, hp2) and
  8777. (tai(hp2).typ=ait_instruction) and
  8778. (taicpu(hp2).opsize = S_Q) and
  8779. (
  8780. (
  8781. MatchInstruction(hp2, A_ADD,[]) and
  8782. (taicpu(hp2).opsize = S_Q) and
  8783. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8784. (
  8785. (
  8786. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8787. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8788. ) or (
  8789. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8790. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8791. )
  8792. )
  8793. ) or (
  8794. MatchInstruction(hp2, A_LEA,[]) and
  8795. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8796. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8797. (
  8798. (
  8799. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8800. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8801. ) or (
  8802. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8803. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8804. )
  8805. ) and (
  8806. (
  8807. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8808. ) or (
  8809. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8810. )
  8811. )
  8812. )
  8813. )
  8814. ) and (
  8815. GetNextInstruction(hp2, hp3) and
  8816. MatchInstruction(hp3, A_SHR,[]) and
  8817. (taicpu(hp3).opsize = S_Q) and
  8818. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8819. (taicpu(hp3).oper[0]^.val = 1) and
  8820. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8821. ) then
  8822. begin
  8823. { Change movl x, reg1d movl x, reg1d
  8824. movl y, reg2d movl y, reg2d
  8825. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8826. shrq $1, reg1q shrq $1, reg1q
  8827. ( reg1d and reg2d can be switched around in the first two instructions )
  8828. To movl x, reg1d
  8829. addl y, reg1d
  8830. rcrl $1, reg1d
  8831. This corresponds to the common expression (x + y) shr 1, where
  8832. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  8833. smaller code, but won't account for x + y causing an overflow). [Kit]
  8834. }
  8835. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  8836. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8837. { Change first MOV command to have the same register as the final output }
  8838. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  8839. else
  8840. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  8841. { Change second MOV command to an ADD command. This is easier than
  8842. converting the existing command because it means we don't have to
  8843. touch 'y', which might be a complicated reference, and also the
  8844. fact that the third command might either be ADD or LEA. [Kit] }
  8845. taicpu(hp1).opcode := A_ADD;
  8846. { Delete old ADD/LEA instruction }
  8847. RemoveInstruction(hp2);
  8848. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  8849. taicpu(hp3).opcode := A_RCR;
  8850. taicpu(hp3).changeopsize(S_L);
  8851. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  8852. {$endif x86_64}
  8853. end;
  8854. if FuncMov2Func(p, hp1) then
  8855. begin
  8856. Result := True;
  8857. Exit;
  8858. end;
  8859. end;
  8860. {$push}
  8861. {$q-}{$r-}
  8862. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  8863. var
  8864. ThisReg: TRegister;
  8865. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  8866. TargetSubReg: TSubRegister;
  8867. hp1, hp2: tai;
  8868. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  8869. { Store list of found instructions so we don't have to call
  8870. GetNextInstructionUsingReg multiple times }
  8871. InstrList: array of taicpu;
  8872. InstrMax, Index: Integer;
  8873. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  8874. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  8875. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  8876. WorkingValue: TCgInt;
  8877. PreMessage: string;
  8878. { Data flow analysis }
  8879. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  8880. BitwiseOnly, OrXorUsed,
  8881. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  8882. function CheckOverflowConditions: Boolean;
  8883. begin
  8884. Result := True;
  8885. if (TestValSignedMax > SignedUpperLimit) then
  8886. UpperSignedOverflow := True;
  8887. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  8888. LowerSignedOverflow := True;
  8889. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  8890. LowerUnsignedOverflow := True;
  8891. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  8892. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  8893. begin
  8894. { Absolute overflow }
  8895. Result := False;
  8896. Exit;
  8897. end;
  8898. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  8899. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8900. ShiftDownOverflow := True;
  8901. if (TestValMin < 0) or (TestValMax < 0) then
  8902. begin
  8903. LowerUnsignedOverflow := True;
  8904. UpperUnsignedOverflow := True;
  8905. end;
  8906. end;
  8907. function AdjustInitialLoadAndSize: Boolean;
  8908. begin
  8909. Result := False;
  8910. if not p_removed then
  8911. begin
  8912. if TargetSize = MinSize then
  8913. begin
  8914. { Convert the input MOVZX to a MOV }
  8915. if (taicpu(p).oper[0]^.typ = top_reg) and
  8916. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8917. begin
  8918. { Or remove it completely! }
  8919. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8920. RemoveCurrentP(p);
  8921. p_removed := True;
  8922. end
  8923. else
  8924. begin
  8925. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8926. taicpu(p).opcode := A_MOV;
  8927. taicpu(p).oper[1]^.reg := ThisReg;
  8928. taicpu(p).opsize := TargetSize;
  8929. end;
  8930. Result := True;
  8931. end
  8932. else if TargetSize <> MaxSize then
  8933. begin
  8934. case MaxSize of
  8935. S_L:
  8936. if TargetSize = S_W then
  8937. begin
  8938. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8939. taicpu(p).opsize := S_BW;
  8940. taicpu(p).oper[1]^.reg := ThisReg;
  8941. Result := True;
  8942. end
  8943. else
  8944. InternalError(2020112341);
  8945. S_W:
  8946. if TargetSize = S_L then
  8947. begin
  8948. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8949. taicpu(p).opsize := S_BL;
  8950. taicpu(p).oper[1]^.reg := ThisReg;
  8951. Result := True;
  8952. end
  8953. else
  8954. InternalError(2020112342);
  8955. else
  8956. ;
  8957. end;
  8958. end
  8959. else if not hp1_removed and not RegInUse then
  8960. begin
  8961. { If we have something like:
  8962. movzbl (oper),%regd
  8963. add x, %regd
  8964. movzbl %regb, %regd
  8965. We can reduce the register size to the input of the final
  8966. movzbl instruction. Overflows won't have any effect.
  8967. }
  8968. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8969. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8970. begin
  8971. TargetSize := S_B;
  8972. setsubreg(ThisReg, R_SUBL);
  8973. Result := True;
  8974. end
  8975. else if (taicpu(p).opsize = S_WL) and
  8976. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8977. begin
  8978. TargetSize := S_W;
  8979. setsubreg(ThisReg, R_SUBW);
  8980. Result := True;
  8981. end;
  8982. if Result then
  8983. begin
  8984. { Convert the input MOVZX to a MOV }
  8985. if (taicpu(p).oper[0]^.typ = top_reg) and
  8986. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8987. begin
  8988. { Or remove it completely! }
  8989. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8990. RemoveCurrentP(p);
  8991. p_removed := True;
  8992. end
  8993. else
  8994. begin
  8995. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8996. taicpu(p).opcode := A_MOV;
  8997. taicpu(p).oper[1]^.reg := ThisReg;
  8998. taicpu(p).opsize := TargetSize;
  8999. end;
  9000. end;
  9001. end;
  9002. end;
  9003. end;
  9004. procedure AdjustFinalLoad;
  9005. begin
  9006. if not LowerUnsignedOverflow then
  9007. begin
  9008. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9009. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9010. begin
  9011. { Convert the output MOVZX to a MOV }
  9012. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9013. begin
  9014. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9015. if (MinSize = S_B) or
  9016. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9017. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9018. begin
  9019. { Remove it completely! }
  9020. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9021. { Be careful; if p = hp1 and p was also removed, p
  9022. will become a dangling pointer }
  9023. if p = hp1 then
  9024. begin
  9025. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9026. p_removed := True;
  9027. end
  9028. else
  9029. RemoveInstruction(hp1);
  9030. hp1_removed := True;
  9031. end;
  9032. end
  9033. else
  9034. begin
  9035. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9036. taicpu(hp1).opcode := A_MOV;
  9037. taicpu(hp1).oper[0]^.reg := ThisReg;
  9038. taicpu(hp1).opsize := TargetSize;
  9039. end;
  9040. end
  9041. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9042. begin
  9043. { Need to change the size of the output }
  9044. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9045. taicpu(hp1).oper[0]^.reg := ThisReg;
  9046. taicpu(hp1).opsize := S_BL;
  9047. end;
  9048. end;
  9049. end;
  9050. function CompressInstructions: Boolean;
  9051. var
  9052. LocalIndex: Integer;
  9053. begin
  9054. Result := False;
  9055. { The objective here is to try to find a combination that
  9056. removes one of the MOV/Z instructions. }
  9057. if (
  9058. (taicpu(p).oper[0]^.typ <> top_reg) or
  9059. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9060. ) and
  9061. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9062. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9063. begin
  9064. { Make a preference to remove the second MOVZX instruction }
  9065. case taicpu(hp1).opsize of
  9066. S_BL, S_WL:
  9067. begin
  9068. TargetSize := S_L;
  9069. TargetSubReg := R_SUBD;
  9070. end;
  9071. S_BW:
  9072. begin
  9073. TargetSize := S_W;
  9074. TargetSubReg := R_SUBW;
  9075. end;
  9076. else
  9077. InternalError(2020112302);
  9078. end;
  9079. end
  9080. else
  9081. begin
  9082. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9083. begin
  9084. { Exceeded lower bound but not upper bound }
  9085. TargetSize := MaxSize;
  9086. end
  9087. else if not LowerUnsignedOverflow then
  9088. begin
  9089. { Size didn't exceed lower bound }
  9090. TargetSize := MinSize;
  9091. end
  9092. else
  9093. Exit;
  9094. end;
  9095. case TargetSize of
  9096. S_B:
  9097. TargetSubReg := R_SUBL;
  9098. S_W:
  9099. TargetSubReg := R_SUBW;
  9100. S_L:
  9101. TargetSubReg := R_SUBD;
  9102. else
  9103. InternalError(2020112350);
  9104. end;
  9105. { Update the register to its new size }
  9106. setsubreg(ThisReg, TargetSubReg);
  9107. RegInUse := False;
  9108. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9109. begin
  9110. { Check to see if the active register is used afterwards;
  9111. if not, we can change it and make a saving. }
  9112. TransferUsedRegs(TmpUsedRegs);
  9113. { The target register may be marked as in use to cross
  9114. a jump to a distant label, so exclude it }
  9115. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9116. hp2 := p;
  9117. repeat
  9118. { Explicitly check for the excluded register (don't include the first
  9119. instruction as it may be reading from here }
  9120. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9121. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9122. begin
  9123. RegInUse := True;
  9124. Break;
  9125. end;
  9126. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9127. if not GetNextInstruction(hp2, hp2) then
  9128. InternalError(2020112340);
  9129. until (hp2 = hp1);
  9130. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9131. { We might still be able to get away with this }
  9132. RegInUse := not
  9133. (
  9134. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9135. (hp2.typ = ait_instruction) and
  9136. (
  9137. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9138. instruction that doesn't actually contain ThisReg }
  9139. (cs_opt_level3 in current_settings.optimizerswitches) or
  9140. RegInInstruction(ThisReg, hp2)
  9141. ) and
  9142. RegLoadedWithNewValue(ThisReg, hp2)
  9143. );
  9144. if not RegInUse then
  9145. begin
  9146. { Force the register size to the same as this instruction so it can be removed}
  9147. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9148. begin
  9149. TargetSize := S_L;
  9150. TargetSubReg := R_SUBD;
  9151. end
  9152. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9153. begin
  9154. TargetSize := S_W;
  9155. TargetSubReg := R_SUBW;
  9156. end;
  9157. ThisReg := taicpu(hp1).oper[1]^.reg;
  9158. setsubreg(ThisReg, TargetSubReg);
  9159. RegChanged := True;
  9160. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9161. TransferUsedRegs(TmpUsedRegs);
  9162. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9163. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9164. if p = hp1 then
  9165. begin
  9166. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9167. p_removed := True;
  9168. end
  9169. else
  9170. RemoveInstruction(hp1);
  9171. hp1_removed := True;
  9172. { Instruction will become "mov %reg,%reg" }
  9173. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9174. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9175. begin
  9176. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9177. RemoveCurrentP(p);
  9178. p_removed := True;
  9179. end
  9180. else
  9181. taicpu(p).oper[1]^.reg := ThisReg;
  9182. Result := True;
  9183. end
  9184. else
  9185. begin
  9186. if TargetSize <> MaxSize then
  9187. begin
  9188. { Since the register is in use, we have to force it to
  9189. MaxSize otherwise part of it may become undefined later on }
  9190. TargetSize := MaxSize;
  9191. case TargetSize of
  9192. S_B:
  9193. TargetSubReg := R_SUBL;
  9194. S_W:
  9195. TargetSubReg := R_SUBW;
  9196. S_L:
  9197. TargetSubReg := R_SUBD;
  9198. else
  9199. InternalError(2020112351);
  9200. end;
  9201. setsubreg(ThisReg, TargetSubReg);
  9202. end;
  9203. AdjustFinalLoad;
  9204. end;
  9205. end
  9206. else
  9207. AdjustFinalLoad;
  9208. Result := AdjustInitialLoadAndSize or Result;
  9209. { Now go through every instruction we found and change the
  9210. size. If TargetSize = MaxSize, then almost no changes are
  9211. needed and Result can remain False if it hasn't been set
  9212. yet.
  9213. If RegChanged is True, then the register requires changing
  9214. and so the point about TargetSize = MaxSize doesn't apply. }
  9215. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9216. begin
  9217. for LocalIndex := 0 to InstrMax do
  9218. begin
  9219. { If p_removed is true, then the original MOV/Z was removed
  9220. and removing the AND instruction may not be safe if it
  9221. appears first }
  9222. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9223. InternalError(2020112310);
  9224. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9225. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9226. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9227. InstrList[LocalIndex].opsize := TargetSize;
  9228. end;
  9229. Result := True;
  9230. end;
  9231. end;
  9232. begin
  9233. Result := False;
  9234. p_removed := False;
  9235. hp1_removed := False;
  9236. ThisReg := taicpu(p).oper[1]^.reg;
  9237. { Check for:
  9238. movs/z ###,%ecx (or %cx or %rcx)
  9239. ...
  9240. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9241. (dealloc %ecx)
  9242. Change to:
  9243. mov ###,%cl (if ### = %cl, then remove completely)
  9244. ...
  9245. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9246. }
  9247. if (getsupreg(ThisReg) = RS_ECX) and
  9248. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9249. (hp1.typ = ait_instruction) and
  9250. (
  9251. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9252. instruction that doesn't actually contain ECX }
  9253. (cs_opt_level3 in current_settings.optimizerswitches) or
  9254. RegInInstruction(NR_ECX, hp1) or
  9255. (
  9256. { It's common for the shift/rotate's read/write register to be
  9257. initialised in between, so under -O2 and under, search ahead
  9258. one more instruction
  9259. }
  9260. GetNextInstruction(hp1, hp1) and
  9261. (hp1.typ = ait_instruction) and
  9262. RegInInstruction(NR_ECX, hp1)
  9263. )
  9264. ) and
  9265. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9266. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9267. begin
  9268. TransferUsedRegs(TmpUsedRegs);
  9269. hp2 := p;
  9270. repeat
  9271. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9272. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9273. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9274. begin
  9275. case taicpu(p).opsize of
  9276. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9277. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9278. begin
  9279. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9280. RemoveCurrentP(p);
  9281. end
  9282. else
  9283. begin
  9284. taicpu(p).opcode := A_MOV;
  9285. taicpu(p).opsize := S_B;
  9286. taicpu(p).oper[1]^.reg := NR_CL;
  9287. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9288. end;
  9289. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9290. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9291. begin
  9292. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9293. RemoveCurrentP(p);
  9294. end
  9295. else
  9296. begin
  9297. taicpu(p).opcode := A_MOV;
  9298. taicpu(p).opsize := S_W;
  9299. taicpu(p).oper[1]^.reg := NR_CX;
  9300. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9301. end;
  9302. {$ifdef x86_64}
  9303. S_LQ:
  9304. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9305. begin
  9306. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9307. RemoveCurrentP(p);
  9308. end
  9309. else
  9310. begin
  9311. taicpu(p).opcode := A_MOV;
  9312. taicpu(p).opsize := S_L;
  9313. taicpu(p).oper[1]^.reg := NR_ECX;
  9314. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9315. end;
  9316. {$endif x86_64}
  9317. else
  9318. InternalError(2021120401);
  9319. end;
  9320. Result := True;
  9321. Exit;
  9322. end;
  9323. end;
  9324. { This is anything but quick! }
  9325. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9326. Exit;
  9327. SetLength(InstrList, 0);
  9328. InstrMax := -1;
  9329. case taicpu(p).opsize of
  9330. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9331. begin
  9332. {$if defined(i386) or defined(i8086)}
  9333. { If the target size is 8-bit, make sure we can actually encode it }
  9334. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9335. Exit;
  9336. {$endif i386 or i8086}
  9337. LowerLimit := $FF;
  9338. SignedLowerLimit := $7F;
  9339. SignedLowerLimitBottom := -128;
  9340. MinSize := S_B;
  9341. if taicpu(p).opsize = S_BW then
  9342. begin
  9343. MaxSize := S_W;
  9344. UpperLimit := $FFFF;
  9345. SignedUpperLimit := $7FFF;
  9346. SignedUpperLimitBottom := -32768;
  9347. end
  9348. else
  9349. begin
  9350. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9351. MaxSize := S_L;
  9352. UpperLimit := $FFFFFFFF;
  9353. SignedUpperLimit := $7FFFFFFF;
  9354. SignedUpperLimitBottom := -2147483648;
  9355. end;
  9356. end;
  9357. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9358. begin
  9359. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9360. LowerLimit := $FFFF;
  9361. SignedLowerLimit := $7FFF;
  9362. SignedLowerLimitBottom := -32768;
  9363. UpperLimit := $FFFFFFFF;
  9364. SignedUpperLimit := $7FFFFFFF;
  9365. SignedUpperLimitBottom := -2147483648;
  9366. MinSize := S_W;
  9367. MaxSize := S_L;
  9368. end;
  9369. {$ifdef x86_64}
  9370. S_LQ:
  9371. begin
  9372. { Both the lower and upper limits are set to 32-bit. If a limit
  9373. is breached, then optimisation is impossible }
  9374. LowerLimit := $FFFFFFFF;
  9375. SignedLowerLimit := $7FFFFFFF;
  9376. SignedLowerLimitBottom := -2147483648;
  9377. UpperLimit := $FFFFFFFF;
  9378. SignedUpperLimit := $7FFFFFFF;
  9379. SignedUpperLimitBottom := -2147483648;
  9380. MinSize := S_L;
  9381. MaxSize := S_L;
  9382. end;
  9383. {$endif x86_64}
  9384. else
  9385. InternalError(2020112301);
  9386. end;
  9387. TestValMin := 0;
  9388. TestValMax := LowerLimit;
  9389. TestValSignedMax := SignedLowerLimit;
  9390. TryShiftDownLimit := LowerLimit;
  9391. TryShiftDown := S_NO;
  9392. ShiftDownOverflow := False;
  9393. RegChanged := False;
  9394. BitwiseOnly := True;
  9395. OrXorUsed := False;
  9396. UpperSignedOverflow := False;
  9397. LowerSignedOverflow := False;
  9398. UpperUnsignedOverflow := False;
  9399. LowerUnsignedOverflow := False;
  9400. hp1 := p;
  9401. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9402. (hp1.typ = ait_instruction) and
  9403. (
  9404. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9405. instruction that doesn't actually contain ThisReg }
  9406. (cs_opt_level3 in current_settings.optimizerswitches) or
  9407. { This allows this Movx optimisation to work through the SETcc instructions
  9408. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9409. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9410. skip over these SETcc instructions). }
  9411. (taicpu(hp1).opcode = A_SETcc) or
  9412. RegInInstruction(ThisReg, hp1)
  9413. ) do
  9414. begin
  9415. case taicpu(hp1).opcode of
  9416. A_INC,A_DEC:
  9417. begin
  9418. { Has to be an exact match on the register }
  9419. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9420. Break;
  9421. if taicpu(hp1).opcode = A_INC then
  9422. begin
  9423. Inc(TestValMin);
  9424. Inc(TestValMax);
  9425. Inc(TestValSignedMax);
  9426. end
  9427. else
  9428. begin
  9429. Dec(TestValMin);
  9430. Dec(TestValMax);
  9431. Dec(TestValSignedMax);
  9432. end;
  9433. end;
  9434. A_TEST, A_CMP:
  9435. begin
  9436. if (
  9437. { Too high a risk of non-linear behaviour that breaks DFA
  9438. here, unless it's cmp $0,%reg, which is equivalent to
  9439. test %reg,%reg }
  9440. OrXorUsed and
  9441. (taicpu(hp1).opcode = A_CMP) and
  9442. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9443. ) or
  9444. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9445. { Has to be an exact match on the register }
  9446. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9447. (
  9448. { Permit "test %reg,%reg" }
  9449. (taicpu(hp1).opcode = A_TEST) and
  9450. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9451. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9452. ) or
  9453. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9454. { Make sure the comparison value is not smaller than the
  9455. smallest allowed signed value for the minimum size (e.g.
  9456. -128 for 8-bit) }
  9457. not (
  9458. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9459. { Is it in the negative range? }
  9460. (
  9461. (taicpu(hp1).oper[0]^.val < 0) and
  9462. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9463. )
  9464. ) then
  9465. Break;
  9466. { Check to see if the active register is used afterwards }
  9467. TransferUsedRegs(TmpUsedRegs);
  9468. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9469. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9470. begin
  9471. { Make sure the comparison or any previous instructions
  9472. hasn't pushed the test values outside of the range of
  9473. MinSize }
  9474. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9475. begin
  9476. { Exceeded lower bound but not upper bound }
  9477. Exit;
  9478. end
  9479. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9480. begin
  9481. { Size didn't exceed lower bound }
  9482. TargetSize := MinSize;
  9483. end
  9484. else
  9485. Break;
  9486. case TargetSize of
  9487. S_B:
  9488. TargetSubReg := R_SUBL;
  9489. S_W:
  9490. TargetSubReg := R_SUBW;
  9491. S_L:
  9492. TargetSubReg := R_SUBD;
  9493. else
  9494. InternalError(2021051002);
  9495. end;
  9496. if TargetSize <> MaxSize then
  9497. begin
  9498. { Update the register to its new size }
  9499. setsubreg(ThisReg, TargetSubReg);
  9500. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9501. taicpu(hp1).oper[1]^.reg := ThisReg;
  9502. taicpu(hp1).opsize := TargetSize;
  9503. { Convert the input MOVZX to a MOV if necessary }
  9504. AdjustInitialLoadAndSize;
  9505. if (InstrMax >= 0) then
  9506. begin
  9507. for Index := 0 to InstrMax do
  9508. begin
  9509. { If p_removed is true, then the original MOV/Z was removed
  9510. and removing the AND instruction may not be safe if it
  9511. appears first }
  9512. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9513. InternalError(2020112311);
  9514. if InstrList[Index].oper[0]^.typ = top_reg then
  9515. InstrList[Index].oper[0]^.reg := ThisReg;
  9516. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9517. InstrList[Index].opsize := MinSize;
  9518. end;
  9519. end;
  9520. Result := True;
  9521. end;
  9522. Exit;
  9523. end;
  9524. end;
  9525. A_SETcc:
  9526. begin
  9527. { This allows this Movx optimisation to work through the SETcc instructions
  9528. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9529. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9530. skip over these SETcc instructions). }
  9531. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9532. { Of course, break out if the current register is used }
  9533. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9534. Break
  9535. else
  9536. { We must use Continue so the instruction doesn't get added
  9537. to InstrList }
  9538. Continue;
  9539. end;
  9540. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9541. begin
  9542. if
  9543. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9544. { Has to be an exact match on the register }
  9545. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9546. (
  9547. (
  9548. (taicpu(hp1).oper[0]^.typ = top_const) and
  9549. (
  9550. (
  9551. (taicpu(hp1).opcode = A_SHL) and
  9552. (
  9553. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9554. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9555. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9556. )
  9557. ) or (
  9558. (taicpu(hp1).opcode <> A_SHL) and
  9559. (
  9560. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9561. { Is it in the negative range? }
  9562. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9563. )
  9564. )
  9565. )
  9566. ) or (
  9567. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9568. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9569. )
  9570. ) then
  9571. Break;
  9572. { Only process OR and XOR if there are only bitwise operations,
  9573. since otherwise they can too easily fool the data flow
  9574. analysis (they can cause non-linear behaviour) }
  9575. case taicpu(hp1).opcode of
  9576. A_ADD:
  9577. begin
  9578. if OrXorUsed then
  9579. { Too high a risk of non-linear behaviour that breaks DFA here }
  9580. Break
  9581. else
  9582. BitwiseOnly := False;
  9583. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9584. begin
  9585. TestValMin := TestValMin * 2;
  9586. TestValMax := TestValMax * 2;
  9587. TestValSignedMax := TestValSignedMax * 2;
  9588. end
  9589. else
  9590. begin
  9591. WorkingValue := taicpu(hp1).oper[0]^.val;
  9592. TestValMin := TestValMin + WorkingValue;
  9593. TestValMax := TestValMax + WorkingValue;
  9594. TestValSignedMax := TestValSignedMax + WorkingValue;
  9595. end;
  9596. end;
  9597. A_SUB:
  9598. begin
  9599. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9600. begin
  9601. TestValMin := 0;
  9602. TestValMax := 0;
  9603. TestValSignedMax := 0;
  9604. end
  9605. else
  9606. begin
  9607. if OrXorUsed then
  9608. { Too high a risk of non-linear behaviour that breaks DFA here }
  9609. Break
  9610. else
  9611. BitwiseOnly := False;
  9612. WorkingValue := taicpu(hp1).oper[0]^.val;
  9613. TestValMin := TestValMin - WorkingValue;
  9614. TestValMax := TestValMax - WorkingValue;
  9615. TestValSignedMax := TestValSignedMax - WorkingValue;
  9616. end;
  9617. end;
  9618. A_AND:
  9619. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9620. begin
  9621. { we might be able to go smaller if AND appears first }
  9622. if InstrMax = -1 then
  9623. case MinSize of
  9624. S_B:
  9625. ;
  9626. S_W:
  9627. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9628. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9629. begin
  9630. TryShiftDown := S_B;
  9631. TryShiftDownLimit := $FF;
  9632. end;
  9633. S_L:
  9634. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9635. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9636. begin
  9637. TryShiftDown := S_B;
  9638. TryShiftDownLimit := $FF;
  9639. end
  9640. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9641. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9642. begin
  9643. TryShiftDown := S_W;
  9644. TryShiftDownLimit := $FFFF;
  9645. end;
  9646. else
  9647. InternalError(2020112320);
  9648. end;
  9649. WorkingValue := taicpu(hp1).oper[0]^.val;
  9650. TestValMin := TestValMin and WorkingValue;
  9651. TestValMax := TestValMax and WorkingValue;
  9652. TestValSignedMax := TestValSignedMax and WorkingValue;
  9653. end;
  9654. A_OR:
  9655. begin
  9656. if not BitwiseOnly then
  9657. Break;
  9658. OrXorUsed := True;
  9659. WorkingValue := taicpu(hp1).oper[0]^.val;
  9660. TestValMin := TestValMin or WorkingValue;
  9661. TestValMax := TestValMax or WorkingValue;
  9662. TestValSignedMax := TestValSignedMax or WorkingValue;
  9663. end;
  9664. A_XOR:
  9665. begin
  9666. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9667. begin
  9668. TestValMin := 0;
  9669. TestValMax := 0;
  9670. TestValSignedMax := 0;
  9671. end
  9672. else
  9673. begin
  9674. if not BitwiseOnly then
  9675. Break;
  9676. OrXorUsed := True;
  9677. WorkingValue := taicpu(hp1).oper[0]^.val;
  9678. TestValMin := TestValMin xor WorkingValue;
  9679. TestValMax := TestValMax xor WorkingValue;
  9680. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9681. end;
  9682. end;
  9683. A_SHL:
  9684. begin
  9685. BitwiseOnly := False;
  9686. WorkingValue := taicpu(hp1).oper[0]^.val;
  9687. TestValMin := TestValMin shl WorkingValue;
  9688. TestValMax := TestValMax shl WorkingValue;
  9689. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9690. end;
  9691. A_SHR,
  9692. { The first instruction was MOVZX, so the value won't be negative }
  9693. A_SAR:
  9694. begin
  9695. if InstrMax <> -1 then
  9696. BitwiseOnly := False
  9697. else
  9698. { we might be able to go smaller if SHR appears first }
  9699. case MinSize of
  9700. S_B:
  9701. ;
  9702. S_W:
  9703. if (taicpu(hp1).oper[0]^.val >= 8) then
  9704. begin
  9705. TryShiftDown := S_B;
  9706. TryShiftDownLimit := $FF;
  9707. TryShiftDownSignedLimit := $7F;
  9708. TryShiftDownSignedLimitLower := -128;
  9709. end;
  9710. S_L:
  9711. if (taicpu(hp1).oper[0]^.val >= 24) then
  9712. begin
  9713. TryShiftDown := S_B;
  9714. TryShiftDownLimit := $FF;
  9715. TryShiftDownSignedLimit := $7F;
  9716. TryShiftDownSignedLimitLower := -128;
  9717. end
  9718. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9719. begin
  9720. TryShiftDown := S_W;
  9721. TryShiftDownLimit := $FFFF;
  9722. TryShiftDownSignedLimit := $7FFF;
  9723. TryShiftDownSignedLimitLower := -32768;
  9724. end;
  9725. else
  9726. InternalError(2020112321);
  9727. end;
  9728. WorkingValue := taicpu(hp1).oper[0]^.val;
  9729. if taicpu(hp1).opcode = A_SAR then
  9730. begin
  9731. TestValMin := SarInt64(TestValMin, WorkingValue);
  9732. TestValMax := SarInt64(TestValMax, WorkingValue);
  9733. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9734. end
  9735. else
  9736. begin
  9737. TestValMin := TestValMin shr WorkingValue;
  9738. TestValMax := TestValMax shr WorkingValue;
  9739. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9740. end;
  9741. end;
  9742. else
  9743. InternalError(2020112303);
  9744. end;
  9745. end;
  9746. (*
  9747. A_IMUL:
  9748. case taicpu(hp1).ops of
  9749. 2:
  9750. begin
  9751. if not MatchOpType(hp1, top_reg, top_reg) or
  9752. { Has to be an exact match on the register }
  9753. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9754. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9755. Break;
  9756. TestValMin := TestValMin * TestValMin;
  9757. TestValMax := TestValMax * TestValMax;
  9758. TestValSignedMax := TestValSignedMax * TestValMax;
  9759. end;
  9760. 3:
  9761. begin
  9762. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9763. { Has to be an exact match on the register }
  9764. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9765. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9766. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9767. { Is it in the negative range? }
  9768. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9769. Break;
  9770. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9771. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9772. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9773. end;
  9774. else
  9775. Break;
  9776. end;
  9777. A_IDIV:
  9778. case taicpu(hp1).ops of
  9779. 3:
  9780. begin
  9781. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9782. { Has to be an exact match on the register }
  9783. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9784. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9785. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9786. { Is it in the negative range? }
  9787. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9788. Break;
  9789. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9790. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9791. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9792. end;
  9793. else
  9794. Break;
  9795. end;
  9796. *)
  9797. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9798. begin
  9799. { If there are no instructions in between, then we might be able to make a saving }
  9800. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9801. Break;
  9802. { We have something like:
  9803. movzbw %dl,%dx
  9804. ...
  9805. movswl %dx,%edx
  9806. Change the latter to a zero-extension then enter the
  9807. A_MOVZX case branch.
  9808. }
  9809. {$ifdef x86_64}
  9810. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9811. begin
  9812. { this becomes a zero extension from 32-bit to 64-bit, but
  9813. the upper 32 bits are already zero, so just delete the
  9814. instruction }
  9815. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9816. RemoveInstruction(hp1);
  9817. Result := True;
  9818. Exit;
  9819. end
  9820. else
  9821. {$endif x86_64}
  9822. begin
  9823. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9824. taicpu(hp1).opcode := A_MOVZX;
  9825. {$ifdef x86_64}
  9826. case taicpu(hp1).opsize of
  9827. S_BQ:
  9828. begin
  9829. taicpu(hp1).opsize := S_BL;
  9830. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9831. end;
  9832. S_WQ:
  9833. begin
  9834. taicpu(hp1).opsize := S_WL;
  9835. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9836. end;
  9837. S_LQ:
  9838. begin
  9839. taicpu(hp1).opcode := A_MOV;
  9840. taicpu(hp1).opsize := S_L;
  9841. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9842. { In this instance, we need to break out because the
  9843. instruction is no longer MOVZX or MOVSXD }
  9844. Result := True;
  9845. Exit;
  9846. end;
  9847. else
  9848. ;
  9849. end;
  9850. {$endif x86_64}
  9851. Result := CompressInstructions;
  9852. Exit;
  9853. end;
  9854. end;
  9855. A_MOVZX:
  9856. begin
  9857. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  9858. Break;
  9859. if (InstrMax = -1) then
  9860. begin
  9861. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  9862. begin
  9863. { Optimise around i40003 }
  9864. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  9865. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  9866. {$ifndef x86_64}
  9867. and (
  9868. (taicpu(p).oper[0]^.typ <> top_reg) or
  9869. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  9870. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  9871. )
  9872. {$endif not x86_64}
  9873. then
  9874. begin
  9875. if (taicpu(p).oper[0]^.typ = top_reg) then
  9876. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  9877. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  9878. taicpu(p).opsize := S_BL;
  9879. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  9880. RemoveInstruction(hp1);
  9881. Result := True;
  9882. Exit;
  9883. end;
  9884. end
  9885. else
  9886. begin
  9887. { Will return false if the second parameter isn't ThisReg
  9888. (can happen on -O2 and under) }
  9889. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9890. begin
  9891. { The two MOVZX instructions are adjacent, so remove the first one }
  9892. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  9893. RemoveCurrentP(p);
  9894. Result := True;
  9895. Exit;
  9896. end;
  9897. Break;
  9898. end;
  9899. end;
  9900. Result := CompressInstructions;
  9901. Exit;
  9902. end;
  9903. else
  9904. { This includes ADC, SBB and IDIV }
  9905. Break;
  9906. end;
  9907. if not CheckOverflowConditions then
  9908. Break;
  9909. { Contains highest index (so instruction count - 1) }
  9910. Inc(InstrMax);
  9911. if InstrMax > High(InstrList) then
  9912. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9913. InstrList[InstrMax] := taicpu(hp1);
  9914. end;
  9915. end;
  9916. {$pop}
  9917. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  9918. var
  9919. hp1 : tai;
  9920. begin
  9921. Result:=false;
  9922. if (taicpu(p).ops >= 2) and
  9923. ((taicpu(p).oper[0]^.typ = top_const) or
  9924. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  9925. (taicpu(p).oper[1]^.typ = top_reg) and
  9926. ((taicpu(p).ops = 2) or
  9927. ((taicpu(p).oper[2]^.typ = top_reg) and
  9928. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  9929. GetLastInstruction(p,hp1) and
  9930. MatchInstruction(hp1,A_MOV,[]) and
  9931. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9932. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9933. begin
  9934. TransferUsedRegs(TmpUsedRegs);
  9935. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  9936. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  9937. { change
  9938. mov reg1,reg2
  9939. imul y,reg2 to imul y,reg1,reg2 }
  9940. begin
  9941. taicpu(p).ops := 3;
  9942. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  9943. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  9944. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  9945. RemoveInstruction(hp1);
  9946. result:=true;
  9947. end;
  9948. end;
  9949. end;
  9950. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  9951. var
  9952. ThisLabel: TAsmLabel;
  9953. begin
  9954. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  9955. ThisLabel.decrefs;
  9956. taicpu(p).condition := C_None;
  9957. taicpu(p).opcode := A_RET;
  9958. taicpu(p).is_jmp := false;
  9959. taicpu(p).ops := taicpu(ret_p).ops;
  9960. case taicpu(ret_p).ops of
  9961. 0:
  9962. taicpu(p).clearop(0);
  9963. 1:
  9964. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  9965. else
  9966. internalerror(2016041301);
  9967. end;
  9968. { If the original label is now dead, it might turn out that the label
  9969. immediately follows p. As a result, everything beyond it, which will
  9970. be just some final register configuration and a RET instruction, is
  9971. now dead code. [Kit] }
  9972. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9973. running RemoveDeadCodeAfterJump for each RET instruction, because
  9974. this optimisation rarely happens and most RETs appear at the end of
  9975. routines where there is nothing that can be stripped. [Kit] }
  9976. if not ThisLabel.is_used then
  9977. RemoveDeadCodeAfterJump(p);
  9978. end;
  9979. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9980. var
  9981. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9982. Unconditional, PotentialModified: Boolean;
  9983. OperPtr: POper;
  9984. NewRef: TReference;
  9985. InstrList: array of taicpu;
  9986. InstrMax, Index: Integer;
  9987. const
  9988. {$ifdef DEBUG_AOPTCPU}
  9989. SNoFlags: shortstring = ' so the flags aren''t modified';
  9990. {$else DEBUG_AOPTCPU}
  9991. SNoFlags = '';
  9992. {$endif DEBUG_AOPTCPU}
  9993. begin
  9994. Result:=false;
  9995. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9996. begin
  9997. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9998. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9999. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10000. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10001. GetNextInstruction(hp1, hp2) and
  10002. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10003. { Change from: To:
  10004. set(C) %reg j(~C) label
  10005. test %reg,%reg/cmp $0,%reg
  10006. je label
  10007. set(C) %reg j(C) label
  10008. test %reg,%reg/cmp $0,%reg
  10009. jne label
  10010. (Also do something similar with sete/setne instead of je/jne)
  10011. }
  10012. begin
  10013. { Before we do anything else, we need to check the instructions
  10014. in between SETcc and TEST to make sure they don't modify the
  10015. FLAGS register - if -O2 or under, there won't be any
  10016. instructions between SET and TEST }
  10017. TransferUsedRegs(TmpUsedRegs);
  10018. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10019. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10020. begin
  10021. next := p;
  10022. SetLength(InstrList, 0);
  10023. InstrMax := -1;
  10024. PotentialModified := False;
  10025. { Make a note of every instruction that modifies the FLAGS
  10026. register }
  10027. while GetNextInstruction(next, next) and (next <> hp1) do
  10028. begin
  10029. if next.typ <> ait_instruction then
  10030. { GetNextInstructionUsingReg should have returned False }
  10031. InternalError(2021051701);
  10032. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10033. begin
  10034. case taicpu(next).opcode of
  10035. A_SETcc,
  10036. A_CMOVcc,
  10037. A_Jcc:
  10038. begin
  10039. if PotentialModified then
  10040. { Not safe because the flags were modified earlier }
  10041. Exit
  10042. else
  10043. { Condition is the same as the initial SETcc, so this is safe
  10044. (don't add to instruction list though) }
  10045. Continue;
  10046. end;
  10047. A_ADD:
  10048. begin
  10049. if (taicpu(next).opsize = S_B) or
  10050. { LEA doesn't support 8-bit operands }
  10051. (taicpu(next).oper[1]^.typ <> top_reg) or
  10052. { Must write to a register }
  10053. (taicpu(next).oper[0]^.typ = top_ref) then
  10054. { Require a constant or a register }
  10055. Exit;
  10056. PotentialModified := True;
  10057. end;
  10058. A_SUB:
  10059. begin
  10060. if (taicpu(next).opsize = S_B) or
  10061. { LEA doesn't support 8-bit operands }
  10062. (taicpu(next).oper[1]^.typ <> top_reg) or
  10063. { Must write to a register }
  10064. (taicpu(next).oper[0]^.typ <> top_const) or
  10065. (taicpu(next).oper[0]^.val = $80000000) then
  10066. { Can't subtract a register with LEA - also
  10067. check that the value isn't -2^31, as this
  10068. can't be negated }
  10069. Exit;
  10070. PotentialModified := True;
  10071. end;
  10072. A_SAL,
  10073. A_SHL:
  10074. begin
  10075. if (taicpu(next).opsize = S_B) or
  10076. { LEA doesn't support 8-bit operands }
  10077. (taicpu(next).oper[1]^.typ <> top_reg) or
  10078. { Must write to a register }
  10079. (taicpu(next).oper[0]^.typ <> top_const) or
  10080. (taicpu(next).oper[0]^.val < 0) or
  10081. (taicpu(next).oper[0]^.val > 3) then
  10082. Exit;
  10083. PotentialModified := True;
  10084. end;
  10085. A_IMUL:
  10086. begin
  10087. if (taicpu(next).ops <> 3) or
  10088. (taicpu(next).oper[1]^.typ <> top_reg) or
  10089. { Must write to a register }
  10090. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10091. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10092. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10093. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10094. Exit
  10095. else
  10096. PotentialModified := True;
  10097. end;
  10098. else
  10099. { Don't know how to change this, so abort }
  10100. Exit;
  10101. end;
  10102. { Contains highest index (so instruction count - 1) }
  10103. Inc(InstrMax);
  10104. if InstrMax > High(InstrList) then
  10105. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10106. InstrList[InstrMax] := taicpu(next);
  10107. end;
  10108. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10109. end;
  10110. if not Assigned(next) or (next <> hp1) then
  10111. { It should be equal to hp1 }
  10112. InternalError(2021051702);
  10113. { Cycle through each instruction and check to see if we can
  10114. change them to versions that don't modify the flags }
  10115. if (InstrMax >= 0) then
  10116. begin
  10117. for Index := 0 to InstrMax do
  10118. case InstrList[Index].opcode of
  10119. A_ADD:
  10120. begin
  10121. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10122. InstrList[Index].opcode := A_LEA;
  10123. reference_reset(NewRef, 1, []);
  10124. NewRef.base := InstrList[Index].oper[1]^.reg;
  10125. if InstrList[Index].oper[0]^.typ = top_reg then
  10126. begin
  10127. NewRef.index := InstrList[Index].oper[0]^.reg;
  10128. NewRef.scalefactor := 1;
  10129. end
  10130. else
  10131. NewRef.offset := InstrList[Index].oper[0]^.val;
  10132. InstrList[Index].loadref(0, NewRef);
  10133. end;
  10134. A_SUB:
  10135. begin
  10136. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10137. InstrList[Index].opcode := A_LEA;
  10138. reference_reset(NewRef, 1, []);
  10139. NewRef.base := InstrList[Index].oper[1]^.reg;
  10140. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10141. InstrList[Index].loadref(0, NewRef);
  10142. end;
  10143. A_SHL,
  10144. A_SAL:
  10145. begin
  10146. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10147. InstrList[Index].opcode := A_LEA;
  10148. reference_reset(NewRef, 1, []);
  10149. NewRef.index := InstrList[Index].oper[1]^.reg;
  10150. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10151. InstrList[Index].loadref(0, NewRef);
  10152. end;
  10153. A_IMUL:
  10154. begin
  10155. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10156. InstrList[Index].opcode := A_LEA;
  10157. reference_reset(NewRef, 1, []);
  10158. NewRef.index := InstrList[Index].oper[1]^.reg;
  10159. case InstrList[Index].oper[0]^.val of
  10160. 2, 4, 8:
  10161. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10162. else {3, 5 and 9}
  10163. begin
  10164. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10165. NewRef.base := InstrList[Index].oper[1]^.reg;
  10166. end;
  10167. end;
  10168. InstrList[Index].loadref(0, NewRef);
  10169. end;
  10170. else
  10171. InternalError(2021051710);
  10172. end;
  10173. end;
  10174. { Mark the FLAGS register as used across this whole block }
  10175. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10176. end;
  10177. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10178. JumpC := taicpu(hp2).condition;
  10179. Unconditional := False;
  10180. if conditions_equal(JumpC, C_E) then
  10181. SetC := inverse_cond(taicpu(p).condition)
  10182. else if conditions_equal(JumpC, C_NE) then
  10183. SetC := taicpu(p).condition
  10184. else
  10185. { We've got something weird here (and inefficent) }
  10186. begin
  10187. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10188. SetC := C_NONE;
  10189. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10190. if condition_in(C_AE, JumpC) then
  10191. Unconditional := True
  10192. else
  10193. { Not sure what to do with this jump - drop out }
  10194. Exit;
  10195. end;
  10196. RemoveInstruction(hp1);
  10197. if Unconditional then
  10198. MakeUnconditional(taicpu(hp2))
  10199. else
  10200. begin
  10201. if SetC = C_NONE then
  10202. InternalError(2018061402);
  10203. taicpu(hp2).SetCondition(SetC);
  10204. end;
  10205. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10206. TmpUsedRegs }
  10207. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10208. begin
  10209. RemoveCurrentp(p, hp2);
  10210. if taicpu(hp2).opcode = A_SETcc then
  10211. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10212. else
  10213. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10214. end
  10215. else
  10216. if taicpu(hp2).opcode = A_SETcc then
  10217. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10218. else
  10219. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10220. Result := True;
  10221. end
  10222. else if
  10223. { Make sure the instructions are adjacent }
  10224. (
  10225. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10226. GetNextInstruction(p, hp1)
  10227. ) and
  10228. MatchInstruction(hp1, A_MOV, [S_B]) and
  10229. { Writing to memory is allowed }
  10230. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10231. begin
  10232. {
  10233. Watch out for sequences such as:
  10234. set(c)b %regb
  10235. movb %regb,(ref)
  10236. movb $0,1(ref)
  10237. movb $0,2(ref)
  10238. movb $0,3(ref)
  10239. Much more efficient to turn it into:
  10240. movl $0,%regl
  10241. set(c)b %regb
  10242. movl %regl,(ref)
  10243. Or:
  10244. set(c)b %regb
  10245. movzbl %regb,%regl
  10246. movl %regl,(ref)
  10247. }
  10248. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10249. GetNextInstruction(hp1, hp2) and
  10250. MatchInstruction(hp2, A_MOV, [S_B]) and
  10251. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10252. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10253. begin
  10254. { Don't do anything else except set Result to True }
  10255. end
  10256. else
  10257. begin
  10258. if taicpu(p).oper[0]^.typ = top_reg then
  10259. begin
  10260. TransferUsedRegs(TmpUsedRegs);
  10261. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10262. end;
  10263. { If it's not a register, it's a memory address }
  10264. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10265. begin
  10266. { Even if the register is still in use, we can minimise the
  10267. pipeline stall by changing the MOV into another SETcc. }
  10268. taicpu(hp1).opcode := A_SETcc;
  10269. taicpu(hp1).condition := taicpu(p).condition;
  10270. if taicpu(hp1).oper[1]^.typ = top_ref then
  10271. begin
  10272. { Swapping the operand pointers like this is probably a
  10273. bit naughty, but it is far faster than using loadoper
  10274. to transfer the reference from oper[1] to oper[0] if
  10275. you take into account the extra procedure calls and
  10276. the memory allocation and deallocation required }
  10277. OperPtr := taicpu(hp1).oper[1];
  10278. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10279. taicpu(hp1).oper[0] := OperPtr;
  10280. end
  10281. else
  10282. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10283. taicpu(hp1).clearop(1);
  10284. taicpu(hp1).ops := 1;
  10285. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10286. end
  10287. else
  10288. begin
  10289. if taicpu(hp1).oper[1]^.typ = top_reg then
  10290. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10291. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10292. RemoveInstruction(hp1);
  10293. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10294. end
  10295. end;
  10296. Result := True;
  10297. end;
  10298. end;
  10299. end;
  10300. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10301. var
  10302. hp1: tai;
  10303. Count: Integer;
  10304. OrigLabel: TAsmLabel;
  10305. begin
  10306. result := False;
  10307. { Sometimes, the optimisations below can permit this }
  10308. RemoveDeadCodeAfterJump(p);
  10309. 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
  10310. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10311. begin
  10312. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10313. { Also a side-effect of optimisations }
  10314. if CollapseZeroDistJump(p, OrigLabel) then
  10315. begin
  10316. Result := True;
  10317. Exit;
  10318. end;
  10319. hp1 := GetLabelWithSym(OrigLabel);
  10320. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10321. begin
  10322. if taicpu(hp1).opcode = A_RET then
  10323. begin
  10324. {
  10325. change
  10326. jmp .L1
  10327. ...
  10328. .L1:
  10329. ret
  10330. into
  10331. ret
  10332. }
  10333. begin
  10334. ConvertJumpToRET(p, hp1);
  10335. result:=true;
  10336. end;
  10337. end
  10338. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10339. not (cs_opt_size in current_settings.optimizerswitches) and
  10340. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10341. begin
  10342. Result := True;
  10343. Exit;
  10344. end;
  10345. end;
  10346. end;
  10347. end;
  10348. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai) : boolean;
  10349. begin
  10350. Result := assigned(p) and
  10351. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10352. (taicpu(p).oper[1]^.typ = top_reg) and
  10353. (
  10354. (taicpu(p).oper[0]^.typ = top_reg) or
  10355. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10356. it is not expected that this can cause a seg. violation }
  10357. (
  10358. (taicpu(p).oper[0]^.typ = top_ref) and
  10359. { TODO: Can we detect which references become constants at this
  10360. stage so we don't have to do a blanket ban? }
  10361. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10362. (
  10363. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10364. (
  10365. { If the reference also appears in the condition, then we know it's safe, otherwise
  10366. any kind of access violation would have occurred already }
  10367. Assigned(cond_p) and
  10368. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10369. (cond_p.typ = ait_instruction) and
  10370. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10371. { Just consider 2-operand comparison instructions for now to be safe }
  10372. (taicpu(cond_p).ops = 2) and
  10373. (
  10374. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10375. (
  10376. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10377. { Don't risk identical registers but different offsets, as we may have constructs
  10378. such as buffer streams with things like length fields that indicate whether
  10379. any more data follows. And there are probably some contrived examples where
  10380. writing to offsets behind the one being read also lead to access violations }
  10381. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10382. (
  10383. { Check that we're not modifying a register that appears in the reference }
  10384. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10385. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10386. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10387. )
  10388. )
  10389. )
  10390. )
  10391. )
  10392. )
  10393. );
  10394. end;
  10395. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10396. begin
  10397. { Update integer registers, ignoring deallocations }
  10398. repeat
  10399. while assigned(p) and
  10400. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10401. (p.typ = ait_label) or
  10402. ((p.typ = ait_marker) and
  10403. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10404. p := tai(p.next);
  10405. while assigned(p) and
  10406. (p.typ=ait_RegAlloc) Do
  10407. begin
  10408. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10409. begin
  10410. case tai_regalloc(p).ratype of
  10411. ra_alloc :
  10412. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10413. else
  10414. ;
  10415. end;
  10416. end;
  10417. p := tai(p.next);
  10418. end;
  10419. until not(assigned(p)) or
  10420. (not(p.typ in SkipInstr) and
  10421. not((p.typ = ait_label) and
  10422. labelCanBeSkipped(tai_label(p))));
  10423. end;
  10424. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10425. var
  10426. hp1,hp2: tai;
  10427. carryadd_opcode : TAsmOp;
  10428. symbol: TAsmSymbol;
  10429. increg, tmpreg: TRegister;
  10430. {$ifndef i8086}
  10431. { Code and variables specific to CMOV optimisations }
  10432. hp3,hp4,hp5,
  10433. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10434. l, c, w, x : Longint;
  10435. condition, second_condition : TAsmCond;
  10436. FoundMatchingJump, RegMatch: Boolean;
  10437. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10438. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10439. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10440. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10441. new register to store the constant }
  10442. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10443. var
  10444. RegSize: TSubRegister;
  10445. CurrentVal: TCGInt;
  10446. NewReg: TRegister;
  10447. X: ShortInt;
  10448. begin
  10449. Result := False;
  10450. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10451. Exit;
  10452. if StoredCount >= MAX_CMOV_REGISTERS then
  10453. { Arrays are full }
  10454. Exit;
  10455. { Remember that CMOV can't encode 8-bit registers }
  10456. case taicpu(p).opsize of
  10457. S_W:
  10458. RegSize := R_SUBW;
  10459. S_L:
  10460. RegSize := R_SUBD;
  10461. S_Q:
  10462. RegSize := R_SUBQ;
  10463. else
  10464. InternalError(2021100401);
  10465. end;
  10466. { See if the value has already been reserved for another CMOV instruction }
  10467. CurrentVal := taicpu(p).oper[0]^.val;
  10468. for X := 0 to StoredCount - 1 do
  10469. if ConstVals[X] = CurrentVal then
  10470. begin
  10471. ConstRegs[StoredCount] := ConstRegs[X];
  10472. ConstVals[StoredCount] := CurrentVal;
  10473. Result := True;
  10474. Inc(StoredCount);
  10475. { Don't increase CMOVCount this time, since we're re-using a register }
  10476. Exit;
  10477. end;
  10478. NewReg := GetIntRegisterBetween(RegSize, TmpUsedRegs, search_start_p, stop_search_p, True);
  10479. if NewReg = NR_NO then
  10480. { No free registers }
  10481. Exit;
  10482. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10483. up vying for the same register }
  10484. IncludeRegInUsedRegs(NewReg, TmpUsedRegs);
  10485. ConstRegs[StoredCount] := NewReg;
  10486. ConstVals[StoredCount] := CurrentVal;
  10487. Inc(StoredCount);
  10488. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10489. MOV required adds complexity and will cause diminishing returns
  10490. sooner than normal. This is more of an approximate weighting than
  10491. anything else. }
  10492. Inc(CMOVCount);
  10493. Result := True;
  10494. end;
  10495. {$endif i8086}
  10496. begin
  10497. result:=false;
  10498. if GetNextInstruction(p,hp1) then
  10499. begin
  10500. if (hp1.typ=ait_label) then
  10501. begin
  10502. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10503. Exit;
  10504. end
  10505. else if (hp1.typ<>ait_instruction) then
  10506. Exit;
  10507. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10508. if (
  10509. (
  10510. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10511. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10512. (Taicpu(hp1).oper[0]^.val=1)
  10513. ) or
  10514. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10515. ) and
  10516. GetNextInstruction(hp1,hp2) and
  10517. SkipAligns(hp2, hp2) and
  10518. (hp2.typ = ait_label) and
  10519. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10520. { jb @@1 cmc
  10521. inc/dec operand --> adc/sbb operand,0
  10522. @@1:
  10523. ... and ...
  10524. jnb @@1
  10525. inc/dec operand --> adc/sbb operand,0
  10526. @@1: }
  10527. begin
  10528. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10529. begin
  10530. case taicpu(hp1).opcode of
  10531. A_INC,
  10532. A_ADD:
  10533. carryadd_opcode:=A_ADC;
  10534. A_DEC,
  10535. A_SUB:
  10536. carryadd_opcode:=A_SBB;
  10537. else
  10538. InternalError(2021011001);
  10539. end;
  10540. Taicpu(p).clearop(0);
  10541. Taicpu(p).ops:=0;
  10542. Taicpu(p).is_jmp:=false;
  10543. Taicpu(p).opcode:=A_CMC;
  10544. Taicpu(p).condition:=C_NONE;
  10545. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10546. Taicpu(hp1).ops:=2;
  10547. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10548. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10549. else
  10550. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10551. Taicpu(hp1).loadconst(0,0);
  10552. Taicpu(hp1).opcode:=carryadd_opcode;
  10553. result:=true;
  10554. exit;
  10555. end
  10556. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10557. begin
  10558. case taicpu(hp1).opcode of
  10559. A_INC,
  10560. A_ADD:
  10561. carryadd_opcode:=A_ADC;
  10562. A_DEC,
  10563. A_SUB:
  10564. carryadd_opcode:=A_SBB;
  10565. else
  10566. InternalError(2021011002);
  10567. end;
  10568. Taicpu(hp1).ops:=2;
  10569. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10570. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10571. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10572. else
  10573. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10574. Taicpu(hp1).loadconst(0,0);
  10575. Taicpu(hp1).opcode:=carryadd_opcode;
  10576. RemoveCurrentP(p, hp1);
  10577. result:=true;
  10578. exit;
  10579. end
  10580. {
  10581. jcc @@1 setcc tmpreg
  10582. inc/dec/add/sub operand -> (movzx tmpreg)
  10583. @@1: add/sub tmpreg,operand
  10584. While this increases code size slightly, it makes the code much faster if the
  10585. jump is unpredictable
  10586. }
  10587. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10588. begin
  10589. { search for an available register which is volatile }
  10590. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10591. if increg <> NR_NO then
  10592. begin
  10593. { We don't need to check if tmpreg is in hp1 or not, because
  10594. it will be marked as in use at p (if not, this is
  10595. indictive of a compiler bug). }
  10596. TAsmLabel(symbol).decrefs;
  10597. Taicpu(p).clearop(0);
  10598. Taicpu(p).ops:=1;
  10599. Taicpu(p).is_jmp:=false;
  10600. Taicpu(p).opcode:=A_SETcc;
  10601. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10602. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10603. Taicpu(p).loadreg(0,increg);
  10604. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10605. begin
  10606. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10607. R_SUBW:
  10608. begin
  10609. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10610. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10611. end;
  10612. R_SUBD:
  10613. begin
  10614. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10615. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10616. end;
  10617. {$ifdef x86_64}
  10618. R_SUBQ:
  10619. begin
  10620. { MOVZX doesn't have a 64-bit variant, because
  10621. the 32-bit version implicitly zeroes the
  10622. upper 32-bits of the destination register }
  10623. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10624. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10625. setsubreg(tmpreg, R_SUBQ);
  10626. end;
  10627. {$endif x86_64}
  10628. else
  10629. Internalerror(2020030601);
  10630. end;
  10631. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10632. asml.InsertAfter(hp2,p);
  10633. end
  10634. else
  10635. tmpreg := increg;
  10636. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10637. begin
  10638. Taicpu(hp1).ops:=2;
  10639. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10640. end;
  10641. Taicpu(hp1).loadreg(0,tmpreg);
  10642. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10643. Result := True;
  10644. { p is no longer a Jcc instruction, so exit }
  10645. Exit;
  10646. end;
  10647. end;
  10648. end;
  10649. { Detect the following:
  10650. jmp<cond> @Lbl1
  10651. jmp @Lbl2
  10652. ...
  10653. @Lbl1:
  10654. ret
  10655. Change to:
  10656. jmp<inv_cond> @Lbl2
  10657. ret
  10658. }
  10659. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10660. begin
  10661. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10662. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10663. MatchInstruction(hp2,A_RET,[S_NO]) then
  10664. begin
  10665. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10666. { Change label address to that of the unconditional jump }
  10667. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10668. TAsmLabel(symbol).DecRefs;
  10669. taicpu(hp1).opcode := A_RET;
  10670. taicpu(hp1).is_jmp := false;
  10671. taicpu(hp1).ops := taicpu(hp2).ops;
  10672. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10673. case taicpu(hp2).ops of
  10674. 0:
  10675. taicpu(hp1).clearop(0);
  10676. 1:
  10677. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10678. else
  10679. internalerror(2016041302);
  10680. end;
  10681. end;
  10682. {$ifndef i8086}
  10683. end
  10684. {
  10685. convert
  10686. j<c> .L1
  10687. mov 1,reg
  10688. jmp .L2
  10689. .L1
  10690. mov 0,reg
  10691. .L2
  10692. into
  10693. mov 0,reg
  10694. set<not(c)> reg
  10695. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10696. would destroy the flag contents
  10697. }
  10698. else if MatchInstruction(hp1,A_MOV,[]) and
  10699. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10700. {$ifdef i386}
  10701. (
  10702. { Under i386, ESI, EDI, EBP and ESP
  10703. don't have an 8-bit representation }
  10704. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10705. ) and
  10706. {$endif i386}
  10707. (taicpu(hp1).oper[0]^.val=1) and
  10708. GetNextInstruction(hp1,hp2) and
  10709. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10710. GetNextInstruction(hp2,hp3) and
  10711. { skip align }
  10712. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10713. (hp3.typ=ait_label) and
  10714. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10715. (tai_label(hp3).labsym.getrefs=1) and
  10716. GetNextInstruction(hp3,hp4) and
  10717. MatchInstruction(hp4,A_MOV,[]) and
  10718. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10719. (taicpu(hp4).oper[0]^.val=0) and
  10720. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10721. GetNextInstruction(hp4,hp5) and
  10722. (hp5.typ=ait_label) and
  10723. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10724. (tai_label(hp5).labsym.getrefs=1) then
  10725. begin
  10726. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10727. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10728. { remove last label }
  10729. RemoveInstruction(hp5);
  10730. { remove second label }
  10731. RemoveInstruction(hp3);
  10732. { if align is present remove it }
  10733. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10734. RemoveInstruction(hp3);
  10735. { remove jmp }
  10736. RemoveInstruction(hp2);
  10737. if taicpu(hp1).opsize=S_B then
  10738. RemoveInstruction(hp1)
  10739. else
  10740. taicpu(hp1).loadconst(0,0);
  10741. taicpu(hp4).opcode:=A_SETcc;
  10742. taicpu(hp4).opsize:=S_B;
  10743. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10744. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10745. taicpu(hp4).opercnt:=1;
  10746. taicpu(hp4).ops:=1;
  10747. taicpu(hp4).freeop(1);
  10748. RemoveCurrentP(p);
  10749. Result:=true;
  10750. exit;
  10751. end
  10752. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.optimizecputype]) and
  10753. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  10754. begin
  10755. { check for
  10756. jCC xxx
  10757. <several movs>
  10758. xxx:
  10759. Also spot:
  10760. Jcc xxx
  10761. <several movs>
  10762. jmp xxx
  10763. Change to:
  10764. <several cmovs with inverted condition>
  10765. jmp xxx (only for the 2nd case)
  10766. }
  10767. hp2 := p;
  10768. hp_lblxxx := hp1;
  10769. hp_flagalloc := nil;
  10770. hp_stop := nil;
  10771. FoundMatchingJump := False;
  10772. { Remember the first instruction in the first block of MOVs }
  10773. hpmov1 := hp1;
  10774. TransferUsedRegs(TmpUsedRegs);
  10775. while assigned(hp_lblxxx) and
  10776. { stop on labels }
  10777. (hp_lblxxx.typ <> ait_label) do
  10778. begin
  10779. { Keep track of all integer registers that are used }
  10780. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  10781. if hp_lblxxx.typ = ait_instruction then
  10782. begin
  10783. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  10784. IsJumpToLabel(taicpu(hp_lblxxx)) then
  10785. begin
  10786. hp_stop := hp_lblxxx;
  10787. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  10788. begin
  10789. { We found Jcc xxx; <several movs>; Jmp xxx }
  10790. FoundMatchingJump := True;
  10791. Break;
  10792. end;
  10793. { If it's not the jump we're looking for, it's
  10794. possibly the "if..else" variant }
  10795. end
  10796. { Check to see if we have a valid MOV instruction instead }
  10797. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  10798. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  10799. Break
  10800. else
  10801. { This will be a valid MOV }
  10802. hp_stop := hp_lblxxx;
  10803. end;
  10804. hp2 := hp_lblxxx;
  10805. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  10806. end;
  10807. { Just make sure the last MOV is included if there's no jump }
  10808. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  10809. hp_stop := hp_lblxxx;
  10810. { Note, the logic behind using hp_stop over hp_lblxxx in the
  10811. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  10812. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  10813. jmp yyy; xxx:; movs; yyy:" variation }
  10814. if assigned(hp_lblxxx) and
  10815. (
  10816. { If we found JMP xxx, we don't actually need a label
  10817. (hp_lblxxx is the JMP instruction instead) }
  10818. FoundMatchingJump or
  10819. { Make sure we actually have the right label }
  10820. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  10821. ) then
  10822. begin
  10823. { Use TmpUsedRegs to track registers that we reserve }
  10824. { When allocating temporary registers, try to look one
  10825. instruction back, as defining them before a CMP or TEST
  10826. instruction will be faster, and also avoid picking a
  10827. register that was only just deallocated }
  10828. if GetLastInstruction(p, hp_prev) and
  10829. 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
  10830. begin
  10831. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  10832. for l := 0 to 1 do
  10833. with taicpu(hp_prev).oper[l]^ do
  10834. case typ of
  10835. top_reg:
  10836. if getregtype(reg) = R_INTREGISTER then
  10837. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  10838. top_ref:
  10839. begin
  10840. if
  10841. {$ifdef x86_64}
  10842. (ref^.base <> NR_RIP) and
  10843. {$endif x86_64}
  10844. (ref^.base <> NR_NO) then
  10845. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  10846. if (ref^.index <> NR_NO) then
  10847. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  10848. end
  10849. else
  10850. ;
  10851. end;
  10852. { When inserting instructions before hp_prev, try to insert
  10853. them before the allocation of the FLAGS register }
  10854. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  10855. { If not found, set it equal to hp_prev so it's something sensible }
  10856. hp_flagalloc := hp_prev;
  10857. hp_prev2 := nil;
  10858. { When dealing with a comparison against zero, take
  10859. note of the instruction before it to see if we can
  10860. move instructions further back in order to benefit
  10861. PostPeepholeOptTestOr.
  10862. }
  10863. if (
  10864. (
  10865. (taicpu(hp_prev).opcode = A_CMP) and
  10866. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  10867. ) or
  10868. (
  10869. (taicpu(hp_prev).opcode = A_TEST) and
  10870. (
  10871. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  10872. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  10873. )
  10874. )
  10875. ) and
  10876. GetLastInstruction(hp_prev, hp_prev2) then
  10877. begin
  10878. if (hp_prev2.typ = ait_instruction) and
  10879. { These instructions set the zero flag if the result is zero }
  10880. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  10881. begin
  10882. { Also mark all the registers in this previous instruction
  10883. as 'in use', even if they've just been deallocated }
  10884. for l := 0 to 1 do
  10885. with taicpu(hp_prev2).oper[l]^ do
  10886. case typ of
  10887. top_reg:
  10888. if getregtype(reg) = R_INTREGISTER then
  10889. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  10890. top_ref:
  10891. begin
  10892. if
  10893. {$ifdef x86_64}
  10894. (ref^.base <> NR_RIP) and
  10895. {$endif x86_64}
  10896. (ref^.base <> NR_NO) then
  10897. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  10898. if (ref^.index <> NR_NO) then
  10899. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  10900. end
  10901. else
  10902. ;
  10903. end;
  10904. end
  10905. else
  10906. { Unsuitable instruction }
  10907. hp_prev2 := nil;
  10908. end;
  10909. end
  10910. else
  10911. begin
  10912. hp_prev := p;
  10913. { When inserting instructions before hp_prev, try to insert
  10914. them before the allocation of the FLAGS register }
  10915. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  10916. { If not found, set it equal to p so it's something sensible }
  10917. hp_flagalloc := p;
  10918. hp_prev2 := nil;
  10919. end;
  10920. l := 0;
  10921. c := 0;
  10922. { Initialise RegWrites, ConstRegs and ConstVals }
  10923. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  10924. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  10925. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  10926. while assigned(hp1) and
  10927. { Stop on the label we found }
  10928. (hp1 <> hp_lblxxx) do
  10929. begin
  10930. case hp1.typ of
  10931. ait_instruction:
  10932. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  10933. begin
  10934. if CanBeCMOV(hp1, hp_prev) then
  10935. Inc(l)
  10936. else if not (cs_opt_size in current_settings.optimizerswitches) and
  10937. { CMOV with constants grows the code size }
  10938. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  10939. begin
  10940. { Register was reserved by TryCMOVConst and
  10941. stored on ConstRegs[c] }
  10942. end
  10943. else
  10944. Break;
  10945. end
  10946. else
  10947. Break;
  10948. else
  10949. ;
  10950. end;
  10951. GetNextInstruction(hp1,hp1);
  10952. end;
  10953. if (hp1 = hp_lblxxx) then
  10954. begin
  10955. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  10956. begin
  10957. { Repurpose TmpUsedRegs to mark registers that we've defined }
  10958. TmpUsedRegs[R_INTREGISTER].Clear;
  10959. x := 0;
  10960. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  10961. condition := inverse_cond(taicpu(p).condition);
  10962. UpdateUsedRegs(tai(p.next));
  10963. hp1 := hpmov1;
  10964. repeat
  10965. if not Assigned(hp1) then
  10966. InternalError(2018062900);
  10967. if (hp1.typ = ait_instruction) then
  10968. begin
  10969. { Extra safeguard }
  10970. if (taicpu(hp1).opcode <> A_MOV) then
  10971. InternalError(2018062901);
  10972. if taicpu(hp1).oper[0]^.typ = top_const then
  10973. begin
  10974. if x >= MAX_CMOV_REGISTERS then
  10975. InternalError(2021100410);
  10976. { If it's in TmpUsedRegs, then this register
  10977. is being used more than once and hence has
  10978. already had its value defined (it gets
  10979. added to UsedRegs through AllocRegBetween
  10980. below) }
  10981. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  10982. begin
  10983. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  10984. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  10985. asml.InsertBefore(hp_new, hp_flagalloc);
  10986. if Assigned(hp_prev2) then
  10987. TrySwapMovOp(hp_prev2, hp_new);
  10988. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  10989. end
  10990. else
  10991. { We just need an instruction between hp_prev and hp1
  10992. where we know the register is marked as in use }
  10993. hp_new := hpmov1;
  10994. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  10995. taicpu(hp1).loadreg(0, ConstRegs[x]);
  10996. Inc(x);
  10997. end;
  10998. taicpu(hp1).opcode := A_CMOVcc;
  10999. taicpu(hp1).condition := condition;
  11000. end;
  11001. UpdateUsedRegs(tai(hp1.next));
  11002. GetNextInstruction(hp1, hp1);
  11003. until (hp1 = hp_lblxxx);
  11004. hp2 := hp_lblxxx;
  11005. repeat
  11006. if not Assigned(hp2) then
  11007. InternalError(2018062910);
  11008. case hp2.typ of
  11009. ait_label:
  11010. { What we expected - break out of the loop (it won't be a dead label at the top of
  11011. a cluster because that was optimised at an earlier stage) }
  11012. Break;
  11013. ait_align:
  11014. { Go to the next entry until a label is found (may be multiple aligns before it) }
  11015. begin
  11016. hp2 := tai(hp2.Next);
  11017. Continue;
  11018. end;
  11019. ait_instruction:
  11020. begin
  11021. if taicpu(hp2).opcode<>A_JMP then
  11022. InternalError(2018062912);
  11023. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  11024. Break;
  11025. end
  11026. else
  11027. begin
  11028. { Might be a comment or temporary allocation entry }
  11029. if not (hp2.typ in SkipInstr) then
  11030. InternalError(2018062911);
  11031. hp2 := tai(hp2.Next);
  11032. Continue;
  11033. end;
  11034. end;
  11035. until False;
  11036. { Now we can safely decrement the reference count }
  11037. tasmlabel(symbol).decrefs;
  11038. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  11039. { Remove the original jump }
  11040. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  11041. if hp2.typ=ait_instruction then
  11042. begin
  11043. p := hp2;
  11044. Result := True;
  11045. end
  11046. else
  11047. begin
  11048. UpdateUsedRegs(tai(hp2.next));
  11049. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  11050. { Remove the label if this is its final reference }
  11051. if (tasmlabel(symbol).getrefs=0) then
  11052. begin
  11053. { Make sure the aligns get stripped too }
  11054. hp1 := tai(hp_lblxxx.Previous);
  11055. while Assigned(hp1) and (hp1.typ = ait_align) do
  11056. begin
  11057. hp_lblxxx := hp1;
  11058. hp1 := tai(hp_lblxxx.Previous);
  11059. end;
  11060. StripLabelFast(hp_lblxxx);
  11061. end;
  11062. end;
  11063. Exit;
  11064. end;
  11065. end
  11066. else if assigned(hp_lblxxx) and
  11067. { check further for
  11068. jCC xxx
  11069. <several movs 1>
  11070. jmp yyy
  11071. xxx:
  11072. <several movs 2>
  11073. yyy:
  11074. }
  11075. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11076. { hp1 should be pointing to jmp yyy }
  11077. MatchInstruction(hp1, A_JMP, []) and
  11078. { real label and jump, no further references to the
  11079. label are allowed }
  11080. (TAsmLabel(symbol).getrefs=1) and
  11081. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  11082. begin
  11083. hp_jump := hp1;
  11084. { Don't set c to zero }
  11085. l := 0;
  11086. w := 0;
  11087. GetNextInstruction(hp_lblxxx, hpmov2);
  11088. hp2 := hp_lblxxx;
  11089. hp_lblyyy := hpmov2;
  11090. while assigned(hp_lblyyy) and
  11091. { stop on labels }
  11092. (hp_lblyyy.typ <> ait_label) do
  11093. begin
  11094. { Keep track of all integer registers that are used }
  11095. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11096. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11097. Break;
  11098. hp2 := hp_lblyyy;
  11099. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  11100. end;
  11101. { Analyse the second batch of MOVs to see if the setup is valid }
  11102. hp1 := hpmov2;
  11103. while assigned(hp1) and
  11104. (hp1 <> hp_lblyyy) do
  11105. begin
  11106. case hp1.typ of
  11107. ait_instruction:
  11108. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11109. begin
  11110. if CanBeCMOV(hp1, hp_prev) then
  11111. Inc(l)
  11112. else if not (cs_opt_size in current_settings.optimizerswitches)
  11113. { CMOV with constants grows the code size }
  11114. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  11115. begin
  11116. { Register was reserved by TryCMOVConst and
  11117. stored on ConstRegs[c] }
  11118. end
  11119. else
  11120. Break;
  11121. end
  11122. else
  11123. Break;
  11124. else
  11125. ;
  11126. end;
  11127. GetNextInstruction(hp1,hp1);
  11128. end;
  11129. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11130. TmpUsedRegs[R_INTREGISTER].Clear;
  11131. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11132. (hp1 = hp_lblyyy) and
  11133. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  11134. begin
  11135. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  11136. second_condition := taicpu(p).condition;
  11137. condition := inverse_cond(taicpu(p).condition);
  11138. UpdateUsedRegs(tai(p.next));
  11139. { Scan through the first set of MOVs to update UsedRegs,
  11140. but don't process them yet }
  11141. hp1 := hpmov1;
  11142. repeat
  11143. if not Assigned(hp1) then
  11144. InternalError(2018062901);
  11145. UpdateUsedRegs(tai(hp1.next));
  11146. GetNextInstruction(hp1, hp1);
  11147. until (hp1 = hp_lblxxx);
  11148. UpdateUsedRegs(tai(hp_lblxxx.next));
  11149. { Process the second set of MOVs first,
  11150. because if a destination register is
  11151. shared between the first and second MOV
  11152. sets, it is more efficient to turn the
  11153. first one into a MOV instruction and place
  11154. it before the CMP if possible, but we
  11155. won't know which registers are shared
  11156. until we've processed at least one list,
  11157. so we might as well make it the second
  11158. one since that won't be modified again. }
  11159. hp1 := hpmov2;
  11160. repeat
  11161. if not Assigned(hp1) then
  11162. InternalError(2018062902);
  11163. if (hp1.typ = ait_instruction) then
  11164. begin
  11165. { Extra safeguard }
  11166. if (taicpu(hp1).opcode <> A_MOV) then
  11167. InternalError(2018062903);
  11168. if taicpu(hp1).oper[0]^.typ = top_const then
  11169. begin
  11170. RegMatch := False;
  11171. for x := 0 to c - 1 do
  11172. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11173. begin
  11174. RegMatch := True;
  11175. { If it's in TmpUsedRegs, then this register
  11176. is being used more than once and hence has
  11177. already had its value defined (it gets
  11178. added to UsedRegs through AllocRegBetween
  11179. below) }
  11180. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11181. begin
  11182. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11183. asml.InsertBefore(hp_new, hp_flagalloc);
  11184. if Assigned(hp_prev2) then
  11185. TrySwapMovOp(hp_prev2, hp_new);
  11186. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11187. end
  11188. else
  11189. { We just need an instruction between hp_prev and hp1
  11190. where we know the register is marked as in use }
  11191. hp_new := hpmov2;
  11192. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11193. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11194. Break;
  11195. end;
  11196. if not RegMatch then
  11197. InternalError(2021100411);
  11198. end;
  11199. taicpu(hp1).opcode := A_CMOVcc;
  11200. taicpu(hp1).condition := second_condition;
  11201. { Store these writes to search for
  11202. duplicates later on }
  11203. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11204. Inc(w);
  11205. end;
  11206. UpdateUsedRegs(tai(hp1.next));
  11207. GetNextInstruction(hp1, hp1);
  11208. until (hp1 = hp_lblyyy);
  11209. { Now do the first set of MOVs }
  11210. hp1 := hpmov1;
  11211. repeat
  11212. if not Assigned(hp1) then
  11213. InternalError(2018062904);
  11214. if (hp1.typ = ait_instruction) then
  11215. begin
  11216. RegMatch := False;
  11217. { Extra safeguard }
  11218. if (taicpu(hp1).opcode <> A_MOV) then
  11219. InternalError(2018062905);
  11220. { Search through the RegWrites list to see
  11221. if there are any opposing CMOV pairs that
  11222. write to the same register }
  11223. for x := 0 to w - 1 do
  11224. if RegWrites[x] = taicpu(hp1).oper[1]^.reg then
  11225. begin
  11226. { We have a match. Move this instruction
  11227. right to the top }
  11228. hp2 := hp1;
  11229. { Move ahead in preparation }
  11230. GetNextInstruction(hp1, hp1);
  11231. asml.Remove(hp2);
  11232. asml.InsertAfter(hp2, hp_prev);
  11233. { Note we can't use the trick of inserting before hp_prev
  11234. and then calling TrySwapMovOp with hp_prev2, like with
  11235. the MOV imm,reg optimisations, because hp2 may share a
  11236. register with the comparison }
  11237. if (hp_prev <> p) then
  11238. TrySwapMovCmp(hp_prev, hp2);
  11239. RegMatch := True;
  11240. Break;
  11241. end;
  11242. if RegMatch then
  11243. Continue;
  11244. if taicpu(hp1).oper[0]^.typ = top_const then
  11245. begin
  11246. RegMatch := False;
  11247. for x := 0 to c - 1 do
  11248. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11249. begin
  11250. RegMatch := True;
  11251. { If it's in TmpUsedRegs, then this register
  11252. is being used more than once and hence has
  11253. already had its value defined (it gets
  11254. added to UsedRegs through AllocRegBetween
  11255. below) }
  11256. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11257. begin
  11258. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11259. asml.InsertBefore(hp_new, hp_flagalloc);
  11260. if Assigned(hp_prev2) then
  11261. TrySwapMovOp(hp_prev2, hp_new);
  11262. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11263. end
  11264. else
  11265. { We just need an instruction between hp_prev and hp1
  11266. where we know the register is marked as in use }
  11267. hp_new := hpmov1;
  11268. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11269. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11270. Break;
  11271. end;
  11272. if not RegMatch then
  11273. InternalError(2021100412);
  11274. end;
  11275. taicpu(hp1).opcode := A_CMOVcc;
  11276. taicpu(hp1).condition := condition;
  11277. end;
  11278. GetNextInstruction(hp1, hp1);
  11279. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11280. UpdateUsedRegs(tai(hp_jump.next));
  11281. UpdateUsedRegs(tai(hp_lblyyy.next));
  11282. { Get first instruction after label }
  11283. hp1 := p;
  11284. GetNextInstruction(hp_lblyyy, p);
  11285. { Don't dereference yet, as doing so will cause
  11286. GetNextInstruction to skip the label and
  11287. optional align marker. [Kit] }
  11288. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11289. { remove Jcc }
  11290. RemoveInstruction(hp1);
  11291. { Now we can safely decrement it }
  11292. tasmlabel(symbol).decrefs;
  11293. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11294. { Make sure the aligns get stripped too }
  11295. hp1 := tai(hp_lblxxx.Previous);
  11296. while Assigned(hp1) and (hp1.typ = ait_align) do
  11297. begin
  11298. hp_lblxxx := hp1;
  11299. hp1 := tai(hp_lblxxx.Previous);
  11300. end;
  11301. StripLabelFast(hp_lblxxx);
  11302. { remove jmp }
  11303. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11304. RemoveInstruction(hp_jump);
  11305. { As before, now we can safely decrement it }
  11306. TAsmLabel(symbol).decrefs;
  11307. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11308. if TAsmLabel(symbol).getrefs = 0 then
  11309. begin
  11310. { Make sure the aligns get stripped too }
  11311. hp1 := tai(hp_lblyyy.Previous);
  11312. while Assigned(hp1) and (hp1.typ = ait_align) do
  11313. begin
  11314. hp_lblyyy := hp1;
  11315. hp1 := tai(hp_lblyyy.Previous);
  11316. end;
  11317. StripLabelFast(hp_lblyyy);
  11318. end;
  11319. if Assigned(p) then
  11320. result := True;
  11321. exit;
  11322. end;
  11323. end;
  11324. end;
  11325. {$endif i8086}
  11326. end;
  11327. end;
  11328. end;
  11329. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11330. var
  11331. hp1,hp2,hp3: tai;
  11332. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11333. NewSize: TOpSize;
  11334. NewRegSize: TSubRegister;
  11335. Limit: TCgInt;
  11336. SwapOper: POper;
  11337. begin
  11338. result:=false;
  11339. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11340. GetNextInstruction(p,hp1) and
  11341. (hp1.typ = ait_instruction);
  11342. if reg_and_hp1_is_instr and
  11343. (
  11344. (taicpu(hp1).opcode <> A_LEA) or
  11345. { If the LEA instruction can be converted into an arithmetic instruction,
  11346. it may be possible to then fold it. }
  11347. (
  11348. { If the flags register is in use, don't change the instruction
  11349. to an ADD otherwise this will scramble the flags. [Kit] }
  11350. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11351. ConvertLEA(taicpu(hp1))
  11352. )
  11353. ) and
  11354. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11355. GetNextInstruction(hp1,hp2) and
  11356. MatchInstruction(hp2,A_MOV,[]) and
  11357. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11358. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11359. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11360. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11361. {$ifdef i386}
  11362. { not all registers have byte size sub registers on i386 }
  11363. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11364. {$endif i386}
  11365. (((taicpu(hp1).ops=2) and
  11366. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11367. ((taicpu(hp1).ops=1) and
  11368. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11369. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11370. begin
  11371. { change movsX/movzX reg/ref, reg2
  11372. add/sub/or/... reg3/$const, reg2
  11373. mov reg2 reg/ref
  11374. to add/sub/or/... reg3/$const, reg/ref }
  11375. { by example:
  11376. movswl %si,%eax movswl %si,%eax p
  11377. decl %eax addl %edx,%eax hp1
  11378. movw %ax,%si movw %ax,%si hp2
  11379. ->
  11380. movswl %si,%eax movswl %si,%eax p
  11381. decw %eax addw %edx,%eax hp1
  11382. movw %ax,%si movw %ax,%si hp2
  11383. }
  11384. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11385. {
  11386. ->
  11387. movswl %si,%eax movswl %si,%eax p
  11388. decw %si addw %dx,%si hp1
  11389. movw %ax,%si movw %ax,%si hp2
  11390. }
  11391. case taicpu(hp1).ops of
  11392. 1:
  11393. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11394. 2:
  11395. begin
  11396. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11397. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11398. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11399. end;
  11400. else
  11401. internalerror(2008042702);
  11402. end;
  11403. {
  11404. ->
  11405. decw %si addw %dx,%si p
  11406. }
  11407. DebugMsg(SPeepholeOptimization + 'var3',p);
  11408. RemoveCurrentP(p, hp1);
  11409. RemoveInstruction(hp2);
  11410. Result := True;
  11411. Exit;
  11412. end;
  11413. if reg_and_hp1_is_instr and
  11414. (taicpu(hp1).opcode = A_MOV) and
  11415. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11416. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11417. {$ifdef x86_64}
  11418. { check for implicit extension to 64 bit }
  11419. or
  11420. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11421. (taicpu(hp1).opsize=S_Q) and
  11422. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11423. )
  11424. {$endif x86_64}
  11425. )
  11426. then
  11427. begin
  11428. { change
  11429. movx %reg1,%reg2
  11430. mov %reg2,%reg3
  11431. dealloc %reg2
  11432. into
  11433. movx %reg,%reg3
  11434. }
  11435. TransferUsedRegs(TmpUsedRegs);
  11436. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11437. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11438. begin
  11439. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11440. {$ifdef x86_64}
  11441. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11442. (taicpu(hp1).opsize=S_Q) then
  11443. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11444. else
  11445. {$endif x86_64}
  11446. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11447. RemoveInstruction(hp1);
  11448. Result := True;
  11449. Exit;
  11450. end;
  11451. end;
  11452. if reg_and_hp1_is_instr and
  11453. ((taicpu(hp1).opcode=A_MOV) or
  11454. (taicpu(hp1).opcode=A_ADD) or
  11455. (taicpu(hp1).opcode=A_SUB) or
  11456. (taicpu(hp1).opcode=A_CMP) or
  11457. (taicpu(hp1).opcode=A_OR) or
  11458. (taicpu(hp1).opcode=A_XOR) or
  11459. (taicpu(hp1).opcode=A_AND)
  11460. ) and
  11461. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11462. begin
  11463. AndTest := (taicpu(hp1).opcode=A_AND) and
  11464. GetNextInstruction(hp1, hp2) and
  11465. (hp2.typ = ait_instruction) and
  11466. (
  11467. (
  11468. (taicpu(hp2).opcode=A_TEST) and
  11469. (
  11470. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11471. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11472. (
  11473. { If the AND and TEST instructions share a constant, this is also valid }
  11474. (taicpu(hp1).oper[0]^.typ = top_const) and
  11475. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11476. )
  11477. ) and
  11478. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11479. ) or
  11480. (
  11481. (taicpu(hp2).opcode=A_CMP) and
  11482. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11483. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11484. )
  11485. );
  11486. { change
  11487. movx (oper),%reg2
  11488. and $x,%reg2
  11489. test %reg2,%reg2
  11490. dealloc %reg2
  11491. into
  11492. op %reg1,%reg3
  11493. if the second op accesses only the bits stored in reg1
  11494. }
  11495. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11496. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11497. (taicpu(hp1).oper[0]^.typ = top_const) and
  11498. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11499. AndTest then
  11500. begin
  11501. { Check if the AND constant is in range }
  11502. case taicpu(p).opsize of
  11503. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11504. begin
  11505. NewSize := S_B;
  11506. Limit := $FF;
  11507. end;
  11508. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11509. begin
  11510. NewSize := S_W;
  11511. Limit := $FFFF;
  11512. end;
  11513. {$ifdef x86_64}
  11514. S_LQ:
  11515. begin
  11516. NewSize := S_L;
  11517. Limit := $FFFFFFFF;
  11518. end;
  11519. {$endif x86_64}
  11520. else
  11521. InternalError(2021120303);
  11522. end;
  11523. if (
  11524. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11525. { Check for negative operands }
  11526. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11527. ) and
  11528. GetNextInstruction(hp2,hp3) and
  11529. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11530. (taicpu(hp3).condition in [C_E,C_NE]) then
  11531. begin
  11532. TransferUsedRegs(TmpUsedRegs);
  11533. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11534. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11535. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11536. begin
  11537. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11538. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11539. taicpu(hp1).opcode := A_TEST;
  11540. taicpu(hp1).opsize := NewSize;
  11541. RemoveInstruction(hp2);
  11542. RemoveCurrentP(p, hp1);
  11543. Result:=true;
  11544. exit;
  11545. end;
  11546. end;
  11547. end;
  11548. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11549. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11550. (taicpu(hp1).opsize=S_B)) or
  11551. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11552. (taicpu(hp1).opsize=S_W))
  11553. {$ifdef x86_64}
  11554. or ((taicpu(p).opsize=S_LQ) and
  11555. (taicpu(hp1).opsize=S_L))
  11556. {$endif x86_64}
  11557. ) and
  11558. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11559. begin
  11560. { change
  11561. movx %reg1,%reg2
  11562. op %reg2,%reg3
  11563. dealloc %reg2
  11564. into
  11565. op %reg1,%reg3
  11566. if the second op accesses only the bits stored in reg1
  11567. }
  11568. TransferUsedRegs(TmpUsedRegs);
  11569. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11570. if AndTest then
  11571. begin
  11572. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11573. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11574. end
  11575. else
  11576. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11577. if not RegUsed then
  11578. begin
  11579. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11580. if taicpu(p).oper[0]^.typ=top_reg then
  11581. begin
  11582. case taicpu(hp1).opsize of
  11583. S_B:
  11584. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11585. S_W:
  11586. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11587. S_L:
  11588. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11589. else
  11590. Internalerror(2020102301);
  11591. end;
  11592. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11593. end
  11594. else
  11595. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11596. RemoveCurrentP(p);
  11597. if AndTest then
  11598. RemoveInstruction(hp2);
  11599. result:=true;
  11600. exit;
  11601. end;
  11602. end
  11603. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11604. (
  11605. { Bitwise operations only }
  11606. (taicpu(hp1).opcode=A_AND) or
  11607. (taicpu(hp1).opcode=A_TEST) or
  11608. (
  11609. (taicpu(hp1).oper[0]^.typ = top_const) and
  11610. (
  11611. (taicpu(hp1).opcode=A_OR) or
  11612. (taicpu(hp1).opcode=A_XOR)
  11613. )
  11614. )
  11615. ) and
  11616. (
  11617. (taicpu(hp1).oper[0]^.typ = top_const) or
  11618. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11619. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11620. ) then
  11621. begin
  11622. { change
  11623. movx %reg2,%reg2
  11624. op const,%reg2
  11625. into
  11626. op const,%reg2 (smaller version)
  11627. movx %reg2,%reg2
  11628. also change
  11629. movx %reg1,%reg2
  11630. and/test (oper),%reg2
  11631. dealloc %reg2
  11632. into
  11633. and/test (oper),%reg1
  11634. }
  11635. case taicpu(p).opsize of
  11636. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11637. begin
  11638. NewSize := S_B;
  11639. NewRegSize := R_SUBL;
  11640. Limit := $FF;
  11641. end;
  11642. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11643. begin
  11644. NewSize := S_W;
  11645. NewRegSize := R_SUBW;
  11646. Limit := $FFFF;
  11647. end;
  11648. {$ifdef x86_64}
  11649. S_LQ:
  11650. begin
  11651. NewSize := S_L;
  11652. NewRegSize := R_SUBD;
  11653. Limit := $FFFFFFFF;
  11654. end;
  11655. {$endif x86_64}
  11656. else
  11657. Internalerror(2021120302);
  11658. end;
  11659. TransferUsedRegs(TmpUsedRegs);
  11660. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11661. if AndTest then
  11662. begin
  11663. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11664. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11665. end
  11666. else
  11667. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11668. if
  11669. (
  11670. (taicpu(p).opcode = A_MOVZX) and
  11671. (
  11672. (taicpu(hp1).opcode=A_AND) or
  11673. (taicpu(hp1).opcode=A_TEST)
  11674. ) and
  11675. not (
  11676. { If both are references, then the final instruction will have
  11677. both operands as references, which is not allowed }
  11678. (taicpu(p).oper[0]^.typ = top_ref) and
  11679. (taicpu(hp1).oper[0]^.typ = top_ref)
  11680. ) and
  11681. not RegUsed
  11682. ) or
  11683. (
  11684. (
  11685. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  11686. not RegUsed
  11687. ) and
  11688. (taicpu(p).oper[0]^.typ = top_reg) and
  11689. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11690. (taicpu(hp1).oper[0]^.typ = top_const) and
  11691. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  11692. ) then
  11693. begin
  11694. {$if defined(i386) or defined(i8086)}
  11695. { If the target size is 8-bit, make sure we can actually encode it }
  11696. 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
  11697. Exit;
  11698. {$endif i386 or i8086}
  11699. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  11700. taicpu(hp1).opsize := NewSize;
  11701. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11702. if AndTest then
  11703. begin
  11704. RemoveInstruction(hp2);
  11705. if not RegUsed then
  11706. begin
  11707. taicpu(hp1).opcode := A_TEST;
  11708. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  11709. begin
  11710. { Make sure the reference is the second operand }
  11711. SwapOper := taicpu(hp1).oper[0];
  11712. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  11713. taicpu(hp1).oper[1] := SwapOper;
  11714. end;
  11715. end;
  11716. end;
  11717. case taicpu(hp1).oper[0]^.typ of
  11718. top_reg:
  11719. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  11720. top_const:
  11721. { For the AND/TEST case }
  11722. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  11723. else
  11724. ;
  11725. end;
  11726. if RegUsed then
  11727. begin
  11728. AsmL.Remove(p);
  11729. AsmL.InsertAfter(p, hp1);
  11730. p := hp1;
  11731. end
  11732. else
  11733. RemoveCurrentP(p, hp1);
  11734. result:=true;
  11735. exit;
  11736. end;
  11737. end;
  11738. end;
  11739. if reg_and_hp1_is_instr and
  11740. (taicpu(p).oper[0]^.typ = top_reg) and
  11741. (
  11742. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  11743. ) and
  11744. (taicpu(hp1).oper[0]^.typ = top_const) and
  11745. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11746. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11747. { Minimum shift value allowed is the bit difference between the sizes }
  11748. (taicpu(hp1).oper[0]^.val >=
  11749. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11750. 8 * (
  11751. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  11752. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11753. )
  11754. ) then
  11755. begin
  11756. { For:
  11757. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  11758. shl/sal ##, %reg1
  11759. Remove the movsx/movzx instruction if the shift overwrites the
  11760. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  11761. }
  11762. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  11763. RemoveCurrentP(p, hp1);
  11764. Result := True;
  11765. Exit;
  11766. end
  11767. else if reg_and_hp1_is_instr and
  11768. (taicpu(p).oper[0]^.typ = top_reg) and
  11769. (
  11770. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  11771. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  11772. ) and
  11773. (taicpu(hp1).oper[0]^.typ = top_const) and
  11774. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11775. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11776. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  11777. (taicpu(hp1).oper[0]^.val <
  11778. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11779. 8 * (
  11780. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11781. )
  11782. ) then
  11783. begin
  11784. { For:
  11785. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  11786. sar ##, %reg1 shr ##, %reg1
  11787. Move the shift to before the movx instruction if the shift value
  11788. is not too large.
  11789. }
  11790. asml.Remove(hp1);
  11791. asml.InsertBefore(hp1, p);
  11792. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11793. case taicpu(p).opsize of
  11794. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  11795. taicpu(hp1).opsize := S_B;
  11796. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  11797. taicpu(hp1).opsize := S_W;
  11798. {$ifdef x86_64}
  11799. S_LQ:
  11800. taicpu(hp1).opsize := S_L;
  11801. {$endif}
  11802. else
  11803. InternalError(2020112401);
  11804. end;
  11805. if (taicpu(hp1).opcode = A_SHR) then
  11806. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  11807. else
  11808. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  11809. Result := True;
  11810. end;
  11811. if reg_and_hp1_is_instr and
  11812. (taicpu(p).oper[0]^.typ = top_reg) and
  11813. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11814. (
  11815. (taicpu(hp1).opcode = taicpu(p).opcode)
  11816. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  11817. {$ifdef x86_64}
  11818. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  11819. {$endif x86_64}
  11820. ) then
  11821. begin
  11822. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  11823. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  11824. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11825. begin
  11826. {
  11827. For example:
  11828. movzbw %al,%ax
  11829. movzwl %ax,%eax
  11830. Compress into:
  11831. movzbl %al,%eax
  11832. }
  11833. RegUsed := False;
  11834. case taicpu(p).opsize of
  11835. S_BW:
  11836. case taicpu(hp1).opsize of
  11837. S_WL:
  11838. begin
  11839. taicpu(p).opsize := S_BL;
  11840. RegUsed := True;
  11841. end;
  11842. {$ifdef x86_64}
  11843. S_WQ:
  11844. begin
  11845. if taicpu(p).opcode = A_MOVZX then
  11846. begin
  11847. taicpu(p).opsize := S_BL;
  11848. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11849. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11850. end
  11851. else
  11852. taicpu(p).opsize := S_BQ;
  11853. RegUsed := True;
  11854. end;
  11855. {$endif x86_64}
  11856. else
  11857. ;
  11858. end;
  11859. {$ifdef x86_64}
  11860. S_BL:
  11861. case taicpu(hp1).opsize of
  11862. S_LQ:
  11863. begin
  11864. if taicpu(p).opcode = A_MOVZX then
  11865. begin
  11866. taicpu(p).opsize := S_BL;
  11867. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11868. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11869. end
  11870. else
  11871. taicpu(p).opsize := S_BQ;
  11872. RegUsed := True;
  11873. end;
  11874. else
  11875. ;
  11876. end;
  11877. S_WL:
  11878. case taicpu(hp1).opsize of
  11879. S_LQ:
  11880. begin
  11881. if taicpu(p).opcode = A_MOVZX then
  11882. begin
  11883. taicpu(p).opsize := S_WL;
  11884. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11885. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11886. end
  11887. else
  11888. taicpu(p).opsize := S_WQ;
  11889. RegUsed := True;
  11890. end;
  11891. else
  11892. ;
  11893. end;
  11894. {$endif x86_64}
  11895. else
  11896. ;
  11897. end;
  11898. if RegUsed then
  11899. begin
  11900. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  11901. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  11902. RemoveInstruction(hp1);
  11903. Result := True;
  11904. Exit;
  11905. end;
  11906. end;
  11907. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  11908. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  11909. GetNextInstruction(hp1, hp2) and
  11910. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  11911. (
  11912. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  11913. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  11914. {$ifdef x86_64}
  11915. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  11916. {$endif x86_64}
  11917. ) and
  11918. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11919. (
  11920. (
  11921. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11922. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11923. ) or
  11924. (
  11925. { Only allow the operands in reverse order for TEST instructions }
  11926. (taicpu(hp2).opcode = A_TEST) and
  11927. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11928. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  11929. )
  11930. ) then
  11931. begin
  11932. {
  11933. For example:
  11934. movzbl %al,%eax
  11935. movzbl (ref),%edx
  11936. andl %edx,%eax
  11937. (%edx deallocated)
  11938. Change to:
  11939. andb (ref),%al
  11940. movzbl %al,%eax
  11941. Rules are:
  11942. - First two instructions have the same opcode and opsize
  11943. - First instruction's operands are the same super-register
  11944. - Second instruction operates on a different register
  11945. - Third instruction is AND, OR, XOR or TEST
  11946. - Third instruction's operands are the destination registers of the first two instructions
  11947. - Third instruction writes to the destination register of the first instruction (except with TEST)
  11948. - Second instruction's destination register is deallocated afterwards
  11949. }
  11950. TransferUsedRegs(TmpUsedRegs);
  11951. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11952. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11953. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  11954. begin
  11955. case taicpu(p).opsize of
  11956. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11957. NewSize := S_B;
  11958. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11959. NewSize := S_W;
  11960. {$ifdef x86_64}
  11961. S_LQ:
  11962. NewSize := S_L;
  11963. {$endif x86_64}
  11964. else
  11965. InternalError(2021120301);
  11966. end;
  11967. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  11968. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  11969. taicpu(hp2).opsize := NewSize;
  11970. RemoveInstruction(hp1);
  11971. { With TEST, it's best to keep the MOVX instruction at the top }
  11972. if (taicpu(hp2).opcode <> A_TEST) then
  11973. begin
  11974. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  11975. asml.Remove(p);
  11976. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  11977. asml.InsertAfter(p, hp2);
  11978. p := hp2;
  11979. end
  11980. else
  11981. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  11982. Result := True;
  11983. Exit;
  11984. end;
  11985. end;
  11986. end;
  11987. if taicpu(p).opcode=A_MOVZX then
  11988. begin
  11989. { removes superfluous And's after movzx's }
  11990. if reg_and_hp1_is_instr and
  11991. (taicpu(hp1).opcode = A_AND) and
  11992. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11993. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11994. {$ifdef x86_64}
  11995. { check for implicit extension to 64 bit }
  11996. or
  11997. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11998. (taicpu(hp1).opsize=S_Q) and
  11999. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12000. )
  12001. {$endif x86_64}
  12002. )
  12003. then
  12004. begin
  12005. case taicpu(p).opsize Of
  12006. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12007. if (taicpu(hp1).oper[0]^.val = $ff) then
  12008. begin
  12009. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12010. RemoveInstruction(hp1);
  12011. Result:=true;
  12012. exit;
  12013. end;
  12014. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12015. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12016. begin
  12017. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12018. RemoveInstruction(hp1);
  12019. Result:=true;
  12020. exit;
  12021. end;
  12022. {$ifdef x86_64}
  12023. S_LQ:
  12024. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12025. begin
  12026. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12027. RemoveInstruction(hp1);
  12028. Result:=true;
  12029. exit;
  12030. end;
  12031. {$endif x86_64}
  12032. else
  12033. ;
  12034. end;
  12035. { we cannot get rid of the and, but can we get rid of the movz ?}
  12036. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12037. begin
  12038. case taicpu(p).opsize Of
  12039. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12040. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12041. begin
  12042. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12043. RemoveCurrentP(p,hp1);
  12044. Result:=true;
  12045. exit;
  12046. end;
  12047. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12048. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12049. begin
  12050. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12051. RemoveCurrentP(p,hp1);
  12052. Result:=true;
  12053. exit;
  12054. end;
  12055. {$ifdef x86_64}
  12056. S_LQ:
  12057. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12058. begin
  12059. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12060. RemoveCurrentP(p,hp1);
  12061. Result:=true;
  12062. exit;
  12063. end;
  12064. {$endif x86_64}
  12065. else
  12066. ;
  12067. end;
  12068. end;
  12069. end;
  12070. { changes some movzx constructs to faster synonyms (all examples
  12071. are given with eax/ax, but are also valid for other registers)}
  12072. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12073. begin
  12074. case taicpu(p).opsize of
  12075. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12076. (the machine code is equivalent to movzbl %al,%eax), but the
  12077. code generator still generates that assembler instruction and
  12078. it is silently converted. This should probably be checked.
  12079. [Kit] }
  12080. S_BW:
  12081. begin
  12082. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12083. (
  12084. not IsMOVZXAcceptable
  12085. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12086. or (
  12087. (cs_opt_size in current_settings.optimizerswitches) and
  12088. (taicpu(p).oper[1]^.reg = NR_AX)
  12089. )
  12090. ) then
  12091. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12092. begin
  12093. DebugMsg(SPeepholeOptimization + 'var7',p);
  12094. taicpu(p).opcode := A_AND;
  12095. taicpu(p).changeopsize(S_W);
  12096. taicpu(p).loadConst(0,$ff);
  12097. Result := True;
  12098. end
  12099. else if not IsMOVZXAcceptable and
  12100. GetNextInstruction(p, hp1) and
  12101. (tai(hp1).typ = ait_instruction) and
  12102. (taicpu(hp1).opcode = A_AND) and
  12103. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12104. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12105. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12106. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12107. begin
  12108. DebugMsg(SPeepholeOptimization + 'var8',p);
  12109. taicpu(p).opcode := A_MOV;
  12110. taicpu(p).changeopsize(S_W);
  12111. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12112. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12113. Result := True;
  12114. end;
  12115. end;
  12116. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12117. S_BL:
  12118. if not IsMOVZXAcceptable then
  12119. begin
  12120. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12121. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12122. begin
  12123. DebugMsg(SPeepholeOptimization + 'var9',p);
  12124. taicpu(p).opcode := A_AND;
  12125. taicpu(p).changeopsize(S_L);
  12126. taicpu(p).loadConst(0,$ff);
  12127. Result := True;
  12128. end
  12129. else if GetNextInstruction(p, hp1) and
  12130. (tai(hp1).typ = ait_instruction) and
  12131. (taicpu(hp1).opcode = A_AND) and
  12132. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12133. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12134. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12135. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12136. begin
  12137. DebugMsg(SPeepholeOptimization + 'var10',p);
  12138. taicpu(p).opcode := A_MOV;
  12139. taicpu(p).changeopsize(S_L);
  12140. { do not use R_SUBWHOLE
  12141. as movl %rdx,%eax
  12142. is invalid in assembler PM }
  12143. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12144. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12145. Result := True;
  12146. end;
  12147. end;
  12148. {$endif i8086}
  12149. S_WL:
  12150. if not IsMOVZXAcceptable then
  12151. begin
  12152. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12153. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12154. begin
  12155. DebugMsg(SPeepholeOptimization + 'var11',p);
  12156. taicpu(p).opcode := A_AND;
  12157. taicpu(p).changeopsize(S_L);
  12158. taicpu(p).loadConst(0,$ffff);
  12159. Result := True;
  12160. end
  12161. else if GetNextInstruction(p, hp1) and
  12162. (tai(hp1).typ = ait_instruction) and
  12163. (taicpu(hp1).opcode = A_AND) and
  12164. (taicpu(hp1).oper[0]^.typ = top_const) and
  12165. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12166. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12167. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12168. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12169. begin
  12170. DebugMsg(SPeepholeOptimization + 'var12',p);
  12171. taicpu(p).opcode := A_MOV;
  12172. taicpu(p).changeopsize(S_L);
  12173. { do not use R_SUBWHOLE
  12174. as movl %rdx,%eax
  12175. is invalid in assembler PM }
  12176. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12177. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12178. Result := True;
  12179. end;
  12180. end;
  12181. else
  12182. InternalError(2017050705);
  12183. end;
  12184. end
  12185. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12186. begin
  12187. if GetNextInstruction(p, hp1) and
  12188. (tai(hp1).typ = ait_instruction) and
  12189. (taicpu(hp1).opcode = A_AND) and
  12190. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12191. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12192. begin
  12193. //taicpu(p).opcode := A_MOV;
  12194. case taicpu(p).opsize Of
  12195. S_BL:
  12196. begin
  12197. DebugMsg(SPeepholeOptimization + 'var13',p);
  12198. taicpu(hp1).changeopsize(S_L);
  12199. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12200. end;
  12201. S_WL:
  12202. begin
  12203. DebugMsg(SPeepholeOptimization + 'var14',p);
  12204. taicpu(hp1).changeopsize(S_L);
  12205. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12206. end;
  12207. S_BW:
  12208. begin
  12209. DebugMsg(SPeepholeOptimization + 'var15',p);
  12210. taicpu(hp1).changeopsize(S_W);
  12211. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12212. end;
  12213. else
  12214. Internalerror(2017050704)
  12215. end;
  12216. Result := True;
  12217. end;
  12218. end;
  12219. end;
  12220. end;
  12221. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12222. var
  12223. hp1, hp2 : tai;
  12224. MaskLength : Cardinal;
  12225. MaskedBits : TCgInt;
  12226. ActiveReg : TRegister;
  12227. begin
  12228. Result:=false;
  12229. { There are no optimisations for reference targets }
  12230. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12231. Exit;
  12232. while GetNextInstruction(p, hp1) and
  12233. (hp1.typ = ait_instruction) do
  12234. begin
  12235. if (taicpu(p).oper[0]^.typ = top_const) then
  12236. begin
  12237. case taicpu(hp1).opcode of
  12238. A_AND:
  12239. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12240. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12241. { the second register must contain the first one, so compare their subreg types }
  12242. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12243. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12244. { change
  12245. and const1, reg
  12246. and const2, reg
  12247. to
  12248. and (const1 and const2), reg
  12249. }
  12250. begin
  12251. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12252. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12253. RemoveCurrentP(p, hp1);
  12254. Result:=true;
  12255. exit;
  12256. end;
  12257. A_CMP:
  12258. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12259. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12260. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12261. { Just check that the condition on the next instruction is compatible }
  12262. GetNextInstruction(hp1, hp2) and
  12263. (hp2.typ = ait_instruction) and
  12264. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12265. then
  12266. { change
  12267. and 2^n, reg
  12268. cmp 2^n, reg
  12269. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12270. to
  12271. and 2^n, reg
  12272. test reg, reg
  12273. j(~c) / set(~c) / cmov(~c)
  12274. }
  12275. begin
  12276. { Keep TEST instruction in, rather than remove it, because
  12277. it may trigger other optimisations such as MovAndTest2Test }
  12278. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12279. taicpu(hp1).opcode := A_TEST;
  12280. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12281. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12282. Result := True;
  12283. Exit;
  12284. end;
  12285. A_MOVZX:
  12286. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12287. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12288. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12289. (
  12290. (
  12291. (taicpu(p).opsize=S_W) and
  12292. (taicpu(hp1).opsize=S_BW)
  12293. ) or
  12294. (
  12295. (taicpu(p).opsize=S_L) and
  12296. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12297. )
  12298. {$ifdef x86_64}
  12299. or
  12300. (
  12301. (taicpu(p).opsize=S_Q) and
  12302. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12303. )
  12304. {$endif x86_64}
  12305. ) then
  12306. begin
  12307. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12308. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12309. ) or
  12310. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12311. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12312. then
  12313. begin
  12314. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12315. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12316. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12317. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12318. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12319. }
  12320. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12321. RemoveInstruction(hp1);
  12322. { See if there are other optimisations possible }
  12323. Continue;
  12324. end;
  12325. end;
  12326. A_SHL:
  12327. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12328. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12329. begin
  12330. {$ifopt R+}
  12331. {$define RANGE_WAS_ON}
  12332. {$R-}
  12333. {$endif}
  12334. { get length of potential and mask }
  12335. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12336. { really a mask? }
  12337. {$ifdef RANGE_WAS_ON}
  12338. {$R+}
  12339. {$endif}
  12340. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12341. { unmasked part shifted out? }
  12342. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12343. begin
  12344. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12345. RemoveCurrentP(p, hp1);
  12346. Result:=true;
  12347. exit;
  12348. end;
  12349. end;
  12350. A_SHR:
  12351. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12352. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12353. (taicpu(hp1).oper[0]^.val <= 63) then
  12354. begin
  12355. { Does SHR combined with the AND cover all the bits?
  12356. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12357. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12358. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12359. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12360. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12361. begin
  12362. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12363. RemoveCurrentP(p, hp1);
  12364. Result := True;
  12365. Exit;
  12366. end;
  12367. end;
  12368. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12369. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12370. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12371. begin
  12372. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12373. (
  12374. (
  12375. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12376. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12377. ) or (
  12378. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12379. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12380. {$ifdef x86_64}
  12381. ) or (
  12382. (taicpu(hp1).opsize = S_LQ) and
  12383. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12384. {$endif x86_64}
  12385. )
  12386. ) then
  12387. begin
  12388. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12389. begin
  12390. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12391. RemoveInstruction(hp1);
  12392. { See if there are other optimisations possible }
  12393. Continue;
  12394. end;
  12395. { The super-registers are the same though.
  12396. Note that this change by itself doesn't improve
  12397. code speed, but it opens up other optimisations. }
  12398. {$ifdef x86_64}
  12399. { Convert 64-bit register to 32-bit }
  12400. case taicpu(hp1).opsize of
  12401. S_BQ:
  12402. begin
  12403. taicpu(hp1).opsize := S_BL;
  12404. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12405. end;
  12406. S_WQ:
  12407. begin
  12408. taicpu(hp1).opsize := S_WL;
  12409. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12410. end
  12411. else
  12412. ;
  12413. end;
  12414. {$endif x86_64}
  12415. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12416. taicpu(hp1).opcode := A_MOVZX;
  12417. { See if there are other optimisations possible }
  12418. Continue;
  12419. end;
  12420. end;
  12421. else
  12422. ;
  12423. end;
  12424. end
  12425. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12426. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12427. begin
  12428. {$ifdef x86_64}
  12429. if (taicpu(p).opsize = S_Q) then
  12430. begin
  12431. { Never necessary }
  12432. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12433. RemoveCurrentP(p, hp1);
  12434. Result := True;
  12435. Exit;
  12436. end;
  12437. {$endif x86_64}
  12438. { Forward check to determine necessity of and %reg,%reg }
  12439. TransferUsedRegs(TmpUsedRegs);
  12440. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12441. { Saves on a bunch of dereferences }
  12442. ActiveReg := taicpu(p).oper[1]^.reg;
  12443. case taicpu(hp1).opcode of
  12444. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12445. if (
  12446. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12447. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12448. ) and
  12449. (
  12450. (taicpu(hp1).opcode <> A_MOV) or
  12451. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12452. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12453. ) and
  12454. not (
  12455. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12456. (taicpu(hp1).opcode = A_MOV) and
  12457. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12458. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12459. ) and
  12460. (
  12461. (
  12462. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12463. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12464. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12465. ) or
  12466. (
  12467. {$ifdef x86_64}
  12468. (
  12469. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12470. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12471. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12472. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12473. ) and
  12474. {$endif x86_64}
  12475. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12476. )
  12477. ) then
  12478. begin
  12479. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12480. RemoveCurrentP(p, hp1);
  12481. Result := True;
  12482. Exit;
  12483. end;
  12484. A_ADD,
  12485. A_AND,
  12486. A_BSF,
  12487. A_BSR,
  12488. A_BTC,
  12489. A_BTR,
  12490. A_BTS,
  12491. A_OR,
  12492. A_SUB,
  12493. A_XOR:
  12494. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12495. if (
  12496. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12497. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12498. ) and
  12499. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12500. begin
  12501. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12502. RemoveCurrentP(p, hp1);
  12503. Result := True;
  12504. Exit;
  12505. end;
  12506. A_CMP,
  12507. A_TEST:
  12508. if (
  12509. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12510. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12511. ) and
  12512. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12513. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12514. begin
  12515. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12516. RemoveCurrentP(p, hp1);
  12517. Result := True;
  12518. Exit;
  12519. end;
  12520. A_BSWAP,
  12521. A_NEG,
  12522. A_NOT:
  12523. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12524. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12525. begin
  12526. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12527. RemoveCurrentP(p, hp1);
  12528. Result := True;
  12529. Exit;
  12530. end;
  12531. else
  12532. ;
  12533. end;
  12534. end;
  12535. if (taicpu(hp1).is_jmp) and
  12536. (taicpu(hp1).opcode<>A_JMP) and
  12537. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12538. begin
  12539. { change
  12540. and x, reg
  12541. jxx
  12542. to
  12543. test x, reg
  12544. jxx
  12545. if reg is deallocated before the
  12546. jump, but only if it's a conditional jump (PFV)
  12547. }
  12548. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12549. taicpu(p).opcode := A_TEST;
  12550. Exit;
  12551. end;
  12552. Break;
  12553. end;
  12554. { Lone AND tests }
  12555. if (taicpu(p).oper[0]^.typ = top_const) then
  12556. begin
  12557. {
  12558. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12559. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12560. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12561. }
  12562. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12563. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12564. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12565. begin
  12566. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12567. if taicpu(p).opsize = S_L then
  12568. begin
  12569. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12570. Result := True;
  12571. end;
  12572. end;
  12573. end;
  12574. { Backward check to determine necessity of and %reg,%reg }
  12575. if (taicpu(p).oper[0]^.typ = top_reg) and
  12576. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12577. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12578. GetLastInstruction(p, hp2) and
  12579. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12580. { Check size of adjacent instruction to determine if the AND is
  12581. effectively a null operation }
  12582. (
  12583. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12584. { Note: Don't include S_Q }
  12585. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12586. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12587. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  12588. ) then
  12589. begin
  12590. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  12591. { If GetNextInstruction returned False, hp1 will be nil }
  12592. RemoveCurrentP(p, hp1);
  12593. Result := True;
  12594. Exit;
  12595. end;
  12596. end;
  12597. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  12598. var
  12599. hp1, hp2: tai;
  12600. NewRef: TReference;
  12601. Distance: Cardinal;
  12602. TempTracking: TAllUsedRegs;
  12603. { This entire nested function is used in an if-statement below, but we
  12604. want to avoid all the used reg transfers and GetNextInstruction calls
  12605. until we really have to check }
  12606. function MemRegisterNotUsedLater: Boolean; inline;
  12607. var
  12608. hp2: tai;
  12609. begin
  12610. TransferUsedRegs(TmpUsedRegs);
  12611. hp2 := p;
  12612. repeat
  12613. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12614. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12615. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  12616. end;
  12617. begin
  12618. Result := False;
  12619. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12620. (taicpu(p).oper[1]^.typ = top_reg) then
  12621. begin
  12622. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12623. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12624. (hp1.typ <> ait_instruction) or
  12625. not
  12626. (
  12627. (cs_opt_level3 in current_settings.optimizerswitches) or
  12628. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12629. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12630. ) then
  12631. Exit;
  12632. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12633. addq $x, %rax
  12634. movq %rax, %rdx
  12635. sarq $63, %rdx
  12636. (%rax still in use)
  12637. ...letting OptPass2ADD run its course (and without -Os) will produce:
  12638. leaq $x(%rax),%rdx
  12639. addq $x, %rax
  12640. sarq $63, %rdx
  12641. ...which is okay since it breaks the dependency chain between
  12642. addq and movq, but if OptPass2MOV is called first:
  12643. addq $x, %rax
  12644. cqto
  12645. ...which is better in all ways, taking only 2 cycles to execute
  12646. and much smaller in code size.
  12647. }
  12648. { The extra register tracking is quite strenuous }
  12649. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12650. MatchInstruction(hp1, A_MOV, []) then
  12651. begin
  12652. { Update the register tracking to the MOV instruction }
  12653. CopyUsedRegs(TempTracking);
  12654. hp2 := p;
  12655. repeat
  12656. UpdateUsedRegs(tai(hp2.Next));
  12657. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12658. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12659. OptPass2ADD get called again }
  12660. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12661. begin
  12662. { Reset the tracking to the current instruction }
  12663. RestoreUsedRegs(TempTracking);
  12664. ReleaseUsedRegs(TempTracking);
  12665. Result := True;
  12666. Exit;
  12667. end;
  12668. { Reset the tracking to the current instruction }
  12669. RestoreUsedRegs(TempTracking);
  12670. ReleaseUsedRegs(TempTracking);
  12671. { If OptPass2MOV returned True, we don't need to set Result to
  12672. True if hp1 didn't change because the ADD instruction didn't
  12673. get modified and we'll be evaluating hp1 again when the
  12674. peephole optimizer reaches it }
  12675. end;
  12676. { Change:
  12677. add %reg2,%reg1
  12678. (%reg2 not modified in between)
  12679. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  12680. To:
  12681. mov/s/z #(%reg1,%reg2),%reg1
  12682. }
  12683. if (taicpu(p).oper[0]^.typ = top_reg) and
  12684. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  12685. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  12686. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  12687. (
  12688. (
  12689. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  12690. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  12691. { r/esp cannot be an index }
  12692. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  12693. ) or (
  12694. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  12695. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  12696. )
  12697. ) and (
  12698. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  12699. (
  12700. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  12701. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12702. MemRegisterNotUsedLater
  12703. )
  12704. ) then
  12705. begin
  12706. if (
  12707. { Instructions are guaranteed to be adjacent on -O2 and under }
  12708. (cs_opt_level3 in current_settings.optimizerswitches) and
  12709. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  12710. ) then
  12711. begin
  12712. { If the other register is used in between, move the MOV
  12713. instruction to right after the ADD instruction so a
  12714. saving can still be made }
  12715. Asml.Remove(hp1);
  12716. Asml.InsertAfter(hp1, p);
  12717. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12718. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12719. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  12720. RemoveCurrentp(p, hp1);
  12721. end
  12722. else
  12723. begin
  12724. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  12725. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12726. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12727. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  12728. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12729. { hp1 may not be the immediate next instruction under -O3 }
  12730. RemoveCurrentp(p)
  12731. else
  12732. RemoveCurrentp(p, hp1);
  12733. end;
  12734. Result := True;
  12735. Exit;
  12736. end;
  12737. { Change:
  12738. addl/q $x,%reg1
  12739. movl/q %reg1,%reg2
  12740. To:
  12741. leal/q $x(%reg1),%reg2
  12742. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12743. Breaks the dependency chain.
  12744. }
  12745. if (taicpu(p).oper[0]^.typ = top_const) and
  12746. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12747. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12748. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12749. (
  12750. { Instructions are guaranteed to be adjacent on -O2 and under }
  12751. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12752. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12753. ) then
  12754. begin
  12755. TransferUsedRegs(TmpUsedRegs);
  12756. hp2 := p;
  12757. repeat
  12758. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12759. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12760. if (
  12761. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  12762. not (cs_opt_size in current_settings.optimizerswitches) or
  12763. (
  12764. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12765. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12766. )
  12767. ) then
  12768. begin
  12769. { Change the MOV instruction to a LEA instruction, and update the
  12770. first operand }
  12771. reference_reset(NewRef, 1, []);
  12772. NewRef.base := taicpu(p).oper[1]^.reg;
  12773. NewRef.scalefactor := 1;
  12774. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  12775. taicpu(hp1).opcode := A_LEA;
  12776. taicpu(hp1).loadref(0, NewRef);
  12777. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12778. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12779. begin
  12780. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12781. { Move what is now the LEA instruction to before the ADD instruction }
  12782. Asml.Remove(hp1);
  12783. Asml.InsertBefore(hp1, p);
  12784. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12785. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  12786. p := hp1;
  12787. end
  12788. else
  12789. begin
  12790. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12791. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  12792. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12793. { hp1 may not be the immediate next instruction under -O3 }
  12794. RemoveCurrentp(p)
  12795. else
  12796. RemoveCurrentp(p, hp1);
  12797. end;
  12798. Result := True;
  12799. end;
  12800. end;
  12801. end;
  12802. end;
  12803. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  12804. var
  12805. SubReg: TSubRegister;
  12806. begin
  12807. Result:=false;
  12808. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  12809. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12810. with taicpu(p).oper[0]^.ref^ do
  12811. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  12812. begin
  12813. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  12814. begin
  12815. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  12816. taicpu(p).opcode := A_ADD;
  12817. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  12818. Result := True;
  12819. end
  12820. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  12821. begin
  12822. if (base <> NR_NO) then
  12823. begin
  12824. if (scalefactor <= 1) then
  12825. begin
  12826. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  12827. taicpu(p).opcode := A_ADD;
  12828. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  12829. Result := True;
  12830. end;
  12831. end
  12832. else
  12833. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  12834. if (scalefactor in [2, 4, 8]) then
  12835. begin
  12836. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  12837. taicpu(p).loadconst(0, BsrByte(scalefactor));
  12838. taicpu(p).opcode := A_SHL;
  12839. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  12840. Result := True;
  12841. end;
  12842. end;
  12843. end;
  12844. end;
  12845. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  12846. var
  12847. hp1, hp2: tai;
  12848. NewRef: TReference;
  12849. Distance: Cardinal;
  12850. TempTracking: TAllUsedRegs;
  12851. begin
  12852. Result := False;
  12853. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12854. MatchOpType(taicpu(p),top_const,top_reg) then
  12855. begin
  12856. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12857. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12858. (hp1.typ <> ait_instruction) or
  12859. not
  12860. (
  12861. (cs_opt_level3 in current_settings.optimizerswitches) or
  12862. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12863. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12864. ) then
  12865. Exit;
  12866. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12867. subq $x, %rax
  12868. movq %rax, %rdx
  12869. sarq $63, %rdx
  12870. (%rax still in use)
  12871. ...letting OptPass2SUB run its course (and without -Os) will produce:
  12872. leaq $-x(%rax),%rdx
  12873. movq $x, %rax
  12874. sarq $63, %rdx
  12875. ...which is okay since it breaks the dependency chain between
  12876. subq and movq, but if OptPass2MOV is called first:
  12877. subq $x, %rax
  12878. cqto
  12879. ...which is better in all ways, taking only 2 cycles to execute
  12880. and much smaller in code size.
  12881. }
  12882. { The extra register tracking is quite strenuous }
  12883. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12884. MatchInstruction(hp1, A_MOV, []) then
  12885. begin
  12886. { Update the register tracking to the MOV instruction }
  12887. CopyUsedRegs(TempTracking);
  12888. hp2 := p;
  12889. repeat
  12890. UpdateUsedRegs(tai(hp2.Next));
  12891. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12892. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12893. OptPass2SUB get called again }
  12894. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12895. begin
  12896. { Reset the tracking to the current instruction }
  12897. RestoreUsedRegs(TempTracking);
  12898. ReleaseUsedRegs(TempTracking);
  12899. Result := True;
  12900. Exit;
  12901. end;
  12902. { Reset the tracking to the current instruction }
  12903. RestoreUsedRegs(TempTracking);
  12904. ReleaseUsedRegs(TempTracking);
  12905. { If OptPass2MOV returned True, we don't need to set Result to
  12906. True if hp1 didn't change because the SUB instruction didn't
  12907. get modified and we'll be evaluating hp1 again when the
  12908. peephole optimizer reaches it }
  12909. end;
  12910. { Change:
  12911. subl/q $x,%reg1
  12912. movl/q %reg1,%reg2
  12913. To:
  12914. leal/q $-x(%reg1),%reg2
  12915. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12916. Breaks the dependency chain and potentially permits the removal of
  12917. a CMP instruction if one follows.
  12918. }
  12919. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12920. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12921. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12922. (
  12923. { Instructions are guaranteed to be adjacent on -O2 and under }
  12924. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12925. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12926. ) then
  12927. begin
  12928. TransferUsedRegs(TmpUsedRegs);
  12929. hp2 := p;
  12930. repeat
  12931. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12932. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12933. if (
  12934. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  12935. not (cs_opt_size in current_settings.optimizerswitches) or
  12936. (
  12937. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12938. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12939. )
  12940. ) then
  12941. begin
  12942. { Change the MOV instruction to a LEA instruction, and update the
  12943. first operand }
  12944. reference_reset(NewRef, 1, []);
  12945. NewRef.base := taicpu(p).oper[1]^.reg;
  12946. NewRef.scalefactor := 1;
  12947. NewRef.offset := -taicpu(p).oper[0]^.val;
  12948. taicpu(hp1).opcode := A_LEA;
  12949. taicpu(hp1).loadref(0, NewRef);
  12950. TransferUsedRegs(TmpUsedRegs);
  12951. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12952. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12953. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12954. begin
  12955. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12956. { Move what is now the LEA instruction to before the SUB instruction }
  12957. Asml.Remove(hp1);
  12958. Asml.InsertBefore(hp1, p);
  12959. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12960. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  12961. p := hp1;
  12962. end
  12963. else
  12964. begin
  12965. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12966. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  12967. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12968. { hp1 may not be the immediate next instruction under -O3 }
  12969. RemoveCurrentp(p)
  12970. else
  12971. RemoveCurrentp(p, hp1);
  12972. end;
  12973. Result := True;
  12974. end;
  12975. end;
  12976. end;
  12977. end;
  12978. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  12979. begin
  12980. { we can skip all instructions not messing with the stack pointer }
  12981. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  12982. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  12983. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  12984. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  12985. ({(taicpu(hp1).ops=0) or }
  12986. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  12987. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  12988. ) and }
  12989. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  12990. )
  12991. ) do
  12992. GetNextInstruction(hp1,hp1);
  12993. Result:=assigned(hp1);
  12994. end;
  12995. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  12996. var
  12997. hp1, hp2, hp3, hp4, hp5: tai;
  12998. begin
  12999. Result:=false;
  13000. hp5:=nil;
  13001. { replace
  13002. leal(q) x(<stackpointer>),<stackpointer>
  13003. call procname
  13004. leal(q) -x(<stackpointer>),<stackpointer>
  13005. ret
  13006. by
  13007. jmp procname
  13008. but do it only on level 4 because it destroys stack back traces
  13009. }
  13010. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13011. MatchOpType(taicpu(p),top_ref,top_reg) and
  13012. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13013. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13014. { the -8 or -24 are not required, but bail out early if possible,
  13015. higher values are unlikely }
  13016. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13017. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13018. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13019. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13020. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13021. GetNextInstruction(p, hp1) and
  13022. { Take a copy of hp1 }
  13023. SetAndTest(hp1, hp4) and
  13024. { trick to skip label }
  13025. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13026. SkipSimpleInstructions(hp1) and
  13027. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13028. GetNextInstruction(hp1, hp2) and
  13029. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13030. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13031. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13032. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13033. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13034. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13035. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13036. { Segment register will be NR_NO }
  13037. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13038. GetNextInstruction(hp2, hp3) and
  13039. { trick to skip label }
  13040. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13041. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13042. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13043. SetAndTest(hp3,hp5) and
  13044. GetNextInstruction(hp3,hp3) and
  13045. MatchInstruction(hp3,A_RET,[S_NO])
  13046. )
  13047. ) and
  13048. (taicpu(hp3).ops=0) then
  13049. begin
  13050. taicpu(hp1).opcode := A_JMP;
  13051. taicpu(hp1).is_jmp := true;
  13052. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13053. RemoveCurrentP(p, hp4);
  13054. RemoveInstruction(hp2);
  13055. RemoveInstruction(hp3);
  13056. if Assigned(hp5) then
  13057. begin
  13058. AsmL.Remove(hp5);
  13059. ASmL.InsertBefore(hp5,hp1)
  13060. end;
  13061. Result:=true;
  13062. end;
  13063. end;
  13064. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13065. {$ifdef x86_64}
  13066. var
  13067. hp1, hp2, hp3, hp4, hp5: tai;
  13068. {$endif x86_64}
  13069. begin
  13070. Result:=false;
  13071. {$ifdef x86_64}
  13072. hp5:=nil;
  13073. { replace
  13074. push %rax
  13075. call procname
  13076. pop %rcx
  13077. ret
  13078. by
  13079. jmp procname
  13080. but do it only on level 4 because it destroys stack back traces
  13081. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13082. for all supported calling conventions
  13083. }
  13084. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13085. MatchOpType(taicpu(p),top_reg) and
  13086. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13087. GetNextInstruction(p, hp1) and
  13088. { Take a copy of hp1 }
  13089. SetAndTest(hp1, hp4) and
  13090. { trick to skip label }
  13091. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13092. SkipSimpleInstructions(hp1) and
  13093. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13094. GetNextInstruction(hp1, hp2) and
  13095. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13096. MatchOpType(taicpu(hp2),top_reg) and
  13097. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13098. GetNextInstruction(hp2, hp3) and
  13099. { trick to skip label }
  13100. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13101. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13102. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13103. SetAndTest(hp3,hp5) and
  13104. GetNextInstruction(hp3,hp3) and
  13105. MatchInstruction(hp3,A_RET,[S_NO])
  13106. )
  13107. ) and
  13108. (taicpu(hp3).ops=0) then
  13109. begin
  13110. taicpu(hp1).opcode := A_JMP;
  13111. taicpu(hp1).is_jmp := true;
  13112. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13113. RemoveCurrentP(p, hp4);
  13114. RemoveInstruction(hp2);
  13115. RemoveInstruction(hp3);
  13116. if Assigned(hp5) then
  13117. begin
  13118. AsmL.Remove(hp5);
  13119. ASmL.InsertBefore(hp5,hp1)
  13120. end;
  13121. Result:=true;
  13122. end;
  13123. {$endif x86_64}
  13124. end;
  13125. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13126. var
  13127. Value, RegName: string;
  13128. begin
  13129. Result:=false;
  13130. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13131. begin
  13132. case taicpu(p).oper[0]^.val of
  13133. 0:
  13134. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13135. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13136. begin
  13137. { change "mov $0,%reg" into "xor %reg,%reg" }
  13138. taicpu(p).opcode := A_XOR;
  13139. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13140. Result := True;
  13141. {$ifdef x86_64}
  13142. end
  13143. else if (taicpu(p).opsize = S_Q) then
  13144. begin
  13145. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13146. { The actual optimization }
  13147. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13148. taicpu(p).changeopsize(S_L);
  13149. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13150. Result := True;
  13151. end;
  13152. $1..$FFFFFFFF:
  13153. begin
  13154. { Code size reduction by J. Gareth "Kit" Moreton }
  13155. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13156. case taicpu(p).opsize of
  13157. S_Q:
  13158. begin
  13159. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13160. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13161. { The actual optimization }
  13162. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13163. taicpu(p).changeopsize(S_L);
  13164. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13165. Result := True;
  13166. end;
  13167. else
  13168. { Do nothing };
  13169. end;
  13170. {$endif x86_64}
  13171. end;
  13172. -1:
  13173. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13174. if (cs_opt_size in current_settings.optimizerswitches) and
  13175. (taicpu(p).opsize <> S_B) and
  13176. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13177. begin
  13178. { change "mov $-1,%reg" into "or $-1,%reg" }
  13179. { NOTES:
  13180. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13181. - This operation creates a false dependency on the register, so only do it when optimising for size
  13182. - 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
  13183. }
  13184. taicpu(p).opcode := A_OR;
  13185. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13186. Result := True;
  13187. end;
  13188. else
  13189. { Do nothing };
  13190. end;
  13191. end;
  13192. end;
  13193. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13194. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13195. begin
  13196. Result := False;
  13197. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13198. Exit;
  13199. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13200. so don't bother optimising }
  13201. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13202. Exit;
  13203. if (taicpu(p).oper[0]^.typ <> top_const) or
  13204. { If the value can fit into an 8-bit signed integer, a smaller
  13205. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13206. falls within this range }
  13207. (
  13208. (taicpu(p).oper[0]^.val > -128) and
  13209. (taicpu(p).oper[0]^.val <= 127)
  13210. ) then
  13211. Exit;
  13212. { If we're optimising for size, this is acceptable }
  13213. if (cs_opt_size in current_settings.optimizerswitches) then
  13214. Exit(True);
  13215. if (taicpu(p).oper[1]^.typ = top_reg) and
  13216. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13217. Exit(True);
  13218. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13219. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13220. Exit(True);
  13221. end;
  13222. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13223. var
  13224. hp1: tai;
  13225. Value: TCGInt;
  13226. begin
  13227. Result := False;
  13228. if MatchOpType(taicpu(p), top_const, top_reg) then
  13229. begin
  13230. { Detect:
  13231. andw x, %ax (0 <= x < $8000)
  13232. ...
  13233. movzwl %ax,%eax
  13234. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13235. }
  13236. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13237. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13238. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13239. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13240. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13241. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13242. begin
  13243. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13244. taicpu(hp1).opcode := A_CWDE;
  13245. taicpu(hp1).clearop(0);
  13246. taicpu(hp1).clearop(1);
  13247. taicpu(hp1).ops := 0;
  13248. { A change was made, but not with p, so move forward 1 }
  13249. p := tai(p.Next);
  13250. Result := True;
  13251. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13252. end;
  13253. end;
  13254. { If "not x" is a power of 2 (popcnt = 1), change:
  13255. and $x, %reg/ref
  13256. To:
  13257. btr lb(x), %reg/ref
  13258. }
  13259. if IsBTXAcceptable(p) and
  13260. (
  13261. { Make sure a TEST doesn't follow that plays with the register }
  13262. not GetNextInstruction(p, hp1) or
  13263. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13264. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13265. ) then
  13266. begin
  13267. {$push}{$R-}{$Q-}
  13268. { Value is a sign-extended 32-bit integer - just correct it
  13269. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13270. checks to see if this operand is an immediate. }
  13271. Value := not taicpu(p).oper[0]^.val;
  13272. {$pop}
  13273. {$ifdef x86_64}
  13274. if taicpu(p).opsize = S_L then
  13275. {$endif x86_64}
  13276. Value := Value and $FFFFFFFF;
  13277. if (PopCnt(QWord(Value)) = 1) then
  13278. begin
  13279. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13280. taicpu(p).opcode := A_BTR;
  13281. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13282. Result := True;
  13283. Exit;
  13284. end;
  13285. end;
  13286. end;
  13287. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13288. begin
  13289. Result := False;
  13290. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13291. Exit;
  13292. { Convert:
  13293. movswl %ax,%eax -> cwtl
  13294. movslq %eax,%rax -> cdqe
  13295. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13296. refer to the same opcode and depends only on the assembler's
  13297. current operand-size attribute. [Kit]
  13298. }
  13299. with taicpu(p) do
  13300. case opsize of
  13301. S_WL:
  13302. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13303. begin
  13304. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13305. opcode := A_CWDE;
  13306. clearop(0);
  13307. clearop(1);
  13308. ops := 0;
  13309. Result := True;
  13310. end;
  13311. {$ifdef x86_64}
  13312. S_LQ:
  13313. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13314. begin
  13315. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13316. opcode := A_CDQE;
  13317. clearop(0);
  13318. clearop(1);
  13319. ops := 0;
  13320. Result := True;
  13321. end;
  13322. {$endif x86_64}
  13323. else
  13324. ;
  13325. end;
  13326. end;
  13327. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13328. var
  13329. hp1, hp2: tai;
  13330. IdentityMask, Shift: TCGInt;
  13331. LimitSize: Topsize;
  13332. DoNotMerge: Boolean;
  13333. begin
  13334. Result := False;
  13335. { All these optimisations work on "shr const,%reg" }
  13336. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13337. Exit;
  13338. DoNotMerge := False;
  13339. Shift := taicpu(p).oper[0]^.val;
  13340. LimitSize := taicpu(p).opsize;
  13341. hp1 := p;
  13342. repeat
  13343. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13344. Break;
  13345. { Detect:
  13346. shr x, %reg
  13347. and y, %reg
  13348. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13349. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13350. }
  13351. case taicpu(hp1).opcode of
  13352. A_AND:
  13353. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13354. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13355. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13356. begin
  13357. { Make sure the FLAGS register isn't in use }
  13358. TransferUsedRegs(TmpUsedRegs);
  13359. hp2 := p;
  13360. repeat
  13361. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13362. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13363. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13364. begin
  13365. { Generate the identity mask }
  13366. case taicpu(p).opsize of
  13367. S_B:
  13368. IdentityMask := $FF shr Shift;
  13369. S_W:
  13370. IdentityMask := $FFFF shr Shift;
  13371. S_L:
  13372. IdentityMask := $FFFFFFFF shr Shift;
  13373. {$ifdef x86_64}
  13374. S_Q:
  13375. { We need to force the operands to be unsigned 64-bit
  13376. integers otherwise the wrong value is generated }
  13377. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13378. {$endif x86_64}
  13379. else
  13380. InternalError(2022081501);
  13381. end;
  13382. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13383. begin
  13384. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13385. { All the possible 1 bits are covered, so we can remove the AND }
  13386. hp2 := tai(hp1.Previous);
  13387. RemoveInstruction(hp1);
  13388. { p wasn't actually changed, so don't set Result to True,
  13389. but a change was nonetheless made elsewhere }
  13390. Include(OptsToCheck, aoc_ForceNewIteration);
  13391. { Do another pass in case other AND or MOVZX instructions
  13392. follow }
  13393. hp1 := hp2;
  13394. Continue;
  13395. end;
  13396. end;
  13397. end;
  13398. A_TEST, A_CMP, A_Jcc:
  13399. { Skip over conditional jumps and relevant comparisons }
  13400. Continue;
  13401. A_MOVZX:
  13402. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13403. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13404. begin
  13405. { Since the original register is being read as is, subsequent
  13406. SHRs must not be merged at this point }
  13407. DoNotMerge := True;
  13408. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13409. begin
  13410. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13411. begin
  13412. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13413. { All the possible 1 bits are covered, so we can remove the AND }
  13414. hp2 := tai(hp1.Previous);
  13415. RemoveInstruction(hp1);
  13416. hp1 := hp2;
  13417. end
  13418. else { Different register target }
  13419. begin
  13420. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13421. taicpu(hp1).opcode := A_MOV;
  13422. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13423. case taicpu(hp1).opsize of
  13424. S_BW:
  13425. taicpu(hp1).opsize := S_W;
  13426. S_BL, S_WL:
  13427. taicpu(hp1).opsize := S_L;
  13428. else
  13429. InternalError(2022081503);
  13430. end;
  13431. end;
  13432. end
  13433. else if (Shift > 0) and
  13434. (taicpu(p).opsize = S_W) and
  13435. (taicpu(hp1).opsize = S_WL) and
  13436. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13437. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13438. begin
  13439. { Detect:
  13440. shr x, %ax (x > 0)
  13441. ...
  13442. movzwl %ax,%eax
  13443. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13444. }
  13445. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13446. taicpu(hp1).opcode := A_CWDE;
  13447. taicpu(hp1).clearop(0);
  13448. taicpu(hp1).clearop(1);
  13449. taicpu(hp1).ops := 0;
  13450. end;
  13451. { Move onto the next instruction }
  13452. Continue;
  13453. end;
  13454. A_SHL, A_SAL, A_SHR:
  13455. if (taicpu(hp1).opsize <= LimitSize) and
  13456. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13457. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13458. begin
  13459. { Make sure the sizes don't exceed the register size limit
  13460. (measured by the shift value falling below the limit) }
  13461. if taicpu(hp1).opsize < LimitSize then
  13462. LimitSize := taicpu(hp1).opsize;
  13463. if taicpu(hp1).opcode = A_SHR then
  13464. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13465. else
  13466. begin
  13467. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13468. DoNotMerge := True;
  13469. end;
  13470. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13471. Break;
  13472. { Since we've established that the combined shift is within
  13473. limits, we can actually combine the adjacent SHR
  13474. instructions even if they're different sizes }
  13475. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13476. begin
  13477. hp2 := tai(hp1.Previous);
  13478. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13479. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13480. RemoveInstruction(hp1);
  13481. hp1 := hp2;
  13482. end;
  13483. { Move onto the next instruction }
  13484. Continue;
  13485. end;
  13486. else
  13487. ;
  13488. end;
  13489. Break;
  13490. until False;
  13491. { Detect the following (looking backwards):
  13492. shr %cl,%reg
  13493. shr x, %reg
  13494. Swap the two SHR instructions to minimise a pipeline stall.
  13495. }
  13496. if GetLastInstruction(p, hp1) and
  13497. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13498. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13499. { First operand will be %cl }
  13500. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13501. { Just to be sure }
  13502. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13503. begin
  13504. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13505. { Moving the entries this way ensures the register tracking remains correct }
  13506. Asml.Remove(p);
  13507. Asml.InsertBefore(p, hp1);
  13508. p := hp1;
  13509. { Don't set Result to True because the current instruction is now
  13510. "shr %cl,%reg" and there's nothing more we can do with it }
  13511. end;
  13512. end;
  13513. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13514. var
  13515. hp1, hp2: tai;
  13516. Opposite, SecondOpposite: TAsmOp;
  13517. NewCond: TAsmCond;
  13518. begin
  13519. Result := False;
  13520. { Change:
  13521. add/sub 128,(dest)
  13522. To:
  13523. sub/add -128,(dest)
  13524. This generaally takes fewer bytes to encode because -128 can be stored
  13525. in a signed byte, whereas +128 cannot.
  13526. }
  13527. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13528. begin
  13529. if taicpu(p).opcode = A_ADD then
  13530. Opposite := A_SUB
  13531. else
  13532. Opposite := A_ADD;
  13533. { Be careful if the flags are in use, because the CF flag inverts
  13534. when changing from ADD to SUB and vice versa }
  13535. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13536. GetNextInstruction(p, hp1) then
  13537. begin
  13538. TransferUsedRegs(TmpUsedRegs);
  13539. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13540. hp2 := hp1;
  13541. { Scan ahead to check if everything's safe }
  13542. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13543. begin
  13544. if (hp1.typ <> ait_instruction) then
  13545. { Probably unsafe since the flags are still in use }
  13546. Exit;
  13547. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13548. { Stop searching at an unconditional jump }
  13549. Break;
  13550. if not
  13551. (
  13552. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13553. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13554. ) and
  13555. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13556. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13557. Exit;
  13558. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13559. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13560. { Move to the next instruction }
  13561. GetNextInstruction(hp1, hp1);
  13562. end;
  13563. while Assigned(hp2) and (hp2 <> hp1) do
  13564. begin
  13565. NewCond := C_None;
  13566. case taicpu(hp2).condition of
  13567. C_A, C_NBE:
  13568. NewCond := C_BE;
  13569. C_B, C_C, C_NAE:
  13570. NewCond := C_AE;
  13571. C_AE, C_NB, C_NC:
  13572. NewCond := C_B;
  13573. C_BE, C_NA:
  13574. NewCond := C_A;
  13575. else
  13576. { No change needed };
  13577. end;
  13578. if NewCond <> C_None then
  13579. begin
  13580. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13581. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13582. taicpu(hp2).condition := NewCond;
  13583. end
  13584. else
  13585. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13586. begin
  13587. { Because of the flipping of the carry bit, to ensure
  13588. the operation remains equivalent, ADC becomes SBB
  13589. and vice versa, and the constant is not-inverted.
  13590. If multiple ADCs or SBBs appear in a row, each one
  13591. changed causes the carry bit to invert, so they all
  13592. need to be flipped }
  13593. if taicpu(hp2).opcode = A_ADC then
  13594. SecondOpposite := A_SBB
  13595. else
  13596. SecondOpposite := A_ADC;
  13597. if taicpu(hp2).oper[0]^.typ <> top_const then
  13598. { Should have broken out of this optimisation already }
  13599. InternalError(2021112901);
  13600. 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]^) + ' -> ' +
  13601. 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);
  13602. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  13603. taicpu(hp2).opcode := SecondOpposite;
  13604. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  13605. end;
  13606. { Move to the next instruction }
  13607. GetNextInstruction(hp2, hp2);
  13608. end;
  13609. if (hp2 <> hp1) then
  13610. InternalError(2021111501);
  13611. end;
  13612. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  13613. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  13614. taicpu(p).opcode := Opposite;
  13615. taicpu(p).oper[0]^.val := -128;
  13616. { No further optimisations can be made on this instruction, so move
  13617. onto the next one to save time }
  13618. p := tai(p.Next);
  13619. UpdateUsedRegs(p);
  13620. Result := True;
  13621. Exit;
  13622. end;
  13623. { Detect:
  13624. add/sub %reg2,(dest)
  13625. add/sub x, (dest)
  13626. (dest can be a register or a reference)
  13627. Swap the instructions to minimise a pipeline stall. This reverses the
  13628. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  13629. optimisations could be made.
  13630. }
  13631. if (taicpu(p).oper[0]^.typ = top_reg) and
  13632. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  13633. (
  13634. (
  13635. (taicpu(p).oper[1]^.typ = top_reg) and
  13636. { We can try searching further ahead if we're writing to a register }
  13637. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  13638. ) or
  13639. (
  13640. (taicpu(p).oper[1]^.typ = top_ref) and
  13641. GetNextInstruction(p, hp1)
  13642. )
  13643. ) and
  13644. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  13645. (taicpu(hp1).oper[0]^.typ = top_const) and
  13646. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  13647. begin
  13648. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  13649. TransferUsedRegs(TmpUsedRegs);
  13650. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13651. hp2 := p;
  13652. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  13653. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  13654. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  13655. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13656. begin
  13657. asml.remove(hp1);
  13658. asml.InsertBefore(hp1, p);
  13659. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  13660. Result := True;
  13661. end;
  13662. end;
  13663. end;
  13664. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  13665. begin
  13666. Result:=false;
  13667. { change "cmp $0, %reg" to "test %reg, %reg" }
  13668. if MatchOpType(taicpu(p),top_const,top_reg) and
  13669. (taicpu(p).oper[0]^.val = 0) then
  13670. begin
  13671. taicpu(p).opcode := A_TEST;
  13672. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  13673. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  13674. Result:=true;
  13675. end;
  13676. end;
  13677. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  13678. var
  13679. IsTestConstX, IsValid : Boolean;
  13680. hp1,hp2 : tai;
  13681. begin
  13682. Result:=false;
  13683. { If x is a power of 2 (popcnt = 1), change:
  13684. or $x, %reg/ref
  13685. To:
  13686. bts lb(x), %reg/ref
  13687. }
  13688. if (taicpu(p).opcode = A_OR) and
  13689. IsBTXAcceptable(p) and
  13690. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  13691. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13692. (
  13693. { Don't optimise if a test instruction follows }
  13694. not GetNextInstruction(p, hp1) or
  13695. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  13696. ) then
  13697. begin
  13698. 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);
  13699. taicpu(p).opcode := A_BTS;
  13700. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13701. Result := True;
  13702. Exit;
  13703. end;
  13704. { If x is a power of 2 (popcnt = 1), change:
  13705. test $x, %reg/ref
  13706. je / sete / cmove (or jne / setne)
  13707. To:
  13708. bt lb(x), %reg/ref
  13709. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  13710. }
  13711. if (taicpu(p).opcode = A_TEST) and
  13712. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  13713. (taicpu(p).oper[0]^.typ = top_const) and
  13714. (
  13715. (cs_opt_size in current_settings.optimizerswitches) or
  13716. (
  13717. (taicpu(p).oper[1]^.typ = top_reg) and
  13718. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13719. ) or
  13720. (
  13721. (taicpu(p).oper[1]^.typ <> top_reg) and
  13722. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13723. )
  13724. ) and
  13725. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13726. { For sizes less than S_L, the byte size is equal or larger with BT,
  13727. so don't bother optimising }
  13728. (taicpu(p).opsize >= S_L) then
  13729. begin
  13730. IsValid := True;
  13731. { Check the next set of instructions, watching the FLAGS register
  13732. and the conditions used }
  13733. TransferUsedRegs(TmpUsedRegs);
  13734. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13735. hp1 := p;
  13736. hp2 := nil;
  13737. while GetNextInstruction(hp1, hp1) do
  13738. begin
  13739. if not Assigned(hp2) then
  13740. { The first instruction after TEST }
  13741. hp2 := hp1;
  13742. if (hp1.typ <> ait_instruction) then
  13743. begin
  13744. { If the flags are no longer in use, everything is fine }
  13745. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13746. IsValid := False;
  13747. Break;
  13748. end;
  13749. case taicpu(hp1).condition of
  13750. C_None:
  13751. begin
  13752. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13753. { Something is not quite normal, so play safe and don't change }
  13754. IsValid := False;
  13755. Break;
  13756. end;
  13757. C_E, C_Z, C_NE, C_NZ:
  13758. { This is fine };
  13759. else
  13760. begin
  13761. { Unsupported condition }
  13762. IsValid := False;
  13763. Break;
  13764. end;
  13765. end;
  13766. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13767. end;
  13768. if IsValid then
  13769. begin
  13770. while hp2 <> hp1 do
  13771. begin
  13772. case taicpu(hp2).condition of
  13773. C_Z, C_E:
  13774. taicpu(hp2).condition := C_NC;
  13775. C_NZ, C_NE:
  13776. taicpu(hp2).condition := C_C;
  13777. else
  13778. { Should not get this by this point }
  13779. InternalError(2022110701);
  13780. end;
  13781. GetNextInstruction(hp2, hp2);
  13782. end;
  13783. 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);
  13784. taicpu(p).opcode := A_BT;
  13785. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13786. Result := True;
  13787. Exit;
  13788. end;
  13789. end;
  13790. { removes the line marked with (x) from the sequence
  13791. and/or/xor/add/sub/... $x, %y
  13792. test/or %y, %y | test $-1, %y (x)
  13793. j(n)z _Label
  13794. as the first instruction already adjusts the ZF
  13795. %y operand may also be a reference }
  13796. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  13797. MatchOperand(taicpu(p).oper[0]^,-1);
  13798. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  13799. GetLastInstruction(p, hp1) and
  13800. (tai(hp1).typ = ait_instruction) and
  13801. GetNextInstruction(p,hp2) and
  13802. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  13803. case taicpu(hp1).opcode Of
  13804. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  13805. { These two instructions set the zero flag if the result is zero }
  13806. A_POPCNT, A_LZCNT:
  13807. begin
  13808. if (
  13809. { With POPCNT, an input of zero will set the zero flag
  13810. because the population count of zero is zero }
  13811. (taicpu(hp1).opcode = A_POPCNT) and
  13812. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  13813. (
  13814. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  13815. { Faster than going through the second half of the 'or'
  13816. condition below }
  13817. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  13818. )
  13819. ) or (
  13820. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  13821. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13822. { and in case of carry for A(E)/B(E)/C/NC }
  13823. (
  13824. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  13825. (
  13826. (taicpu(hp1).opcode <> A_ADD) and
  13827. (taicpu(hp1).opcode <> A_SUB) and
  13828. (taicpu(hp1).opcode <> A_LZCNT)
  13829. )
  13830. )
  13831. ) then
  13832. begin
  13833. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  13834. RemoveCurrentP(p, hp2);
  13835. Result:=true;
  13836. Exit;
  13837. end;
  13838. end;
  13839. A_SHL, A_SAL, A_SHR, A_SAR:
  13840. begin
  13841. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  13842. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  13843. { therefore, it's only safe to do this optimization for }
  13844. { shifts by a (nonzero) constant }
  13845. (taicpu(hp1).oper[0]^.typ = top_const) and
  13846. (taicpu(hp1).oper[0]^.val <> 0) and
  13847. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13848. { and in case of carry for A(E)/B(E)/C/NC }
  13849. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13850. begin
  13851. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  13852. RemoveCurrentP(p, hp2);
  13853. Result:=true;
  13854. Exit;
  13855. end;
  13856. end;
  13857. A_DEC, A_INC, A_NEG:
  13858. begin
  13859. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  13860. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13861. { and in case of carry for A(E)/B(E)/C/NC }
  13862. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13863. begin
  13864. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  13865. RemoveCurrentP(p, hp2);
  13866. Result:=true;
  13867. Exit;
  13868. end;
  13869. end;
  13870. A_ANDN, A_BZHI:
  13871. begin
  13872. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  13873. { Only the zero and sign flags are consistent with what the result is }
  13874. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  13875. begin
  13876. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  13877. RemoveCurrentP(p, hp2);
  13878. Result:=true;
  13879. Exit;
  13880. end;
  13881. end;
  13882. A_BEXTR:
  13883. begin
  13884. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  13885. { Only the zero flag is set }
  13886. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13887. begin
  13888. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  13889. RemoveCurrentP(p, hp2);
  13890. Result:=true;
  13891. Exit;
  13892. end;
  13893. end;
  13894. else
  13895. ;
  13896. end; { case }
  13897. { change "test $-1,%reg" into "test %reg,%reg" }
  13898. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  13899. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  13900. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  13901. if MatchInstruction(p, A_OR, []) and
  13902. { Can only match if they're both registers }
  13903. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  13904. begin
  13905. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  13906. taicpu(p).opcode := A_TEST;
  13907. { No need to set Result to True, as we've done all the optimisations we can }
  13908. end;
  13909. end;
  13910. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  13911. var
  13912. hp1,hp3 : tai;
  13913. {$ifndef x86_64}
  13914. hp2 : taicpu;
  13915. {$endif x86_64}
  13916. begin
  13917. Result:=false;
  13918. hp3:=nil;
  13919. {$ifndef x86_64}
  13920. { don't do this on modern CPUs, this really hurts them due to
  13921. broken call/ret pairing }
  13922. if (current_settings.optimizecputype < cpu_Pentium2) and
  13923. not(cs_create_pic in current_settings.moduleswitches) and
  13924. GetNextInstruction(p, hp1) and
  13925. MatchInstruction(hp1,A_JMP,[S_NO]) and
  13926. MatchOpType(taicpu(hp1),top_ref) and
  13927. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  13928. begin
  13929. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  13930. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  13931. InsertLLItem(p.previous, p, hp2);
  13932. taicpu(p).opcode := A_JMP;
  13933. taicpu(p).is_jmp := true;
  13934. RemoveInstruction(hp1);
  13935. Result:=true;
  13936. end
  13937. else
  13938. {$endif x86_64}
  13939. { replace
  13940. call procname
  13941. ret
  13942. by
  13943. jmp procname
  13944. but do it only on level 4 because it destroys stack back traces
  13945. else if the subroutine is marked as no return, remove the ret
  13946. }
  13947. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  13948. (po_noreturn in current_procinfo.procdef.procoptions)) and
  13949. GetNextInstruction(p, hp1) and
  13950. (MatchInstruction(hp1,A_RET,[S_NO]) or
  13951. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  13952. SetAndTest(hp1,hp3) and
  13953. GetNextInstruction(hp1,hp1) and
  13954. MatchInstruction(hp1,A_RET,[S_NO])
  13955. )
  13956. ) and
  13957. (taicpu(hp1).ops=0) then
  13958. begin
  13959. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13960. { we might destroy stack alignment here if we do not do a call }
  13961. (target_info.stackalign<=sizeof(SizeUInt)) then
  13962. begin
  13963. taicpu(p).opcode := A_JMP;
  13964. taicpu(p).is_jmp := true;
  13965. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  13966. end
  13967. else
  13968. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  13969. RemoveInstruction(hp1);
  13970. if Assigned(hp3) then
  13971. begin
  13972. AsmL.Remove(hp3);
  13973. AsmL.InsertBefore(hp3,p)
  13974. end;
  13975. Result:=true;
  13976. end;
  13977. end;
  13978. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  13979. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  13980. begin
  13981. case OpSize of
  13982. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13983. Result := (Val <= $FF) and (Val >= -128);
  13984. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13985. Result := (Val <= $FFFF) and (Val >= -32768);
  13986. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  13987. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  13988. else
  13989. Result := True;
  13990. end;
  13991. end;
  13992. var
  13993. hp1, hp2 : tai;
  13994. SizeChange: Boolean;
  13995. PreMessage: string;
  13996. begin
  13997. Result := False;
  13998. if (taicpu(p).oper[0]^.typ = top_reg) and
  13999. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14000. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14001. begin
  14002. { Change (using movzbl %al,%eax as an example):
  14003. movzbl %al, %eax movzbl %al, %eax
  14004. cmpl x, %eax testl %eax,%eax
  14005. To:
  14006. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14007. movzbl %al, %eax movzbl %al, %eax
  14008. Smaller instruction and minimises pipeline stall as the CPU
  14009. doesn't have to wait for the register to get zero-extended. [Kit]
  14010. Also allow if the smaller of the two registers is being checked,
  14011. as this still removes the false dependency.
  14012. }
  14013. if
  14014. (
  14015. (
  14016. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14017. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14018. ) or (
  14019. { If MatchOperand returns True, they must both be registers }
  14020. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14021. )
  14022. ) and
  14023. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14024. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14025. begin
  14026. 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);
  14027. asml.Remove(hp1);
  14028. asml.InsertBefore(hp1, p);
  14029. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14030. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14031. begin
  14032. taicpu(hp1).opcode := A_TEST;
  14033. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14034. end;
  14035. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14036. case taicpu(p).opsize of
  14037. S_BW, S_BL:
  14038. begin
  14039. SizeChange := taicpu(hp1).opsize <> S_B;
  14040. taicpu(hp1).changeopsize(S_B);
  14041. end;
  14042. S_WL:
  14043. begin
  14044. SizeChange := taicpu(hp1).opsize <> S_W;
  14045. taicpu(hp1).changeopsize(S_W);
  14046. end
  14047. else
  14048. InternalError(2020112701);
  14049. end;
  14050. UpdateUsedRegs(tai(p.Next));
  14051. { Check if the register is used aferwards - if not, we can
  14052. remove the movzx instruction completely }
  14053. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14054. begin
  14055. { Hp1 is a better position than p for debugging purposes }
  14056. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14057. RemoveCurrentp(p, hp1);
  14058. Result := True;
  14059. end;
  14060. if SizeChange then
  14061. DebugMsg(SPeepholeOptimization + PreMessage +
  14062. 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)
  14063. else
  14064. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14065. Exit;
  14066. end;
  14067. { Change (using movzwl %ax,%eax as an example):
  14068. movzwl %ax, %eax
  14069. movb %al, (dest) (Register is smaller than read register in movz)
  14070. To:
  14071. movb %al, (dest) (Move one back to avoid a false dependency)
  14072. movzwl %ax, %eax
  14073. }
  14074. if (taicpu(hp1).opcode = A_MOV) and
  14075. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14076. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14077. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14078. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14079. begin
  14080. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14081. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14082. asml.Remove(hp1);
  14083. asml.InsertBefore(hp1, p);
  14084. if taicpu(hp1).oper[1]^.typ = top_reg then
  14085. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14086. { Check if the register is used aferwards - if not, we can
  14087. remove the movzx instruction completely }
  14088. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14089. begin
  14090. { Hp1 is a better position than p for debugging purposes }
  14091. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14092. RemoveCurrentp(p, hp1);
  14093. Result := True;
  14094. end;
  14095. Exit;
  14096. end;
  14097. end;
  14098. end;
  14099. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14100. var
  14101. hp1: tai;
  14102. {$ifdef x86_64}
  14103. PreMessage, RegName: string;
  14104. {$endif x86_64}
  14105. begin
  14106. Result := False;
  14107. { If x is a power of 2 (popcnt = 1), change:
  14108. xor $x, %reg/ref
  14109. To:
  14110. btc lb(x), %reg/ref
  14111. }
  14112. if IsBTXAcceptable(p) and
  14113. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14114. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14115. (
  14116. { Don't optimise if a test instruction follows }
  14117. not GetNextInstruction(p, hp1) or
  14118. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14119. ) then
  14120. begin
  14121. 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);
  14122. taicpu(p).opcode := A_BTC;
  14123. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14124. Result := True;
  14125. Exit;
  14126. end;
  14127. {$ifdef x86_64}
  14128. { Code size reduction by J. Gareth "Kit" Moreton }
  14129. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14130. as this removes the REX prefix }
  14131. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14132. Exit;
  14133. if taicpu(p).oper[0]^.typ <> top_reg then
  14134. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14135. InternalError(2018011500);
  14136. case taicpu(p).opsize of
  14137. S_Q:
  14138. begin
  14139. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14140. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14141. { The actual optimization }
  14142. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14143. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14144. taicpu(p).changeopsize(S_L);
  14145. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14146. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14147. end;
  14148. else
  14149. ;
  14150. end;
  14151. {$endif x86_64}
  14152. end;
  14153. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14154. var
  14155. XReg: TRegister;
  14156. begin
  14157. Result := False;
  14158. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14159. Smaller encoding and slightly faster on some platforms (also works for
  14160. ZMM-sized registers) }
  14161. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14162. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14163. begin
  14164. XReg := taicpu(p).oper[0]^.reg;
  14165. if (taicpu(p).oper[1]^.reg = XReg) then
  14166. begin
  14167. taicpu(p).changeopsize(S_XMM);
  14168. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14169. if (cs_opt_size in current_settings.optimizerswitches) then
  14170. begin
  14171. { Change input registers to %xmm0 to reduce size. Note that
  14172. there's a risk of a false dependency doing this, so only
  14173. optimise for size here }
  14174. XReg := NR_XMM0;
  14175. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14176. end
  14177. else
  14178. begin
  14179. setsubreg(XReg, R_SUBMMX);
  14180. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14181. end;
  14182. taicpu(p).oper[0]^.reg := XReg;
  14183. taicpu(p).oper[1]^.reg := XReg;
  14184. Result := True;
  14185. end;
  14186. end;
  14187. end;
  14188. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14189. var
  14190. OperIdx: Integer;
  14191. begin
  14192. for OperIdx := 0 to p.ops - 1 do
  14193. if p.oper[OperIdx]^.typ = top_ref then
  14194. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14195. end;
  14196. end.