aoptx86.pas 666 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517
  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 : 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_regname(r: TRegister): string; inline;
  1088. begin
  1089. Result := '%' + std_regname(r);
  1090. end;
  1091. { Debug output function - creates a string representation of an operator }
  1092. function debug_operstr(oper: TOper): string;
  1093. begin
  1094. case oper.typ of
  1095. top_const:
  1096. Result := '$' + debug_tostr(oper.val);
  1097. top_reg:
  1098. Result := debug_regname(oper.reg);
  1099. top_ref:
  1100. begin
  1101. if oper.ref^.offset <> 0 then
  1102. Result := debug_tostr(oper.ref^.offset) + '('
  1103. else
  1104. Result := '(';
  1105. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1106. begin
  1107. Result := Result + debug_regname(oper.ref^.base);
  1108. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1109. Result := Result + ',' + debug_regname(oper.ref^.index);
  1110. end
  1111. else
  1112. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1113. Result := Result + debug_regname(oper.ref^.index);
  1114. if (oper.ref^.scalefactor > 1) then
  1115. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1116. else
  1117. Result := Result + ')';
  1118. end;
  1119. else
  1120. Result := '[UNKNOWN]';
  1121. end;
  1122. end;
  1123. function debug_op2str(opcode: tasmop): string; inline;
  1124. begin
  1125. Result := std_op2str[opcode];
  1126. end;
  1127. function debug_opsize2str(opsize: topsize): string; inline;
  1128. begin
  1129. Result := gas_opsize2str[opsize];
  1130. end;
  1131. {$else DEBUG_AOPTCPU}
  1132. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1133. begin
  1134. end;
  1135. function debug_tostr(i: tcgint): string; inline;
  1136. begin
  1137. Result := '';
  1138. end;
  1139. function debug_regname(r: TRegister): string; inline;
  1140. begin
  1141. Result := '';
  1142. end;
  1143. function debug_operstr(oper: TOper): string; inline;
  1144. begin
  1145. Result := '';
  1146. end;
  1147. function debug_op2str(opcode: tasmop): string; inline;
  1148. begin
  1149. Result := '';
  1150. end;
  1151. function debug_opsize2str(opsize: topsize): string; inline;
  1152. begin
  1153. Result := '';
  1154. end;
  1155. {$endif DEBUG_AOPTCPU}
  1156. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1157. begin
  1158. {$ifdef x86_64}
  1159. { Always fine on x86-64 }
  1160. Result := True;
  1161. {$else x86_64}
  1162. Result :=
  1163. {$ifdef i8086}
  1164. (current_settings.cputype >= cpu_386) and
  1165. {$endif i8086}
  1166. (
  1167. { Always accept if optimising for size }
  1168. (cs_opt_size in current_settings.optimizerswitches) or
  1169. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1170. (current_settings.optimizecputype >= cpu_Pentium2)
  1171. );
  1172. {$endif x86_64}
  1173. end;
  1174. { Attempts to allocate a volatile integer register for use between p and hp,
  1175. using AUsedRegs for the current register usage information. Returns NR_NO
  1176. if no free register could be found }
  1177. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1178. var
  1179. RegSet: TCPURegisterSet;
  1180. CurrentSuperReg: Integer;
  1181. CurrentReg: TRegister;
  1182. Currentp: tai;
  1183. Breakout: Boolean;
  1184. begin
  1185. Result := NR_NO;
  1186. RegSet :=
  1187. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1188. current_procinfo.saved_regs_int;
  1189. for CurrentSuperReg in RegSet do
  1190. begin
  1191. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1192. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1193. {$if defined(i386) or defined(i8086)}
  1194. { If the target size is 8-bit, make sure we can actually encode it }
  1195. and (
  1196. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1197. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1198. )
  1199. {$endif i386 or i8086}
  1200. then
  1201. begin
  1202. Currentp := p;
  1203. Breakout := False;
  1204. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1205. begin
  1206. case Currentp.typ of
  1207. ait_instruction:
  1208. begin
  1209. if RegInInstruction(CurrentReg, Currentp) then
  1210. begin
  1211. Breakout := True;
  1212. Break;
  1213. end;
  1214. { Cannot allocate across an unconditional jump }
  1215. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1216. Exit;
  1217. end;
  1218. ait_marker:
  1219. { Don't try anything more if a marker is hit }
  1220. Exit;
  1221. ait_regalloc:
  1222. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1223. begin
  1224. Breakout := True;
  1225. Break;
  1226. end;
  1227. else
  1228. ;
  1229. end;
  1230. end;
  1231. if Breakout then
  1232. { Try the next register }
  1233. Continue;
  1234. { We have a free register available }
  1235. Result := CurrentReg;
  1236. if not DontAlloc then
  1237. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1238. Exit;
  1239. end;
  1240. end;
  1241. end;
  1242. { Attempts to allocate a volatile MM register for use between p and hp,
  1243. using AUsedRegs for the current register usage information. Returns NR_NO
  1244. if no free register could be found }
  1245. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1246. var
  1247. RegSet: TCPURegisterSet;
  1248. CurrentSuperReg: Integer;
  1249. CurrentReg: TRegister;
  1250. Currentp: tai;
  1251. Breakout: Boolean;
  1252. begin
  1253. Result := NR_NO;
  1254. RegSet :=
  1255. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1256. current_procinfo.saved_regs_mm;
  1257. for CurrentSuperReg in RegSet do
  1258. begin
  1259. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1260. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1261. begin
  1262. Currentp := p;
  1263. Breakout := False;
  1264. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1265. begin
  1266. case Currentp.typ of
  1267. ait_instruction:
  1268. begin
  1269. if RegInInstruction(CurrentReg, Currentp) then
  1270. begin
  1271. Breakout := True;
  1272. Break;
  1273. end;
  1274. { Cannot allocate across an unconditional jump }
  1275. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1276. Exit;
  1277. end;
  1278. ait_marker:
  1279. { Don't try anything more if a marker is hit }
  1280. Exit;
  1281. ait_regalloc:
  1282. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1283. begin
  1284. Breakout := True;
  1285. Break;
  1286. end;
  1287. else
  1288. ;
  1289. end;
  1290. end;
  1291. if Breakout then
  1292. { Try the next register }
  1293. Continue;
  1294. { We have a free register available }
  1295. Result := CurrentReg;
  1296. if not DontAlloc then
  1297. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1298. Exit;
  1299. end;
  1300. end;
  1301. end;
  1302. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1303. begin
  1304. if not SuperRegistersEqual(reg1,reg2) then
  1305. exit(false);
  1306. if getregtype(reg1)<>R_INTREGISTER then
  1307. exit(true); {because SuperRegisterEqual is true}
  1308. case getsubreg(reg1) of
  1309. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1310. higher, it preserves the high bits, so the new value depends on
  1311. reg2's previous value. In other words, it is equivalent to doing:
  1312. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1313. R_SUBL:
  1314. exit(getsubreg(reg2)=R_SUBL);
  1315. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1316. higher, it actually does a:
  1317. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1318. R_SUBH:
  1319. exit(getsubreg(reg2)=R_SUBH);
  1320. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1321. bits of reg2:
  1322. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1323. R_SUBW:
  1324. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1325. { a write to R_SUBD always overwrites every other subregister,
  1326. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1327. R_SUBD,
  1328. R_SUBQ:
  1329. exit(true);
  1330. else
  1331. internalerror(2017042801);
  1332. end;
  1333. end;
  1334. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1335. begin
  1336. if not SuperRegistersEqual(reg1,reg2) then
  1337. exit(false);
  1338. if getregtype(reg1)<>R_INTREGISTER then
  1339. exit(true); {because SuperRegisterEqual is true}
  1340. case getsubreg(reg1) of
  1341. R_SUBL:
  1342. exit(getsubreg(reg2)<>R_SUBH);
  1343. R_SUBH:
  1344. exit(getsubreg(reg2)<>R_SUBL);
  1345. R_SUBW,
  1346. R_SUBD,
  1347. R_SUBQ:
  1348. exit(true);
  1349. else
  1350. internalerror(2017042802);
  1351. end;
  1352. end;
  1353. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1354. var
  1355. hp1 : tai;
  1356. l : TCGInt;
  1357. begin
  1358. result:=false;
  1359. { changes the code sequence
  1360. shr/sar const1, x
  1361. shl const2, x
  1362. to
  1363. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1364. if GetNextInstruction(p, hp1) and
  1365. MatchInstruction(hp1,A_SHL,[]) and
  1366. (taicpu(p).oper[0]^.typ = top_const) and
  1367. (taicpu(hp1).oper[0]^.typ = top_const) and
  1368. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1369. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1370. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1371. begin
  1372. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1373. not(cs_opt_size in current_settings.optimizerswitches) then
  1374. begin
  1375. { shr/sar const1, %reg
  1376. shl const2, %reg
  1377. with const1 > const2 }
  1378. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1379. taicpu(hp1).opcode := A_AND;
  1380. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1381. case taicpu(p).opsize Of
  1382. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1383. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1384. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1385. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1386. else
  1387. Internalerror(2017050703)
  1388. end;
  1389. end
  1390. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1391. not(cs_opt_size in current_settings.optimizerswitches) then
  1392. begin
  1393. { shr/sar const1, %reg
  1394. shl const2, %reg
  1395. with const1 < const2 }
  1396. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1397. taicpu(p).opcode := A_AND;
  1398. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1399. case taicpu(p).opsize Of
  1400. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1401. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1402. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1403. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1404. else
  1405. Internalerror(2017050702)
  1406. end;
  1407. end
  1408. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1409. begin
  1410. { shr/sar const1, %reg
  1411. shl const2, %reg
  1412. with const1 = const2 }
  1413. taicpu(p).opcode := A_AND;
  1414. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1415. case taicpu(p).opsize Of
  1416. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1417. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1418. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1419. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1420. else
  1421. Internalerror(2017050701)
  1422. end;
  1423. RemoveInstruction(hp1);
  1424. end;
  1425. end;
  1426. end;
  1427. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1428. var
  1429. opsize : topsize;
  1430. hp1, hp2 : tai;
  1431. tmpref : treference;
  1432. ShiftValue : Cardinal;
  1433. BaseValue : TCGInt;
  1434. begin
  1435. result:=false;
  1436. opsize:=taicpu(p).opsize;
  1437. { changes certain "imul const, %reg"'s to lea sequences }
  1438. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1439. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1440. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1441. if (taicpu(p).oper[0]^.val = 1) then
  1442. if (taicpu(p).ops = 2) then
  1443. { remove "imul $1, reg" }
  1444. begin
  1445. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1446. Result := RemoveCurrentP(p);
  1447. end
  1448. else
  1449. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1450. begin
  1451. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1452. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1453. asml.InsertAfter(hp1, p);
  1454. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1455. RemoveCurrentP(p, hp1);
  1456. Result := True;
  1457. end
  1458. else if ((taicpu(p).ops <= 2) or
  1459. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1460. not(cs_opt_size in current_settings.optimizerswitches) and
  1461. (not(GetNextInstruction(p, hp1)) or
  1462. not((tai(hp1).typ = ait_instruction) and
  1463. ((taicpu(hp1).opcode=A_Jcc) and
  1464. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1465. begin
  1466. {
  1467. imul X, reg1, reg2 to
  1468. lea (reg1,reg1,Y), reg2
  1469. shl ZZ,reg2
  1470. imul XX, reg1 to
  1471. lea (reg1,reg1,YY), reg1
  1472. shl ZZ,reg2
  1473. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1474. it does not exist as a separate optimization target in FPC though.
  1475. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1476. at most two zeros
  1477. }
  1478. reference_reset(tmpref,1,[]);
  1479. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1480. begin
  1481. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1482. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1483. TmpRef.base := taicpu(p).oper[1]^.reg;
  1484. TmpRef.index := taicpu(p).oper[1]^.reg;
  1485. if not(BaseValue in [3,5,9]) then
  1486. Internalerror(2018110101);
  1487. TmpRef.ScaleFactor := BaseValue-1;
  1488. if (taicpu(p).ops = 2) then
  1489. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1490. else
  1491. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1492. AsmL.InsertAfter(hp1,p);
  1493. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1494. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1495. RemoveCurrentP(p, hp1);
  1496. if ShiftValue>0 then
  1497. begin
  1498. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1499. AsmL.InsertAfter(hp2,hp1);
  1500. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1501. end;
  1502. Result := True;
  1503. end;
  1504. end;
  1505. end;
  1506. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1507. begin
  1508. Result := False;
  1509. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1510. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1511. begin
  1512. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1513. taicpu(p).opcode := A_MOV;
  1514. Result := True;
  1515. end;
  1516. end;
  1517. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1518. var
  1519. p: taicpu absolute hp; { Implicit typecast }
  1520. i: Integer;
  1521. begin
  1522. Result := False;
  1523. if not assigned(hp) or
  1524. (hp.typ <> ait_instruction) then
  1525. Exit;
  1526. Prefetch(insprop[p.opcode]);
  1527. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1528. with insprop[p.opcode] do
  1529. begin
  1530. case getsubreg(reg) of
  1531. R_SUBW,R_SUBD,R_SUBQ:
  1532. Result:=
  1533. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1534. uncommon flags are checked first }
  1535. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1536. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1537. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1538. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1539. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1540. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1541. R_SUBFLAGCARRY:
  1542. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1543. R_SUBFLAGPARITY:
  1544. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1545. R_SUBFLAGAUXILIARY:
  1546. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1547. R_SUBFLAGZERO:
  1548. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1549. R_SUBFLAGSIGN:
  1550. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1551. R_SUBFLAGOVERFLOW:
  1552. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1553. R_SUBFLAGINTERRUPT:
  1554. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1555. R_SUBFLAGDIRECTION:
  1556. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1557. else
  1558. internalerror(2017050501);
  1559. end;
  1560. exit;
  1561. end;
  1562. { Handle special cases first }
  1563. case p.opcode of
  1564. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1565. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1566. begin
  1567. Result :=
  1568. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1569. (p.oper[1]^.typ = top_reg) and
  1570. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1571. (
  1572. (p.oper[0]^.typ = top_const) or
  1573. (
  1574. (p.oper[0]^.typ = top_reg) and
  1575. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1576. ) or (
  1577. (p.oper[0]^.typ = top_ref) and
  1578. not RegInRef(reg,p.oper[0]^.ref^)
  1579. )
  1580. );
  1581. end;
  1582. A_MUL, A_IMUL:
  1583. Result :=
  1584. (
  1585. (p.ops=3) and { IMUL only }
  1586. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1587. (
  1588. (
  1589. (p.oper[1]^.typ=top_reg) and
  1590. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1591. ) or (
  1592. (p.oper[1]^.typ=top_ref) and
  1593. not RegInRef(reg,p.oper[1]^.ref^)
  1594. )
  1595. )
  1596. ) or (
  1597. (
  1598. (p.ops=1) and
  1599. (
  1600. (
  1601. (
  1602. (p.oper[0]^.typ=top_reg) and
  1603. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1604. )
  1605. ) or (
  1606. (p.oper[0]^.typ=top_ref) and
  1607. not RegInRef(reg,p.oper[0]^.ref^)
  1608. )
  1609. ) and (
  1610. (
  1611. (p.opsize=S_B) and
  1612. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1613. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1614. ) or (
  1615. (p.opsize=S_W) and
  1616. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1617. ) or (
  1618. (p.opsize=S_L) and
  1619. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1620. {$ifdef x86_64}
  1621. ) or (
  1622. (p.opsize=S_Q) and
  1623. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1624. {$endif x86_64}
  1625. )
  1626. )
  1627. )
  1628. );
  1629. A_CBW:
  1630. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1631. {$ifndef x86_64}
  1632. A_LDS:
  1633. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1634. A_LES:
  1635. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1636. {$endif not x86_64}
  1637. A_LFS:
  1638. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1639. A_LGS:
  1640. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1641. A_LSS:
  1642. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1643. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1644. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1645. A_LODSB:
  1646. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1647. A_LODSW:
  1648. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1649. {$ifdef x86_64}
  1650. A_LODSQ:
  1651. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1652. {$endif x86_64}
  1653. A_LODSD:
  1654. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1655. A_FSTSW, A_FNSTSW:
  1656. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1657. else
  1658. begin
  1659. with insprop[p.opcode] do
  1660. begin
  1661. if (
  1662. { xor %reg,%reg etc. is classed as a new value }
  1663. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1664. MatchOpType(p, top_reg, top_reg) and
  1665. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1666. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1667. ) then
  1668. begin
  1669. Result := True;
  1670. Exit;
  1671. end;
  1672. { Make sure the entire register is overwritten }
  1673. if (getregtype(reg) = R_INTREGISTER) then
  1674. begin
  1675. if (p.ops > 0) then
  1676. begin
  1677. if RegInOp(reg, p.oper[0]^) then
  1678. begin
  1679. if (p.oper[0]^.typ = top_ref) then
  1680. begin
  1681. if RegInRef(reg, p.oper[0]^.ref^) then
  1682. begin
  1683. Result := False;
  1684. Exit;
  1685. end;
  1686. end
  1687. else if (p.oper[0]^.typ = top_reg) then
  1688. begin
  1689. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1690. begin
  1691. Result := False;
  1692. Exit;
  1693. end
  1694. else if ([Ch_WOp1]*Ch<>[]) then
  1695. begin
  1696. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1697. Result := True
  1698. else
  1699. begin
  1700. Result := False;
  1701. Exit;
  1702. end;
  1703. end;
  1704. end;
  1705. end;
  1706. if (p.ops > 1) then
  1707. begin
  1708. if RegInOp(reg, p.oper[1]^) then
  1709. begin
  1710. if (p.oper[1]^.typ = top_ref) then
  1711. begin
  1712. if RegInRef(reg, p.oper[1]^.ref^) then
  1713. begin
  1714. Result := False;
  1715. Exit;
  1716. end;
  1717. end
  1718. else if (p.oper[1]^.typ = top_reg) then
  1719. begin
  1720. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1721. begin
  1722. Result := False;
  1723. Exit;
  1724. end
  1725. else if ([Ch_WOp2]*Ch<>[]) then
  1726. begin
  1727. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1728. Result := True
  1729. else
  1730. begin
  1731. Result := False;
  1732. Exit;
  1733. end;
  1734. end;
  1735. end;
  1736. end;
  1737. if (p.ops > 2) then
  1738. begin
  1739. if RegInOp(reg, p.oper[2]^) then
  1740. begin
  1741. if (p.oper[2]^.typ = top_ref) then
  1742. begin
  1743. if RegInRef(reg, p.oper[2]^.ref^) then
  1744. begin
  1745. Result := False;
  1746. Exit;
  1747. end;
  1748. end
  1749. else if (p.oper[2]^.typ = top_reg) then
  1750. begin
  1751. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1752. begin
  1753. Result := False;
  1754. Exit;
  1755. end
  1756. else if ([Ch_WOp3]*Ch<>[]) then
  1757. begin
  1758. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1759. Result := True
  1760. else
  1761. begin
  1762. Result := False;
  1763. Exit;
  1764. end;
  1765. end;
  1766. end;
  1767. end;
  1768. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1769. begin
  1770. if (p.oper[3]^.typ = top_ref) then
  1771. begin
  1772. if RegInRef(reg, p.oper[3]^.ref^) then
  1773. begin
  1774. Result := False;
  1775. Exit;
  1776. end;
  1777. end
  1778. else if (p.oper[3]^.typ = top_reg) then
  1779. begin
  1780. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1781. begin
  1782. Result := False;
  1783. Exit;
  1784. end
  1785. else if ([Ch_WOp4]*Ch<>[]) then
  1786. begin
  1787. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1788. Result := True
  1789. else
  1790. begin
  1791. Result := False;
  1792. Exit;
  1793. end;
  1794. end;
  1795. end;
  1796. end;
  1797. end;
  1798. end;
  1799. end;
  1800. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1801. case getsupreg(reg) of
  1802. RS_EAX:
  1803. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1804. begin
  1805. Result := True;
  1806. Exit;
  1807. end;
  1808. RS_ECX:
  1809. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1810. begin
  1811. Result := True;
  1812. Exit;
  1813. end;
  1814. RS_EDX:
  1815. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1816. begin
  1817. Result := True;
  1818. Exit;
  1819. end;
  1820. RS_EBX:
  1821. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1822. begin
  1823. Result := True;
  1824. Exit;
  1825. end;
  1826. RS_ESP:
  1827. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1828. begin
  1829. Result := True;
  1830. Exit;
  1831. end;
  1832. RS_EBP:
  1833. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1834. begin
  1835. Result := True;
  1836. Exit;
  1837. end;
  1838. RS_ESI:
  1839. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1840. begin
  1841. Result := True;
  1842. Exit;
  1843. end;
  1844. RS_EDI:
  1845. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1846. begin
  1847. Result := True;
  1848. Exit;
  1849. end;
  1850. else
  1851. ;
  1852. end;
  1853. end;
  1854. end;
  1855. end;
  1856. end;
  1857. end;
  1858. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1859. var
  1860. hp2,hp3 : tai;
  1861. begin
  1862. { some x86-64 issue a NOP before the real exit code }
  1863. if MatchInstruction(p,A_NOP,[]) then
  1864. GetNextInstruction(p,p);
  1865. result:=assigned(p) and (p.typ=ait_instruction) and
  1866. ((taicpu(p).opcode = A_RET) or
  1867. ((taicpu(p).opcode=A_LEAVE) and
  1868. GetNextInstruction(p,hp2) and
  1869. MatchInstruction(hp2,A_RET,[S_NO])
  1870. ) or
  1871. (((taicpu(p).opcode=A_LEA) and
  1872. MatchOpType(taicpu(p),top_ref,top_reg) and
  1873. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1874. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1875. ) and
  1876. GetNextInstruction(p,hp2) and
  1877. MatchInstruction(hp2,A_RET,[S_NO])
  1878. ) or
  1879. ((((taicpu(p).opcode=A_MOV) and
  1880. MatchOpType(taicpu(p),top_reg,top_reg) and
  1881. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1882. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1883. ((taicpu(p).opcode=A_LEA) and
  1884. MatchOpType(taicpu(p),top_ref,top_reg) and
  1885. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1886. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1887. )
  1888. ) and
  1889. GetNextInstruction(p,hp2) and
  1890. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1891. MatchOpType(taicpu(hp2),top_reg) and
  1892. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1893. GetNextInstruction(hp2,hp3) and
  1894. MatchInstruction(hp3,A_RET,[S_NO])
  1895. )
  1896. );
  1897. end;
  1898. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1899. begin
  1900. isFoldableArithOp := False;
  1901. case hp1.opcode of
  1902. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1903. isFoldableArithOp :=
  1904. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1905. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1906. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1907. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1908. (taicpu(hp1).oper[1]^.reg = reg);
  1909. A_INC,A_DEC,A_NEG,A_NOT:
  1910. isFoldableArithOp :=
  1911. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1912. (taicpu(hp1).oper[0]^.reg = reg);
  1913. else
  1914. ;
  1915. end;
  1916. end;
  1917. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1918. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1919. var
  1920. hp2: tai;
  1921. begin
  1922. hp2 := p;
  1923. repeat
  1924. hp2 := tai(hp2.previous);
  1925. if assigned(hp2) and
  1926. (hp2.typ = ait_regalloc) and
  1927. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1928. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1929. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1930. begin
  1931. RemoveInstruction(hp2);
  1932. break;
  1933. end;
  1934. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1935. end;
  1936. begin
  1937. case current_procinfo.procdef.returndef.typ of
  1938. arraydef,recorddef,pointerdef,
  1939. stringdef,enumdef,procdef,objectdef,errordef,
  1940. filedef,setdef,procvardef,
  1941. classrefdef,forwarddef:
  1942. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1943. orddef:
  1944. if current_procinfo.procdef.returndef.size <> 0 then
  1945. begin
  1946. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1947. { for int64/qword }
  1948. if current_procinfo.procdef.returndef.size = 8 then
  1949. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1950. end;
  1951. else
  1952. ;
  1953. end;
  1954. end;
  1955. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1956. var
  1957. hp1,hp2 : tai;
  1958. begin
  1959. result:=false;
  1960. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1961. begin
  1962. { vmova* reg1,reg1
  1963. =>
  1964. <nop> }
  1965. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1966. begin
  1967. RemoveCurrentP(p);
  1968. result:=true;
  1969. exit;
  1970. end
  1971. else if GetNextInstruction(p,hp1) then
  1972. begin
  1973. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1974. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1975. begin
  1976. { vmova* reg1,reg2
  1977. vmova* reg2,reg3
  1978. dealloc reg2
  1979. =>
  1980. vmova* reg1,reg3 }
  1981. TransferUsedRegs(TmpUsedRegs);
  1982. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1983. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1984. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1985. begin
  1986. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1987. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1988. RemoveInstruction(hp1);
  1989. result:=true;
  1990. exit;
  1991. end
  1992. { special case:
  1993. vmova* reg1,<op>
  1994. vmova* <op>,reg1
  1995. =>
  1996. vmova* reg1,<op> }
  1997. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1998. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1999. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2000. ) then
  2001. begin
  2002. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2003. RemoveInstruction(hp1);
  2004. result:=true;
  2005. exit;
  2006. end
  2007. end
  2008. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2009. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2010. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2011. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2012. ) and
  2013. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2014. begin
  2015. { vmova* reg1,reg2
  2016. vmovs* reg2,<op>
  2017. dealloc reg2
  2018. =>
  2019. vmovs* reg1,reg3 }
  2020. TransferUsedRegs(TmpUsedRegs);
  2021. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2022. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2023. begin
  2024. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2025. taicpu(p).opcode:=taicpu(hp1).opcode;
  2026. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2027. RemoveInstruction(hp1);
  2028. result:=true;
  2029. exit;
  2030. end
  2031. end;
  2032. end;
  2033. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2034. begin
  2035. if MatchInstruction(hp1,[A_VFMADDPD,
  2036. A_VFMADD132PD,
  2037. A_VFMADD132PS,
  2038. A_VFMADD132SD,
  2039. A_VFMADD132SS,
  2040. A_VFMADD213PD,
  2041. A_VFMADD213PS,
  2042. A_VFMADD213SD,
  2043. A_VFMADD213SS,
  2044. A_VFMADD231PD,
  2045. A_VFMADD231PS,
  2046. A_VFMADD231SD,
  2047. A_VFMADD231SS,
  2048. A_VFMADDSUB132PD,
  2049. A_VFMADDSUB132PS,
  2050. A_VFMADDSUB213PD,
  2051. A_VFMADDSUB213PS,
  2052. A_VFMADDSUB231PD,
  2053. A_VFMADDSUB231PS,
  2054. A_VFMSUB132PD,
  2055. A_VFMSUB132PS,
  2056. A_VFMSUB132SD,
  2057. A_VFMSUB132SS,
  2058. A_VFMSUB213PD,
  2059. A_VFMSUB213PS,
  2060. A_VFMSUB213SD,
  2061. A_VFMSUB213SS,
  2062. A_VFMSUB231PD,
  2063. A_VFMSUB231PS,
  2064. A_VFMSUB231SD,
  2065. A_VFMSUB231SS,
  2066. A_VFMSUBADD132PD,
  2067. A_VFMSUBADD132PS,
  2068. A_VFMSUBADD213PD,
  2069. A_VFMSUBADD213PS,
  2070. A_VFMSUBADD231PD,
  2071. A_VFMSUBADD231PS,
  2072. A_VFNMADD132PD,
  2073. A_VFNMADD132PS,
  2074. A_VFNMADD132SD,
  2075. A_VFNMADD132SS,
  2076. A_VFNMADD213PD,
  2077. A_VFNMADD213PS,
  2078. A_VFNMADD213SD,
  2079. A_VFNMADD213SS,
  2080. A_VFNMADD231PD,
  2081. A_VFNMADD231PS,
  2082. A_VFNMADD231SD,
  2083. A_VFNMADD231SS,
  2084. A_VFNMSUB132PD,
  2085. A_VFNMSUB132PS,
  2086. A_VFNMSUB132SD,
  2087. A_VFNMSUB132SS,
  2088. A_VFNMSUB213PD,
  2089. A_VFNMSUB213PS,
  2090. A_VFNMSUB213SD,
  2091. A_VFNMSUB213SS,
  2092. A_VFNMSUB231PD,
  2093. A_VFNMSUB231PS,
  2094. A_VFNMSUB231SD,
  2095. A_VFNMSUB231SS],[S_NO]) and
  2096. { we mix single and double opperations here because we assume that the compiler
  2097. generates vmovapd only after double operations and vmovaps only after single operations }
  2098. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2099. GetNextInstruction(hp1,hp2) and
  2100. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2101. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2102. begin
  2103. TransferUsedRegs(TmpUsedRegs);
  2104. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2105. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2106. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2107. begin
  2108. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2109. RemoveCurrentP(p);
  2110. RemoveInstruction(hp2);
  2111. end;
  2112. end
  2113. else if (hp1.typ = ait_instruction) and
  2114. GetNextInstruction(hp1, hp2) and
  2115. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2116. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2117. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2118. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2119. (((taicpu(p).opcode=A_MOVAPS) and
  2120. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2121. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2122. ((taicpu(p).opcode=A_MOVAPD) and
  2123. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2124. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2125. ) then
  2126. { change
  2127. movapX reg,reg2
  2128. addsX/subsX/... reg3, reg2
  2129. movapX reg2,reg
  2130. to
  2131. addsX/subsX/... reg3,reg
  2132. }
  2133. begin
  2134. TransferUsedRegs(TmpUsedRegs);
  2135. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2136. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2137. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2138. begin
  2139. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2140. debug_op2str(taicpu(p).opcode)+' '+
  2141. debug_op2str(taicpu(hp1).opcode)+' '+
  2142. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2143. { we cannot eliminate the first move if
  2144. the operations uses the same register for source and dest }
  2145. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2146. { Remember that hp1 is not necessarily the immediate
  2147. next instruction }
  2148. RemoveCurrentP(p);
  2149. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2150. RemoveInstruction(hp2);
  2151. result:=true;
  2152. end;
  2153. end
  2154. else if (hp1.typ = ait_instruction) and
  2155. (((taicpu(p).opcode=A_VMOVAPD) and
  2156. (taicpu(hp1).opcode=A_VCOMISD)) or
  2157. ((taicpu(p).opcode=A_VMOVAPS) and
  2158. ((taicpu(hp1).opcode=A_VCOMISS))
  2159. )
  2160. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2161. { change
  2162. movapX reg,reg1
  2163. vcomisX reg1,reg1
  2164. to
  2165. vcomisX reg,reg
  2166. }
  2167. begin
  2168. TransferUsedRegs(TmpUsedRegs);
  2169. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2170. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2171. begin
  2172. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2173. debug_op2str(taicpu(p).opcode)+' '+
  2174. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2175. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2176. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2177. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2178. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2179. RemoveCurrentP(p);
  2180. result:=true;
  2181. exit;
  2182. end;
  2183. end
  2184. end;
  2185. end;
  2186. end;
  2187. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2188. var
  2189. hp1 : tai;
  2190. begin
  2191. result:=false;
  2192. { replace
  2193. V<Op>X %mreg1,%mreg2,%mreg3
  2194. VMovX %mreg3,%mreg4
  2195. dealloc %mreg3
  2196. by
  2197. V<Op>X %mreg1,%mreg2,%mreg4
  2198. ?
  2199. }
  2200. if GetNextInstruction(p,hp1) and
  2201. { we mix single and double operations here because we assume that the compiler
  2202. generates vmovapd only after double operations and vmovaps only after single operations }
  2203. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2204. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2205. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2206. begin
  2207. TransferUsedRegs(TmpUsedRegs);
  2208. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2209. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2210. begin
  2211. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2212. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2213. RemoveInstruction(hp1);
  2214. result:=true;
  2215. end;
  2216. end;
  2217. end;
  2218. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2219. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2220. begin
  2221. Result := False;
  2222. { For safety reasons, only check for exact register matches }
  2223. { Check base register }
  2224. if (ref.base = AOldReg) then
  2225. begin
  2226. ref.base := ANewReg;
  2227. Result := True;
  2228. end;
  2229. { Check index register }
  2230. if (ref.index = AOldReg) then
  2231. begin
  2232. ref.index := ANewReg;
  2233. Result := True;
  2234. end;
  2235. end;
  2236. { Replaces all references to AOldReg in an operand to ANewReg }
  2237. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2238. var
  2239. OldSupReg, NewSupReg: TSuperRegister;
  2240. OldSubReg, NewSubReg: TSubRegister;
  2241. OldRegType: TRegisterType;
  2242. ThisOper: POper;
  2243. begin
  2244. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2245. Result := False;
  2246. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2247. InternalError(2020011801);
  2248. OldSupReg := getsupreg(AOldReg);
  2249. OldSubReg := getsubreg(AOldReg);
  2250. OldRegType := getregtype(AOldReg);
  2251. NewSupReg := getsupreg(ANewReg);
  2252. NewSubReg := getsubreg(ANewReg);
  2253. if OldRegType <> getregtype(ANewReg) then
  2254. InternalError(2020011802);
  2255. if OldSubReg <> NewSubReg then
  2256. InternalError(2020011803);
  2257. case ThisOper^.typ of
  2258. top_reg:
  2259. if (
  2260. (ThisOper^.reg = AOldReg) or
  2261. (
  2262. (OldRegType = R_INTREGISTER) and
  2263. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2264. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2265. (
  2266. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2267. {$ifndef x86_64}
  2268. and (
  2269. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2270. don't have an 8-bit representation }
  2271. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2272. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2273. )
  2274. {$endif x86_64}
  2275. )
  2276. )
  2277. ) then
  2278. begin
  2279. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2280. Result := True;
  2281. end;
  2282. top_ref:
  2283. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2284. Result := True;
  2285. else
  2286. ;
  2287. end;
  2288. end;
  2289. { Replaces all references to AOldReg in an instruction to ANewReg }
  2290. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2291. const
  2292. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2293. var
  2294. OperIdx: Integer;
  2295. begin
  2296. Result := False;
  2297. for OperIdx := 0 to p.ops - 1 do
  2298. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2299. begin
  2300. { The shift and rotate instructions can only use CL }
  2301. if not (
  2302. (OperIdx = 0) and
  2303. { This second condition just helps to avoid unnecessarily
  2304. calling MatchInstruction for 10 different opcodes }
  2305. (p.oper[0]^.reg = NR_CL) and
  2306. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2307. ) then
  2308. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2309. end
  2310. else if p.oper[OperIdx]^.typ = top_ref then
  2311. { It's okay to replace registers in references that get written to }
  2312. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2313. end;
  2314. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2315. begin
  2316. Result :=
  2317. (ref^.index = NR_NO) and
  2318. (
  2319. {$ifdef x86_64}
  2320. (
  2321. (ref^.base = NR_RIP) and
  2322. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2323. ) or
  2324. {$endif x86_64}
  2325. (ref^.refaddr = addr_full) or
  2326. (ref^.base = NR_STACK_POINTER_REG) or
  2327. (ref^.base = current_procinfo.framepointer)
  2328. );
  2329. end;
  2330. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2331. var
  2332. l: asizeint;
  2333. begin
  2334. Result := False;
  2335. { Should have been checked previously }
  2336. if p.opcode <> A_LEA then
  2337. InternalError(2020072501);
  2338. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2339. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2340. not(cs_opt_size in current_settings.optimizerswitches) then
  2341. exit;
  2342. with p.oper[0]^.ref^ do
  2343. begin
  2344. if (base <> p.oper[1]^.reg) or
  2345. (index <> NR_NO) or
  2346. assigned(symbol) then
  2347. exit;
  2348. l:=offset;
  2349. if (l=1) and UseIncDec then
  2350. begin
  2351. p.opcode:=A_INC;
  2352. p.loadreg(0,p.oper[1]^.reg);
  2353. p.ops:=1;
  2354. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2355. end
  2356. else if (l=-1) and UseIncDec then
  2357. begin
  2358. p.opcode:=A_DEC;
  2359. p.loadreg(0,p.oper[1]^.reg);
  2360. p.ops:=1;
  2361. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2362. end
  2363. else
  2364. begin
  2365. if (l<0) and (l<>-2147483648) then
  2366. begin
  2367. p.opcode:=A_SUB;
  2368. p.loadConst(0,-l);
  2369. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2370. end
  2371. else
  2372. begin
  2373. p.opcode:=A_ADD;
  2374. p.loadConst(0,l);
  2375. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2376. end;
  2377. end;
  2378. end;
  2379. Result := True;
  2380. end;
  2381. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2382. var
  2383. CurrentReg, ReplaceReg: TRegister;
  2384. begin
  2385. Result := False;
  2386. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2387. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2388. case hp.opcode of
  2389. A_FSTSW, A_FNSTSW,
  2390. A_IN, A_INS, A_OUT, A_OUTS,
  2391. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2392. { These routines have explicit operands, but they are restricted in
  2393. what they can be (e.g. IN and OUT can only read from AL, AX or
  2394. EAX. }
  2395. Exit;
  2396. A_IMUL:
  2397. begin
  2398. { The 1-operand version writes to implicit registers
  2399. The 2-operand version reads from the first operator, and reads
  2400. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2401. the 3-operand version reads from a register that it doesn't write to
  2402. }
  2403. case hp.ops of
  2404. 1:
  2405. if (
  2406. (
  2407. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2408. ) or
  2409. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2410. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2411. begin
  2412. Result := True;
  2413. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2414. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2415. end;
  2416. 2:
  2417. { Only modify the first parameter }
  2418. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2419. begin
  2420. Result := True;
  2421. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2422. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2423. end;
  2424. 3:
  2425. { Only modify the second parameter }
  2426. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2427. begin
  2428. Result := True;
  2429. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2430. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2431. end;
  2432. else
  2433. InternalError(2020012901);
  2434. end;
  2435. end;
  2436. else
  2437. if (hp.ops > 0) and
  2438. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2439. begin
  2440. Result := True;
  2441. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2442. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2443. end;
  2444. end;
  2445. end;
  2446. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2447. var
  2448. hp2: tai;
  2449. p_SourceReg, p_TargetReg: TRegister;
  2450. begin
  2451. Result := False;
  2452. { Backward optimisation. If we have:
  2453. func. %reg1,%reg2
  2454. mov %reg2,%reg3
  2455. (dealloc %reg2)
  2456. Change to:
  2457. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2458. Perform similar optimisations with 1, 3 and 4-operand instructions
  2459. that only have one output.
  2460. }
  2461. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2462. begin
  2463. p_SourceReg := taicpu(p).oper[0]^.reg;
  2464. p_TargetReg := taicpu(p).oper[1]^.reg;
  2465. TransferUsedRegs(TmpUsedRegs);
  2466. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2467. GetLastInstruction(p, hp2) and
  2468. (hp2.typ = ait_instruction) and
  2469. { Have to make sure it's an instruction that only reads from
  2470. the first operands and only writes (not reads or modifies) to
  2471. the last one; in essence, a pure function such as BSR, POPCNT
  2472. or ANDN }
  2473. (
  2474. (
  2475. (taicpu(hp2).ops = 1) and
  2476. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2477. ) or
  2478. (
  2479. (taicpu(hp2).ops = 2) and
  2480. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2481. ) or
  2482. (
  2483. (taicpu(hp2).ops = 3) and
  2484. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2485. ) or
  2486. (
  2487. (taicpu(hp2).ops = 4) and
  2488. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2489. )
  2490. ) and
  2491. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2492. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2493. begin
  2494. case taicpu(hp2).opcode of
  2495. A_FSTSW, A_FNSTSW,
  2496. A_IN, A_INS, A_OUT, A_OUTS,
  2497. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2498. { These routines have explicit operands, but they are restricted in
  2499. what they can be (e.g. IN and OUT can only read from AL, AX or
  2500. EAX. }
  2501. ;
  2502. else
  2503. begin
  2504. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2505. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2506. if not RegInInstruction(p_TargetReg, hp2) then
  2507. begin
  2508. { Since we're allocating from an earlier point, we
  2509. need to remove the register from the tracking }
  2510. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2511. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2512. end;
  2513. RemoveCurrentp(p, hp1);
  2514. { If the Func was another MOV instruction, we might get
  2515. "mov %reg,%reg" that doesn't get removed in Pass 2
  2516. otherwise, so deal with it here (also do something
  2517. similar with lea (%reg),%reg}
  2518. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2519. begin
  2520. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2521. if p = hp2 then
  2522. RemoveCurrentp(p)
  2523. else
  2524. RemoveInstruction(hp2);
  2525. end;
  2526. Result := True;
  2527. Exit;
  2528. end;
  2529. end;
  2530. end;
  2531. end;
  2532. end;
  2533. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2534. var
  2535. hp1, hp2, hp3: tai;
  2536. DoOptimisation, TempBool: Boolean;
  2537. {$ifdef x86_64}
  2538. NewConst: TCGInt;
  2539. {$endif x86_64}
  2540. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2541. begin
  2542. if taicpu(hp1).opcode = signed_movop then
  2543. begin
  2544. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2545. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2546. end
  2547. else
  2548. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2549. end;
  2550. function TryConstMerge(var p1, p2: tai): Boolean;
  2551. var
  2552. ThisRef: TReference;
  2553. begin
  2554. Result := False;
  2555. ThisRef := taicpu(p2).oper[1]^.ref^;
  2556. { Only permit writes to the stack, since we can guarantee alignment with that }
  2557. if (ThisRef.index = NR_NO) and
  2558. (
  2559. (ThisRef.base = NR_STACK_POINTER_REG) or
  2560. (ThisRef.base = current_procinfo.framepointer)
  2561. ) then
  2562. begin
  2563. case taicpu(p).opsize of
  2564. S_B:
  2565. begin
  2566. { Word writes must be on a 2-byte boundary }
  2567. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2568. begin
  2569. { Reduce offset of second reference to see if it is sequential with the first }
  2570. Dec(ThisRef.offset, 1);
  2571. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2572. begin
  2573. { Make sure the constants aren't represented as a
  2574. negative number, as these won't merge properly }
  2575. taicpu(p1).opsize := S_W;
  2576. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2577. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2578. RemoveInstruction(p2);
  2579. Result := True;
  2580. end;
  2581. end;
  2582. end;
  2583. S_W:
  2584. begin
  2585. { Longword writes must be on a 4-byte boundary }
  2586. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2587. begin
  2588. { Reduce offset of second reference to see if it is sequential with the first }
  2589. Dec(ThisRef.offset, 2);
  2590. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2591. begin
  2592. { Make sure the constants aren't represented as a
  2593. negative number, as these won't merge properly }
  2594. taicpu(p1).opsize := S_L;
  2595. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2596. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2597. RemoveInstruction(p2);
  2598. Result := True;
  2599. end;
  2600. end;
  2601. end;
  2602. {$ifdef x86_64}
  2603. S_L:
  2604. begin
  2605. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2606. see if the constants can be encoded this way. }
  2607. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2608. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2609. { Quadword writes must be on an 8-byte boundary }
  2610. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2611. begin
  2612. { Reduce offset of second reference to see if it is sequential with the first }
  2613. Dec(ThisRef.offset, 4);
  2614. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2615. begin
  2616. { Make sure the constants aren't represented as a
  2617. negative number, as these won't merge properly }
  2618. taicpu(p1).opsize := S_Q;
  2619. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2620. taicpu(p1).oper[0]^.val := NewConst;
  2621. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2622. RemoveInstruction(p2);
  2623. Result := True;
  2624. end;
  2625. end;
  2626. end;
  2627. {$endif x86_64}
  2628. else
  2629. ;
  2630. end;
  2631. end;
  2632. end;
  2633. var
  2634. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2635. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2636. NewSize: topsize; NewOffset: asizeint;
  2637. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2638. SourceRef, TargetRef: TReference;
  2639. MovAligned, MovUnaligned: TAsmOp;
  2640. ThisRef: TReference;
  2641. JumpTracking: TLinkedList;
  2642. begin
  2643. Result:=false;
  2644. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2645. { remove mov reg1,reg1? }
  2646. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2647. then
  2648. begin
  2649. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2650. { take care of the register (de)allocs following p }
  2651. RemoveCurrentP(p, hp1);
  2652. Result:=true;
  2653. exit;
  2654. end;
  2655. { All the next optimisations require a next instruction }
  2656. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2657. Exit;
  2658. { Prevent compiler warnings }
  2659. p_TargetReg := NR_NO;
  2660. if taicpu(p).oper[1]^.typ = top_reg then
  2661. begin
  2662. { Saves on a large number of dereferences }
  2663. p_TargetReg := taicpu(p).oper[1]^.reg;
  2664. { Look for:
  2665. mov %reg1,%reg2
  2666. ??? %reg2,r/m
  2667. Change to:
  2668. mov %reg1,%reg2
  2669. ??? %reg1,r/m
  2670. }
  2671. if taicpu(p).oper[0]^.typ = top_reg then
  2672. begin
  2673. if RegReadByInstruction(p_TargetReg, hp1) and
  2674. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2675. begin
  2676. { A change has occurred, just not in p }
  2677. Result := True;
  2678. TransferUsedRegs(TmpUsedRegs);
  2679. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2680. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2681. { Just in case something didn't get modified (e.g. an
  2682. implicit register) }
  2683. not RegReadByInstruction(p_TargetReg, hp1) then
  2684. begin
  2685. { We can remove the original MOV }
  2686. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2687. RemoveCurrentp(p, hp1);
  2688. { UsedRegs got updated by RemoveCurrentp }
  2689. Result := True;
  2690. Exit;
  2691. end;
  2692. { If we know a MOV instruction has become a null operation, we might as well
  2693. get rid of it now to save time. }
  2694. if (taicpu(hp1).opcode = A_MOV) and
  2695. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2696. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2697. { Just being a register is enough to confirm it's a null operation }
  2698. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2699. begin
  2700. Result := True;
  2701. { Speed-up to reduce a pipeline stall... if we had something like...
  2702. movl %eax,%edx
  2703. movw %dx,%ax
  2704. ... the second instruction would change to movw %ax,%ax, but
  2705. given that it is now %ax that's active rather than %eax,
  2706. penalties might occur due to a partial register write, so instead,
  2707. change it to a MOVZX instruction when optimising for speed.
  2708. }
  2709. if not (cs_opt_size in current_settings.optimizerswitches) and
  2710. IsMOVZXAcceptable and
  2711. (taicpu(hp1).opsize < taicpu(p).opsize)
  2712. {$ifdef x86_64}
  2713. { operations already implicitly set the upper 64 bits to zero }
  2714. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2715. {$endif x86_64}
  2716. then
  2717. begin
  2718. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2719. case taicpu(p).opsize of
  2720. S_W:
  2721. if taicpu(hp1).opsize = S_B then
  2722. taicpu(hp1).opsize := S_BL
  2723. else
  2724. InternalError(2020012911);
  2725. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2726. case taicpu(hp1).opsize of
  2727. S_B:
  2728. taicpu(hp1).opsize := S_BL;
  2729. S_W:
  2730. taicpu(hp1).opsize := S_WL;
  2731. else
  2732. InternalError(2020012912);
  2733. end;
  2734. else
  2735. InternalError(2020012910);
  2736. end;
  2737. taicpu(hp1).opcode := A_MOVZX;
  2738. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2739. end
  2740. else
  2741. begin
  2742. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2743. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2744. RemoveInstruction(hp1);
  2745. { The instruction after what was hp1 is now the immediate next instruction,
  2746. so we can continue to make optimisations if it's present }
  2747. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2748. Exit;
  2749. hp1 := hp2;
  2750. end;
  2751. end;
  2752. end;
  2753. end;
  2754. end;
  2755. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2756. overwrites the original destination register. e.g.
  2757. movl ###,%reg2d
  2758. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2759. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2760. }
  2761. if (taicpu(p).oper[1]^.typ = top_reg) and
  2762. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2763. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2764. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2765. begin
  2766. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2767. begin
  2768. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2769. case taicpu(p).oper[0]^.typ of
  2770. top_const:
  2771. { We have something like:
  2772. movb $x, %regb
  2773. movzbl %regb,%regd
  2774. Change to:
  2775. movl $x, %regd
  2776. }
  2777. begin
  2778. case taicpu(hp1).opsize of
  2779. S_BW:
  2780. begin
  2781. convert_mov_value(A_MOVSX, $FF);
  2782. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2783. taicpu(p).opsize := S_W;
  2784. end;
  2785. S_BL:
  2786. begin
  2787. convert_mov_value(A_MOVSX, $FF);
  2788. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2789. taicpu(p).opsize := S_L;
  2790. end;
  2791. S_WL:
  2792. begin
  2793. convert_mov_value(A_MOVSX, $FFFF);
  2794. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2795. taicpu(p).opsize := S_L;
  2796. end;
  2797. {$ifdef x86_64}
  2798. S_BQ:
  2799. begin
  2800. convert_mov_value(A_MOVSX, $FF);
  2801. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2802. taicpu(p).opsize := S_Q;
  2803. end;
  2804. S_WQ:
  2805. begin
  2806. convert_mov_value(A_MOVSX, $FFFF);
  2807. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2808. taicpu(p).opsize := S_Q;
  2809. end;
  2810. S_LQ:
  2811. begin
  2812. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2813. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2814. taicpu(p).opsize := S_Q;
  2815. end;
  2816. {$endif x86_64}
  2817. else
  2818. { If hp1 was a MOV instruction, it should have been
  2819. optimised already }
  2820. InternalError(2020021001);
  2821. end;
  2822. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2823. RemoveInstruction(hp1);
  2824. Result := True;
  2825. Exit;
  2826. end;
  2827. top_ref:
  2828. begin
  2829. { We have something like:
  2830. movb mem, %regb
  2831. movzbl %regb,%regd
  2832. Change to:
  2833. movzbl mem, %regd
  2834. }
  2835. ThisRef := taicpu(p).oper[0]^.ref^;
  2836. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2837. begin
  2838. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2839. taicpu(hp1).loadref(0, ThisRef);
  2840. { Make sure any registers in the references are properly tracked }
  2841. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2842. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2843. if (ThisRef.index <> NR_NO) then
  2844. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2845. RemoveCurrentP(p, hp1);
  2846. Result := True;
  2847. Exit;
  2848. end;
  2849. end;
  2850. else
  2851. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2852. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2853. Exit;
  2854. end;
  2855. end
  2856. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2857. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2858. optimised }
  2859. else
  2860. begin
  2861. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2862. RemoveCurrentP(p, hp1);
  2863. Result := True;
  2864. Exit;
  2865. end;
  2866. end;
  2867. if (taicpu(hp1).opcode = A_AND) and
  2868. (taicpu(p).oper[1]^.typ = top_reg) and
  2869. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2870. begin
  2871. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2872. begin
  2873. case taicpu(p).opsize of
  2874. S_L:
  2875. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2876. begin
  2877. { Optimize out:
  2878. mov x, %reg
  2879. and ffffffffh, %reg
  2880. }
  2881. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2882. RemoveInstruction(hp1);
  2883. Result:=true;
  2884. exit;
  2885. end;
  2886. S_Q: { TODO: Confirm if this is even possible }
  2887. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2888. begin
  2889. { Optimize out:
  2890. mov x, %reg
  2891. and ffffffffffffffffh, %reg
  2892. }
  2893. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2894. RemoveInstruction(hp1);
  2895. Result:=true;
  2896. exit;
  2897. end;
  2898. else
  2899. ;
  2900. end;
  2901. if (
  2902. (taicpu(p).oper[0]^.typ=top_reg) or
  2903. (
  2904. (taicpu(p).oper[0]^.typ=top_ref) and
  2905. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2906. )
  2907. ) and
  2908. GetNextInstruction(hp1,hp2) and
  2909. MatchInstruction(hp2,A_TEST,[]) and
  2910. (
  2911. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2912. (
  2913. { If the register being tested is smaller than the one
  2914. that received a bitwise AND, permit it if the constant
  2915. fits into the smaller size }
  2916. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2917. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2918. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2919. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2920. (
  2921. (
  2922. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2923. (taicpu(hp1).oper[0]^.val <= $FF)
  2924. ) or
  2925. (
  2926. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2927. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2928. {$ifdef x86_64}
  2929. ) or
  2930. (
  2931. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2932. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2933. {$endif x86_64}
  2934. )
  2935. )
  2936. )
  2937. ) and
  2938. (
  2939. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2940. MatchOperand(taicpu(hp2).oper[0]^,-1)
  2941. ) and
  2942. GetNextInstruction(hp2,hp3) and
  2943. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2944. (taicpu(hp3).condition in [C_E,C_NE]) then
  2945. begin
  2946. TransferUsedRegs(TmpUsedRegs);
  2947. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2948. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2949. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2950. begin
  2951. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2952. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2953. taicpu(hp1).opcode:=A_TEST;
  2954. { Shrink the TEST instruction down to the smallest possible size }
  2955. case taicpu(hp1).oper[0]^.val of
  2956. 0..255:
  2957. if (taicpu(hp1).opsize <> S_B)
  2958. {$ifndef x86_64}
  2959. and (
  2960. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  2961. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  2962. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  2963. )
  2964. {$endif x86_64}
  2965. then
  2966. begin
  2967. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2968. { Only print debug message if the TEST instruction
  2969. is a different size before and after }
  2970. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  2971. taicpu(hp1).opsize := S_B;
  2972. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2973. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  2974. end;
  2975. 256..65535:
  2976. if (taicpu(hp1).opsize <> S_W) then
  2977. begin
  2978. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2979. { Only print debug message if the TEST instruction
  2980. is a different size before and after }
  2981. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  2982. taicpu(hp1).opsize := S_W;
  2983. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2984. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  2985. end;
  2986. {$ifdef x86_64}
  2987. 65536..$7FFFFFFF:
  2988. if (taicpu(hp1).opsize <> S_L) then
  2989. begin
  2990. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2991. { Only print debug message if the TEST instruction
  2992. is a different size before and after }
  2993. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  2994. taicpu(hp1).opsize := S_L;
  2995. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2996. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2997. end;
  2998. {$endif x86_64}
  2999. else
  3000. ;
  3001. end;
  3002. RemoveInstruction(hp2);
  3003. RemoveCurrentP(p, hp1);
  3004. Result:=true;
  3005. exit;
  3006. end;
  3007. end;
  3008. end
  3009. else if IsMOVZXAcceptable and
  3010. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3011. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3012. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3013. then
  3014. begin
  3015. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3016. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3017. case taicpu(p).opsize of
  3018. S_B:
  3019. if (taicpu(hp1).oper[0]^.val = $ff) then
  3020. begin
  3021. { Convert:
  3022. movb x, %regl movb x, %regl
  3023. andw ffh, %regw andl ffh, %regd
  3024. To:
  3025. movzbw x, %regd movzbl x, %regd
  3026. (Identical registers, just different sizes)
  3027. }
  3028. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3029. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3030. case taicpu(hp1).opsize of
  3031. S_W: NewSize := S_BW;
  3032. S_L: NewSize := S_BL;
  3033. {$ifdef x86_64}
  3034. S_Q: NewSize := S_BQ;
  3035. {$endif x86_64}
  3036. else
  3037. InternalError(2018011510);
  3038. end;
  3039. end
  3040. else
  3041. NewSize := S_NO;
  3042. S_W:
  3043. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3044. begin
  3045. { Convert:
  3046. movw x, %regw
  3047. andl ffffh, %regd
  3048. To:
  3049. movzwl x, %regd
  3050. (Identical registers, just different sizes)
  3051. }
  3052. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3053. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3054. case taicpu(hp1).opsize of
  3055. S_L: NewSize := S_WL;
  3056. {$ifdef x86_64}
  3057. S_Q: NewSize := S_WQ;
  3058. {$endif x86_64}
  3059. else
  3060. InternalError(2018011511);
  3061. end;
  3062. end
  3063. else
  3064. NewSize := S_NO;
  3065. else
  3066. NewSize := S_NO;
  3067. end;
  3068. if NewSize <> S_NO then
  3069. begin
  3070. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3071. { The actual optimization }
  3072. taicpu(p).opcode := A_MOVZX;
  3073. taicpu(p).changeopsize(NewSize);
  3074. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3075. { Safeguard if "and" is followed by a conditional command }
  3076. TransferUsedRegs(TmpUsedRegs);
  3077. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3078. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3079. begin
  3080. { At this point, the "and" command is effectively equivalent to
  3081. "test %reg,%reg". This will be handled separately by the
  3082. Peephole Optimizer. [Kit] }
  3083. DebugMsg(SPeepholeOptimization + PreMessage +
  3084. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3085. end
  3086. else
  3087. begin
  3088. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3089. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3090. RemoveInstruction(hp1);
  3091. end;
  3092. Result := True;
  3093. Exit;
  3094. end;
  3095. end;
  3096. end;
  3097. if (taicpu(hp1).opcode = A_OR) and
  3098. (taicpu(p).oper[1]^.typ = top_reg) and
  3099. MatchOperand(taicpu(p).oper[0]^, 0) and
  3100. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3101. begin
  3102. { mov 0, %reg
  3103. or ###,%reg
  3104. Change to (only if the flags are not used):
  3105. mov ###,%reg
  3106. }
  3107. TransferUsedRegs(TmpUsedRegs);
  3108. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3109. DoOptimisation := True;
  3110. { Even if the flags are used, we might be able to do the optimisation
  3111. if the conditions are predictable }
  3112. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3113. begin
  3114. { Only perform if ### = %reg (the same register) or equal to 0,
  3115. so %reg is guaranteed to still have a value of zero }
  3116. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3117. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3118. begin
  3119. hp2 := hp1;
  3120. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3121. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3122. GetNextInstruction(hp2, hp3) do
  3123. begin
  3124. { Don't continue modifying if the flags state is getting changed }
  3125. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3126. Break;
  3127. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3128. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3129. begin
  3130. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3131. begin
  3132. { Condition is always true }
  3133. case taicpu(hp3).opcode of
  3134. A_Jcc:
  3135. begin
  3136. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3137. { Check for jump shortcuts before we destroy the condition }
  3138. DoJumpOptimizations(hp3, TempBool);
  3139. MakeUnconditional(taicpu(hp3));
  3140. Result := True;
  3141. end;
  3142. A_CMOVcc:
  3143. begin
  3144. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3145. taicpu(hp3).opcode := A_MOV;
  3146. taicpu(hp3).condition := C_None;
  3147. Result := True;
  3148. end;
  3149. A_SETcc:
  3150. begin
  3151. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3152. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3153. taicpu(hp3).opcode := A_MOV;
  3154. taicpu(hp3).ops := 2;
  3155. taicpu(hp3).condition := C_None;
  3156. taicpu(hp3).opsize := S_B;
  3157. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3158. taicpu(hp3).loadconst(0, 1);
  3159. Result := True;
  3160. end;
  3161. else
  3162. InternalError(2021090701);
  3163. end;
  3164. end
  3165. 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
  3166. begin
  3167. { Condition is always false }
  3168. case taicpu(hp3).opcode of
  3169. A_Jcc:
  3170. begin
  3171. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3172. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3173. RemoveInstruction(hp3);
  3174. Result := True;
  3175. { Since hp3 was deleted, hp2 must not be updated }
  3176. Continue;
  3177. end;
  3178. A_CMOVcc:
  3179. begin
  3180. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3181. RemoveInstruction(hp3);
  3182. Result := True;
  3183. { Since hp3 was deleted, hp2 must not be updated }
  3184. Continue;
  3185. end;
  3186. A_SETcc:
  3187. begin
  3188. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3189. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3190. taicpu(hp3).opcode := A_MOV;
  3191. taicpu(hp3).ops := 2;
  3192. taicpu(hp3).condition := C_None;
  3193. taicpu(hp3).opsize := S_B;
  3194. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3195. taicpu(hp3).loadconst(0, 0);
  3196. Result := True;
  3197. end;
  3198. else
  3199. InternalError(2021090702);
  3200. end;
  3201. end
  3202. else
  3203. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3204. DoOptimisation := False;
  3205. end;
  3206. hp2 := hp3;
  3207. end;
  3208. { Flags are still in use - don't optimise }
  3209. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3210. DoOptimisation := False;
  3211. end
  3212. else
  3213. DoOptimisation := False;
  3214. end;
  3215. if DoOptimisation then
  3216. begin
  3217. {$ifdef x86_64}
  3218. { OR only supports 32-bit sign-extended constants for 64-bit
  3219. instructions, so compensate for this if the constant is
  3220. encoded as a value greater than or equal to 2^31 }
  3221. if (taicpu(hp1).opsize = S_Q) and
  3222. (taicpu(hp1).oper[0]^.typ = top_const) and
  3223. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3224. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3225. {$endif x86_64}
  3226. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3227. taicpu(hp1).opcode := A_MOV;
  3228. RemoveCurrentP(p, hp1);
  3229. Result := True;
  3230. Exit;
  3231. end;
  3232. end;
  3233. { Next instruction is also a MOV ? }
  3234. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3235. begin
  3236. if MatchOpType(taicpu(p), top_const, top_ref) and
  3237. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3238. TryConstMerge(p, hp1) then
  3239. begin
  3240. Result := True;
  3241. { In case we have four byte writes in a row, check for 2 more
  3242. right now so we don't have to wait for another iteration of
  3243. pass 1
  3244. }
  3245. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3246. case taicpu(p).opsize of
  3247. S_W:
  3248. begin
  3249. if GetNextInstruction(p, hp1) and
  3250. MatchInstruction(hp1, A_MOV, [S_B]) and
  3251. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3252. GetNextInstruction(hp1, hp2) and
  3253. MatchInstruction(hp2, A_MOV, [S_B]) and
  3254. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3255. { Try to merge the two bytes }
  3256. TryConstMerge(hp1, hp2) then
  3257. { Now try to merge the two words (hp2 will get deleted) }
  3258. TryConstMerge(p, hp1);
  3259. end;
  3260. S_L:
  3261. begin
  3262. { Though this only really benefits x86_64 and not i386, it
  3263. gets a potential optimisation done faster and hence
  3264. reduces the number of times OptPass1MOV is entered }
  3265. if GetNextInstruction(p, hp1) and
  3266. MatchInstruction(hp1, A_MOV, [S_W]) and
  3267. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3268. GetNextInstruction(hp1, hp2) and
  3269. MatchInstruction(hp2, A_MOV, [S_W]) and
  3270. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3271. { Try to merge the two words }
  3272. TryConstMerge(hp1, hp2) then
  3273. { This will always fail on i386, so don't bother
  3274. calling it unless we're doing x86_64 }
  3275. {$ifdef x86_64}
  3276. { Now try to merge the two longwords (hp2 will get deleted) }
  3277. TryConstMerge(p, hp1)
  3278. {$endif x86_64}
  3279. ;
  3280. end;
  3281. else
  3282. ;
  3283. end;
  3284. Exit;
  3285. end;
  3286. if (taicpu(p).oper[1]^.typ = top_reg) and
  3287. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3288. begin
  3289. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3290. TransferUsedRegs(TmpUsedRegs);
  3291. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3292. { we have
  3293. mov x, %treg
  3294. mov %treg, y
  3295. }
  3296. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3297. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3298. { we've got
  3299. mov x, %treg
  3300. mov %treg, y
  3301. with %treg is not used after }
  3302. case taicpu(p).oper[0]^.typ Of
  3303. { top_reg is covered by DeepMOVOpt }
  3304. top_const:
  3305. begin
  3306. { change
  3307. mov const, %treg
  3308. mov %treg, y
  3309. to
  3310. mov const, y
  3311. }
  3312. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3313. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3314. begin
  3315. if taicpu(hp1).oper[1]^.typ=top_reg then
  3316. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3317. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3318. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3319. RemoveInstruction(hp1);
  3320. Result:=true;
  3321. Exit;
  3322. end;
  3323. end;
  3324. top_ref:
  3325. case taicpu(hp1).oper[1]^.typ of
  3326. top_reg:
  3327. begin
  3328. { change
  3329. mov mem, %treg
  3330. mov %treg, %reg
  3331. to
  3332. mov mem, %reg"
  3333. }
  3334. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3335. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3336. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3337. RemoveInstruction(hp1);
  3338. Result:=true;
  3339. Exit;
  3340. end;
  3341. top_ref:
  3342. begin
  3343. {$ifdef x86_64}
  3344. { Look for the following to simplify:
  3345. mov x(mem1), %reg
  3346. mov %reg, y(mem2)
  3347. mov x+8(mem1), %reg
  3348. mov %reg, y+8(mem2)
  3349. Change to:
  3350. movdqu x(mem1), %xmmreg
  3351. movdqu %xmmreg, y(mem2)
  3352. ...but only as long as the memory blocks don't overlap
  3353. }
  3354. SourceRef := taicpu(p).oper[0]^.ref^;
  3355. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3356. if (taicpu(p).opsize = S_Q) and
  3357. GetNextInstruction(hp1, hp2) and
  3358. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3359. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3360. begin
  3361. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3362. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3363. Inc(SourceRef.offset, 8);
  3364. if UseAVX then
  3365. begin
  3366. MovAligned := A_VMOVDQA;
  3367. MovUnaligned := A_VMOVDQU;
  3368. end
  3369. else
  3370. begin
  3371. MovAligned := A_MOVDQA;
  3372. MovUnaligned := A_MOVDQU;
  3373. end;
  3374. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3375. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3376. begin
  3377. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3378. Inc(TargetRef.offset, 8);
  3379. if GetNextInstruction(hp2, hp3) and
  3380. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3381. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3382. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3383. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3384. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3385. begin
  3386. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3387. if NewMMReg <> NR_NO then
  3388. begin
  3389. { Remember that the offsets are 8 ahead }
  3390. if ((SourceRef.offset mod 16) = 8) and
  3391. (
  3392. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3393. (SourceRef.base = current_procinfo.framepointer) or
  3394. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3395. ) then
  3396. taicpu(p).opcode := MovAligned
  3397. else
  3398. taicpu(p).opcode := MovUnaligned;
  3399. taicpu(p).opsize := S_XMM;
  3400. taicpu(p).oper[1]^.reg := NewMMReg;
  3401. if ((TargetRef.offset mod 16) = 8) and
  3402. (
  3403. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3404. (TargetRef.base = current_procinfo.framepointer) or
  3405. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3406. ) then
  3407. taicpu(hp1).opcode := MovAligned
  3408. else
  3409. taicpu(hp1).opcode := MovUnaligned;
  3410. taicpu(hp1).opsize := S_XMM;
  3411. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3412. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3413. RemoveInstruction(hp2);
  3414. RemoveInstruction(hp3);
  3415. Result := True;
  3416. Exit;
  3417. end;
  3418. end;
  3419. end
  3420. else
  3421. begin
  3422. { See if the next references are 8 less rather than 8 greater }
  3423. Dec(SourceRef.offset, 16); { -8 the other way }
  3424. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3425. begin
  3426. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3427. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3428. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3429. GetNextInstruction(hp2, hp3) and
  3430. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3431. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3432. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3433. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3434. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3435. begin
  3436. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3437. if NewMMReg <> NR_NO then
  3438. begin
  3439. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3440. if ((SourceRef.offset mod 16) = 0) and
  3441. (
  3442. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3443. (SourceRef.base = current_procinfo.framepointer) or
  3444. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3445. ) then
  3446. taicpu(hp2).opcode := MovAligned
  3447. else
  3448. taicpu(hp2).opcode := MovUnaligned;
  3449. taicpu(hp2).opsize := S_XMM;
  3450. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3451. if ((TargetRef.offset mod 16) = 0) and
  3452. (
  3453. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3454. (TargetRef.base = current_procinfo.framepointer) or
  3455. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3456. ) then
  3457. taicpu(hp3).opcode := MovAligned
  3458. else
  3459. taicpu(hp3).opcode := MovUnaligned;
  3460. taicpu(hp3).opsize := S_XMM;
  3461. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3462. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3463. RemoveInstruction(hp1);
  3464. RemoveCurrentP(p, hp2);
  3465. Result := True;
  3466. Exit;
  3467. end;
  3468. end;
  3469. end;
  3470. end;
  3471. end;
  3472. {$endif x86_64}
  3473. end;
  3474. else
  3475. { The write target should be a reg or a ref }
  3476. InternalError(2021091601);
  3477. end;
  3478. else
  3479. ;
  3480. end
  3481. else
  3482. { %treg is used afterwards, but all eventualities
  3483. other than the first MOV instruction being a constant
  3484. are covered by DeepMOVOpt, so only check for that }
  3485. if (taicpu(p).oper[0]^.typ = top_const) and
  3486. (
  3487. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3488. not (cs_opt_size in current_settings.optimizerswitches) or
  3489. (taicpu(hp1).opsize = S_B)
  3490. ) and
  3491. (
  3492. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3493. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3494. ) then
  3495. begin
  3496. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3497. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3498. end;
  3499. end;
  3500. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3501. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3502. { mov reg1, mem1 or mov mem1, reg1
  3503. mov mem2, reg2 mov reg2, mem2}
  3504. begin
  3505. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3506. { mov reg1, mem1 or mov mem1, reg1
  3507. mov mem2, reg1 mov reg2, mem1}
  3508. begin
  3509. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3510. { Removes the second statement from
  3511. mov reg1, mem1/reg2
  3512. mov mem1/reg2, reg1 }
  3513. begin
  3514. if taicpu(p).oper[0]^.typ=top_reg then
  3515. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3516. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3517. RemoveInstruction(hp1);
  3518. Result:=true;
  3519. exit;
  3520. end
  3521. else
  3522. begin
  3523. TransferUsedRegs(TmpUsedRegs);
  3524. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3525. if (taicpu(p).oper[1]^.typ = top_ref) and
  3526. { mov reg1, mem1
  3527. mov mem2, reg1 }
  3528. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3529. GetNextInstruction(hp1, hp2) and
  3530. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3531. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3532. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3533. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3534. { change to
  3535. mov reg1, mem1 mov reg1, mem1
  3536. mov mem2, reg1 cmp reg1, mem2
  3537. cmp mem1, reg1
  3538. }
  3539. begin
  3540. RemoveInstruction(hp2);
  3541. taicpu(hp1).opcode := A_CMP;
  3542. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3543. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3544. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3545. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3546. end;
  3547. end;
  3548. end
  3549. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3550. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3551. begin
  3552. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3553. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3554. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3555. end
  3556. else
  3557. begin
  3558. TransferUsedRegs(TmpUsedRegs);
  3559. if GetNextInstruction(hp1, hp2) and
  3560. MatchOpType(taicpu(p),top_ref,top_reg) and
  3561. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3562. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3563. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3564. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3565. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3566. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3567. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3568. { mov mem1, %reg1
  3569. mov %reg1, mem2
  3570. mov mem2, reg2
  3571. to:
  3572. mov mem1, reg2
  3573. mov reg2, mem2}
  3574. begin
  3575. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3576. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3577. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3578. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3579. RemoveInstruction(hp2);
  3580. Result := True;
  3581. end
  3582. {$ifdef i386}
  3583. { this is enabled for i386 only, as the rules to create the reg sets below
  3584. are too complicated for x86-64, so this makes this code too error prone
  3585. on x86-64
  3586. }
  3587. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3588. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3589. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3590. { mov mem1, reg1 mov mem1, reg1
  3591. mov reg1, mem2 mov reg1, mem2
  3592. mov mem2, reg2 mov mem2, reg1
  3593. to: to:
  3594. mov mem1, reg1 mov mem1, reg1
  3595. mov mem1, reg2 mov reg1, mem2
  3596. mov reg1, mem2
  3597. or (if mem1 depends on reg1
  3598. and/or if mem2 depends on reg2)
  3599. to:
  3600. mov mem1, reg1
  3601. mov reg1, mem2
  3602. mov reg1, reg2
  3603. }
  3604. begin
  3605. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3606. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3607. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3608. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3609. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3610. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3611. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3612. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3613. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3614. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3615. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3616. end
  3617. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3618. begin
  3619. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3620. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3621. end
  3622. else
  3623. begin
  3624. RemoveInstruction(hp2);
  3625. end
  3626. {$endif i386}
  3627. ;
  3628. end;
  3629. end
  3630. { movl [mem1],reg1
  3631. movl [mem1],reg2
  3632. to
  3633. movl [mem1],reg1
  3634. movl reg1,reg2
  3635. }
  3636. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3637. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3638. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3639. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3640. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3641. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3642. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3643. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3644. begin
  3645. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3646. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3647. end;
  3648. { movl const1,[mem1]
  3649. movl [mem1],reg1
  3650. to
  3651. movl const1,reg1
  3652. movl reg1,[mem1]
  3653. }
  3654. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3655. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3656. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3657. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3658. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3659. begin
  3660. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3661. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3662. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3663. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3664. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3665. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3666. Result:=true;
  3667. exit;
  3668. end;
  3669. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3670. { Change:
  3671. movl %reg1,%reg2
  3672. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3673. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3674. To:
  3675. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3676. movl x(%reg1),%reg1
  3677. movl %reg1,%regX
  3678. }
  3679. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3680. begin
  3681. p_SourceReg := taicpu(p).oper[0]^.reg;
  3682. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3683. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3684. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3685. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3686. GetNextInstruction(hp1, hp2) and
  3687. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3688. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3689. begin
  3690. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3691. if RegInRef(p_TargetReg, SourceRef) and
  3692. { If %reg1 also appears in the second reference, then it will
  3693. not refer to the same memory block as the first reference }
  3694. not RegInRef(p_SourceReg, SourceRef) then
  3695. begin
  3696. { Check to see if the references match if %reg2 is changed to %reg1 }
  3697. if SourceRef.base = p_TargetReg then
  3698. SourceRef.base := p_SourceReg;
  3699. if SourceRef.index = p_TargetReg then
  3700. SourceRef.index := p_SourceReg;
  3701. { RefsEqual also checks to ensure both references are non-volatile }
  3702. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3703. begin
  3704. taicpu(hp2).loadreg(0, p_SourceReg);
  3705. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3706. Result := True;
  3707. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3708. begin
  3709. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3710. RemoveCurrentP(p, hp1);
  3711. Exit;
  3712. end
  3713. else
  3714. begin
  3715. { Check to see if %reg2 is no longer in use }
  3716. TransferUsedRegs(TmpUsedRegs);
  3717. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3718. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3719. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3720. begin
  3721. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3722. RemoveCurrentP(p, hp1);
  3723. Exit;
  3724. end;
  3725. end;
  3726. { If we reach this point, p and hp1 weren't actually modified,
  3727. so we can do a bit more work on this pass }
  3728. end;
  3729. end;
  3730. end;
  3731. end;
  3732. end;
  3733. { search further than the next instruction for a mov (as long as it's not a jump) }
  3734. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3735. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3736. (taicpu(p).oper[1]^.typ = top_reg) and
  3737. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3738. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3739. begin
  3740. { we work with hp2 here, so hp1 can be still used later on when
  3741. checking for GetNextInstruction_p }
  3742. hp3 := hp1;
  3743. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3744. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3745. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3746. TransferUsedRegs(TmpUsedRegs);
  3747. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3748. if NotFirstIteration then
  3749. JumpTracking := TLinkedList.Create
  3750. else
  3751. JumpTracking := nil;
  3752. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3753. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3754. (hp2.typ=ait_instruction) do
  3755. begin
  3756. case taicpu(hp2).opcode of
  3757. A_POP:
  3758. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3759. begin
  3760. if not CrossJump and
  3761. not RegUsedBetween(p_TargetReg, p, hp2) then
  3762. begin
  3763. { We can remove the original MOV since the register
  3764. wasn't used between it and its popping from the stack }
  3765. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3766. RemoveCurrentp(p, hp1);
  3767. Result := True;
  3768. JumpTracking.Free;
  3769. Exit;
  3770. end;
  3771. { Can't go any further }
  3772. Break;
  3773. end;
  3774. A_MOV:
  3775. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3776. ((taicpu(p).oper[0]^.typ=top_const) or
  3777. ((taicpu(p).oper[0]^.typ=top_reg) and
  3778. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3779. )
  3780. ) then
  3781. begin
  3782. { we have
  3783. mov x, %treg
  3784. mov %treg, y
  3785. }
  3786. { We don't need to call UpdateUsedRegs for every instruction between
  3787. p and hp2 because the register we're concerned about will not
  3788. become deallocated (otherwise GetNextInstructionUsingReg would
  3789. have stopped at an earlier instruction). [Kit] }
  3790. TempRegUsed :=
  3791. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3792. RegReadByInstruction(p_TargetReg, hp3) or
  3793. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3794. case taicpu(p).oper[0]^.typ Of
  3795. top_reg:
  3796. begin
  3797. { change
  3798. mov %reg, %treg
  3799. mov %treg, y
  3800. to
  3801. mov %reg, y
  3802. }
  3803. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3804. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3805. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3806. begin
  3807. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3808. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3809. if TempRegUsed then
  3810. begin
  3811. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3812. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3813. { Set the start of the next GetNextInstructionUsingRegCond search
  3814. to start at the entry right before hp2 (which is about to be removed) }
  3815. hp3 := tai(hp2.Previous);
  3816. RemoveInstruction(hp2);
  3817. { See if there's more we can optimise }
  3818. Continue;
  3819. end
  3820. else
  3821. begin
  3822. RemoveInstruction(hp2);
  3823. { We can remove the original MOV too }
  3824. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3825. RemoveCurrentP(p, hp1);
  3826. Result:=true;
  3827. JumpTracking.Free;
  3828. Exit;
  3829. end;
  3830. end
  3831. else
  3832. begin
  3833. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3834. taicpu(hp2).loadReg(0, p_SourceReg);
  3835. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3836. { Check to see if the register also appears in the reference }
  3837. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3838. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3839. { Don't remove the first instruction if the temporary register is in use }
  3840. if not TempRegUsed and
  3841. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3842. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3843. begin
  3844. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3845. RemoveCurrentP(p, hp1);
  3846. Result:=true;
  3847. JumpTracking.Free;
  3848. Exit;
  3849. end;
  3850. { No need to set Result to True here. If there's another instruction later
  3851. on that can be optimised, it will be detected when the main Pass 1 loop
  3852. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3853. end;
  3854. end;
  3855. top_const:
  3856. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3857. begin
  3858. { change
  3859. mov const, %treg
  3860. mov %treg, y
  3861. to
  3862. mov const, y
  3863. }
  3864. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3865. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3866. begin
  3867. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3868. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3869. if TempRegUsed then
  3870. begin
  3871. { Don't remove the first instruction if the temporary register is in use }
  3872. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3873. { No need to set Result to True. If there's another instruction later on
  3874. that can be optimised, it will be detected when the main Pass 1 loop
  3875. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3876. end
  3877. else
  3878. begin
  3879. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3880. RemoveCurrentP(p, hp1);
  3881. Result:=true;
  3882. Exit;
  3883. end;
  3884. end;
  3885. end;
  3886. else
  3887. Internalerror(2019103001);
  3888. end;
  3889. end
  3890. else
  3891. if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3892. begin
  3893. if not CrossJump and
  3894. not RegUsedBetween(p_TargetReg, p, hp2) and
  3895. not RegReadByInstruction(p_TargetReg, hp2) then
  3896. begin
  3897. { Register is not used before it is overwritten }
  3898. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3899. RemoveCurrentp(p, hp1);
  3900. Result := True;
  3901. Exit;
  3902. end;
  3903. if (taicpu(p).oper[0]^.typ = top_const) and
  3904. (taicpu(hp2).oper[0]^.typ = top_const) then
  3905. begin
  3906. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3907. begin
  3908. { Same value - register hasn't changed }
  3909. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3910. RemoveInstruction(hp2);
  3911. Result := True;
  3912. { See if there's more we can optimise }
  3913. Continue;
  3914. end;
  3915. end;
  3916. end;
  3917. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3918. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3919. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  3920. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  3921. begin
  3922. {
  3923. Change from:
  3924. mov ###, %reg
  3925. ...
  3926. movs/z %reg,%reg (Same register, just different sizes)
  3927. To:
  3928. movs/z ###, %reg (Longer version)
  3929. ...
  3930. (remove)
  3931. }
  3932. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3933. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3934. { Keep the first instruction as mov if ### is a constant }
  3935. if taicpu(p).oper[0]^.typ = top_const then
  3936. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3937. else
  3938. begin
  3939. taicpu(p).opcode := taicpu(hp2).opcode;
  3940. taicpu(p).opsize := taicpu(hp2).opsize;
  3941. end;
  3942. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3943. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3944. RemoveInstruction(hp2);
  3945. Result := True;
  3946. JumpTracking.Free;
  3947. Exit;
  3948. end;
  3949. else
  3950. { Move down to the MatchOpType if-block below };
  3951. end;
  3952. { Also catches MOV/S/Z instructions that aren't modified }
  3953. if taicpu(p).oper[0]^.typ = top_reg then
  3954. begin
  3955. p_SourceReg := taicpu(p).oper[0]^.reg;
  3956. if
  3957. not RegModifiedByInstruction(p_SourceReg, hp3) and
  3958. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  3959. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3960. begin
  3961. Result := True;
  3962. { Just in case something didn't get modified (e.g. an
  3963. implicit register). Also, if it does read from this
  3964. register, then there's no longer an advantage to
  3965. changing the register on subsequent instructions.}
  3966. if not RegReadByInstruction(p_TargetReg, hp2) then
  3967. begin
  3968. { If a conditional jump was crossed, do not delete
  3969. the original MOV no matter what }
  3970. if not CrossJump and
  3971. { RegEndOfLife returns True if the register is
  3972. deallocated before the next instruction or has
  3973. been loaded with a new value }
  3974. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  3975. begin
  3976. { We can remove the original MOV }
  3977. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3978. RemoveCurrentp(p, hp1);
  3979. JumpTracking.Free;
  3980. Result := True;
  3981. Exit;
  3982. end;
  3983. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  3984. begin
  3985. { See if there's more we can optimise }
  3986. hp3 := hp2;
  3987. Continue;
  3988. end;
  3989. end;
  3990. end;
  3991. end;
  3992. { Break out of the while loop under normal circumstances }
  3993. Break;
  3994. end;
  3995. JumpTracking.Free;
  3996. end;
  3997. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3998. (taicpu(p).oper[1]^.typ = top_reg) and
  3999. (taicpu(p).opsize = S_L) and
  4000. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4001. (hp2.typ = ait_instruction) and
  4002. (taicpu(hp2).opcode = A_AND) and
  4003. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4004. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4005. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4006. ) then
  4007. begin
  4008. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4009. begin
  4010. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4011. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4012. begin
  4013. { Optimize out:
  4014. mov x, %reg
  4015. and ffffffffh, %reg
  4016. }
  4017. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4018. RemoveInstruction(hp2);
  4019. Result:=true;
  4020. exit;
  4021. end;
  4022. end;
  4023. end;
  4024. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4025. x >= RetOffset) as it doesn't do anything (it writes either to a
  4026. parameter or to the temporary storage room for the function
  4027. result)
  4028. }
  4029. if IsExitCode(hp1) and
  4030. (taicpu(p).oper[1]^.typ = top_ref) and
  4031. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4032. (
  4033. (
  4034. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4035. not (
  4036. assigned(current_procinfo.procdef.funcretsym) and
  4037. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4038. )
  4039. ) or
  4040. { Also discard writes to the stack that are below the base pointer,
  4041. as this is temporary storage rather than a function result on the
  4042. stack, say. }
  4043. (
  4044. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4045. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4046. )
  4047. ) then
  4048. begin
  4049. RemoveCurrentp(p, hp1);
  4050. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4051. RemoveLastDeallocForFuncRes(p);
  4052. Result:=true;
  4053. exit;
  4054. end;
  4055. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4056. begin
  4057. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4058. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4059. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4060. begin
  4061. { change
  4062. mov reg1, mem1
  4063. test/cmp x, mem1
  4064. to
  4065. mov reg1, mem1
  4066. test/cmp x, reg1
  4067. }
  4068. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4069. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4070. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4071. Result := True;
  4072. Exit;
  4073. end;
  4074. if DoMovCmpMemOpt(p, hp1, True) then
  4075. begin
  4076. Result := True;
  4077. Exit;
  4078. end;
  4079. end;
  4080. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4081. { If the flags register is in use, don't change the instruction to an
  4082. ADD otherwise this will scramble the flags. [Kit] }
  4083. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4084. begin
  4085. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4086. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4087. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4088. ) or
  4089. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4090. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4091. )
  4092. ) then
  4093. { mov reg1,ref
  4094. lea reg2,[reg1,reg2]
  4095. to
  4096. add reg2,ref}
  4097. begin
  4098. TransferUsedRegs(TmpUsedRegs);
  4099. { reg1 may not be used afterwards }
  4100. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4101. begin
  4102. Taicpu(hp1).opcode:=A_ADD;
  4103. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4104. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4105. RemoveCurrentp(p, hp1);
  4106. result:=true;
  4107. exit;
  4108. end;
  4109. end;
  4110. { If the LEA instruction can be converted into an arithmetic instruction,
  4111. it may be possible to then fold it in the next optimisation, otherwise
  4112. there's nothing more that can be optimised here. }
  4113. if not ConvertLEA(taicpu(hp1)) then
  4114. Exit;
  4115. end;
  4116. if (taicpu(p).oper[1]^.typ = top_reg) and
  4117. (hp1.typ = ait_instruction) and
  4118. GetNextInstruction(hp1, hp2) and
  4119. MatchInstruction(hp2,A_MOV,[]) and
  4120. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4121. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4122. (
  4123. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4124. {$ifdef x86_64}
  4125. or
  4126. (
  4127. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4128. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4129. )
  4130. {$endif x86_64}
  4131. ) then
  4132. begin
  4133. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4134. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4135. { change movsX/movzX reg/ref, reg2
  4136. add/sub/or/... reg3/$const, reg2
  4137. mov reg2 reg/ref
  4138. dealloc reg2
  4139. to
  4140. add/sub/or/... reg3/$const, reg/ref }
  4141. begin
  4142. TransferUsedRegs(TmpUsedRegs);
  4143. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4144. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4145. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4146. begin
  4147. { by example:
  4148. movswl %si,%eax movswl %si,%eax p
  4149. decl %eax addl %edx,%eax hp1
  4150. movw %ax,%si movw %ax,%si hp2
  4151. ->
  4152. movswl %si,%eax movswl %si,%eax p
  4153. decw %eax addw %edx,%eax hp1
  4154. movw %ax,%si movw %ax,%si hp2
  4155. }
  4156. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4157. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4158. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4159. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4160. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4161. {
  4162. ->
  4163. movswl %si,%eax movswl %si,%eax p
  4164. decw %si addw %dx,%si hp1
  4165. movw %ax,%si movw %ax,%si hp2
  4166. }
  4167. case taicpu(hp1).ops of
  4168. 1:
  4169. begin
  4170. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4171. if taicpu(hp1).oper[0]^.typ=top_reg then
  4172. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4173. end;
  4174. 2:
  4175. begin
  4176. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4177. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4178. (taicpu(hp1).opcode<>A_SHL) and
  4179. (taicpu(hp1).opcode<>A_SHR) and
  4180. (taicpu(hp1).opcode<>A_SAR) then
  4181. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4182. end;
  4183. else
  4184. internalerror(2008042701);
  4185. end;
  4186. {
  4187. ->
  4188. decw %si addw %dx,%si p
  4189. }
  4190. RemoveInstruction(hp2);
  4191. RemoveCurrentP(p, hp1);
  4192. Result:=True;
  4193. Exit;
  4194. end;
  4195. end;
  4196. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4197. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4198. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4199. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4200. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4201. )
  4202. {$ifdef i386}
  4203. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4204. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4205. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4206. {$endif i386}
  4207. then
  4208. { change movsX/movzX reg/ref, reg2
  4209. add/sub/or/... regX/$const, reg2
  4210. mov reg2, reg3
  4211. dealloc reg2
  4212. to
  4213. movsX/movzX reg/ref, reg3
  4214. add/sub/or/... reg3/$const, reg3
  4215. }
  4216. begin
  4217. TransferUsedRegs(TmpUsedRegs);
  4218. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4219. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4220. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4221. begin
  4222. { by example:
  4223. movswl %si,%eax movswl %si,%eax p
  4224. decl %eax addl %edx,%eax hp1
  4225. movw %ax,%si movw %ax,%si hp2
  4226. ->
  4227. movswl %si,%eax movswl %si,%eax p
  4228. decw %eax addw %edx,%eax hp1
  4229. movw %ax,%si movw %ax,%si hp2
  4230. }
  4231. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4232. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4233. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4234. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4235. { limit size of constants as well to avoid assembler errors, but
  4236. check opsize to avoid overflow when left shifting the 1 }
  4237. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4238. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4239. {$ifdef x86_64}
  4240. { Be careful of, for example:
  4241. movl %reg1,%reg2
  4242. addl %reg3,%reg2
  4243. movq %reg2,%reg4
  4244. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4245. }
  4246. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4247. begin
  4248. taicpu(hp2).changeopsize(S_L);
  4249. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4250. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4251. end;
  4252. {$endif x86_64}
  4253. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4254. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4255. if taicpu(p).oper[0]^.typ=top_reg then
  4256. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4257. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4258. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4259. {
  4260. ->
  4261. movswl %si,%eax movswl %si,%eax p
  4262. decw %si addw %dx,%si hp1
  4263. movw %ax,%si movw %ax,%si hp2
  4264. }
  4265. case taicpu(hp1).ops of
  4266. 1:
  4267. begin
  4268. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4269. if taicpu(hp1).oper[0]^.typ=top_reg then
  4270. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4271. end;
  4272. 2:
  4273. begin
  4274. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4275. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4276. (taicpu(hp1).opcode<>A_SHL) and
  4277. (taicpu(hp1).opcode<>A_SHR) and
  4278. (taicpu(hp1).opcode<>A_SAR) then
  4279. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4280. end;
  4281. else
  4282. internalerror(2018111801);
  4283. end;
  4284. {
  4285. ->
  4286. decw %si addw %dx,%si p
  4287. }
  4288. RemoveInstruction(hp2);
  4289. end;
  4290. end;
  4291. end;
  4292. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4293. GetNextInstruction(hp1, hp2) and
  4294. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4295. MatchOperand(Taicpu(p).oper[0]^,0) and
  4296. (Taicpu(p).oper[1]^.typ = top_reg) and
  4297. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4298. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4299. { mov reg1,0
  4300. bts reg1,operand1 --> mov reg1,operand2
  4301. or reg1,operand2 bts reg1,operand1}
  4302. begin
  4303. Taicpu(hp2).opcode:=A_MOV;
  4304. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4305. asml.remove(hp1);
  4306. insertllitem(hp2,hp2.next,hp1);
  4307. RemoveCurrentp(p, hp1);
  4308. Result:=true;
  4309. exit;
  4310. end;
  4311. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4312. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4313. GetNextInstruction(hp1, hp2) and
  4314. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4315. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4316. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4317. { change
  4318. mov reg1,reg2
  4319. sub reg3,reg2
  4320. cmp reg3,reg1
  4321. into
  4322. mov reg1,reg2
  4323. sub reg3,reg2
  4324. }
  4325. begin
  4326. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4327. RemoveInstruction(hp2);
  4328. Result:=true;
  4329. exit;
  4330. end;
  4331. {
  4332. mov ref,reg0
  4333. <op> reg0,reg1
  4334. dealloc reg0
  4335. to
  4336. <op> ref,reg1
  4337. }
  4338. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4339. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4340. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4341. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4342. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4343. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4344. begin
  4345. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4346. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4347. RemoveCurrentp(p, hp1);
  4348. Result:=true;
  4349. exit;
  4350. end;
  4351. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4352. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4353. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4354. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4355. begin
  4356. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4357. {$ifdef x86_64}
  4358. { Convert:
  4359. movq x(ref),%reg64
  4360. shrq y,%reg64
  4361. To:
  4362. movl x+4(ref),%reg32
  4363. shrl y-32,%reg32 (Remove if y = 32)
  4364. }
  4365. if (taicpu(p).opsize = S_Q) and
  4366. (taicpu(hp1).opcode = A_SHR) and
  4367. (taicpu(hp1).oper[0]^.val >= 32) then
  4368. begin
  4369. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4370. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4371. { Convert to 32-bit }
  4372. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4373. taicpu(p).opsize := S_L;
  4374. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4375. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4376. if (taicpu(hp1).oper[0]^.val = 32) then
  4377. begin
  4378. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4379. RemoveInstruction(hp1);
  4380. end
  4381. else
  4382. begin
  4383. { This will potentially open up more arithmetic operations since
  4384. the peephole optimizer now has a big hint that only the lower
  4385. 32 bits are currently in use (and opcodes are smaller in size) }
  4386. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4387. taicpu(hp1).opsize := S_L;
  4388. Dec(taicpu(hp1).oper[0]^.val, 32);
  4389. DebugMsg(SPeepholeOptimization + PreMessage +
  4390. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4391. end;
  4392. Result := True;
  4393. Exit;
  4394. end;
  4395. {$endif x86_64}
  4396. { Convert:
  4397. movl x(ref),%reg
  4398. shrl $24,%reg
  4399. To:
  4400. movzbl x+3(ref),%reg
  4401. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4402. Also accept sar instead of shr, but convert to movsx instead of movzx
  4403. }
  4404. if taicpu(hp1).opcode = A_SHR then
  4405. MovUnaligned := A_MOVZX
  4406. else
  4407. MovUnaligned := A_MOVSX;
  4408. NewSize := S_NO;
  4409. NewOffset := 0;
  4410. case taicpu(p).opsize of
  4411. S_B:
  4412. { No valid combinations };
  4413. S_W:
  4414. if (taicpu(hp1).oper[0]^.val = 8) then
  4415. begin
  4416. NewSize := S_BW;
  4417. NewOffset := 1;
  4418. end;
  4419. S_L:
  4420. case taicpu(hp1).oper[0]^.val of
  4421. 16:
  4422. begin
  4423. NewSize := S_WL;
  4424. NewOffset := 2;
  4425. end;
  4426. 24:
  4427. begin
  4428. NewSize := S_BL;
  4429. NewOffset := 3;
  4430. end;
  4431. else
  4432. ;
  4433. end;
  4434. {$ifdef x86_64}
  4435. S_Q:
  4436. case taicpu(hp1).oper[0]^.val of
  4437. 32:
  4438. begin
  4439. if taicpu(hp1).opcode = A_SAR then
  4440. begin
  4441. { 32-bit to 64-bit is a distinct instruction }
  4442. MovUnaligned := A_MOVSXD;
  4443. NewSize := S_LQ;
  4444. NewOffset := 4;
  4445. end
  4446. else
  4447. { Should have been handled by MovShr2Mov above }
  4448. InternalError(2022081811);
  4449. end;
  4450. 48:
  4451. begin
  4452. NewSize := S_WQ;
  4453. NewOffset := 6;
  4454. end;
  4455. 56:
  4456. begin
  4457. NewSize := S_BQ;
  4458. NewOffset := 7;
  4459. end;
  4460. else
  4461. ;
  4462. end;
  4463. {$endif x86_64}
  4464. else
  4465. InternalError(2022081810);
  4466. end;
  4467. if (NewSize <> S_NO) and
  4468. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4469. begin
  4470. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4471. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4472. debug_op2str(MovUnaligned);
  4473. {$ifdef x86_64}
  4474. if MovUnaligned <> A_MOVSXD then
  4475. { Don't add size suffix for MOVSXD }
  4476. {$endif x86_64}
  4477. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4478. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4479. taicpu(p).opcode := MovUnaligned;
  4480. taicpu(p).opsize := NewSize;
  4481. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4482. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4483. RemoveInstruction(hp1);
  4484. Result := True;
  4485. Exit;
  4486. end;
  4487. end;
  4488. { Backward optimisation shared with OptPass2MOV }
  4489. if FuncMov2Func(p, hp1) then
  4490. begin
  4491. Result := True;
  4492. Exit;
  4493. end;
  4494. end;
  4495. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4496. var
  4497. hp1 : tai;
  4498. begin
  4499. Result:=false;
  4500. if taicpu(p).ops <> 2 then
  4501. exit;
  4502. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4503. GetNextInstruction(p,hp1) then
  4504. begin
  4505. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4506. (taicpu(hp1).ops = 2) then
  4507. begin
  4508. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4509. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4510. { movXX reg1, mem1 or movXX mem1, reg1
  4511. movXX mem2, reg2 movXX reg2, mem2}
  4512. begin
  4513. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4514. { movXX reg1, mem1 or movXX mem1, reg1
  4515. movXX mem2, reg1 movXX reg2, mem1}
  4516. begin
  4517. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4518. begin
  4519. { Removes the second statement from
  4520. movXX reg1, mem1/reg2
  4521. movXX mem1/reg2, reg1
  4522. }
  4523. if taicpu(p).oper[0]^.typ=top_reg then
  4524. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4525. { Removes the second statement from
  4526. movXX mem1/reg1, reg2
  4527. movXX reg2, mem1/reg1
  4528. }
  4529. if (taicpu(p).oper[1]^.typ=top_reg) and
  4530. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4531. begin
  4532. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4533. RemoveInstruction(hp1);
  4534. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4535. Result:=true;
  4536. exit;
  4537. end
  4538. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4539. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4540. begin
  4541. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4542. RemoveInstruction(hp1);
  4543. Result:=true;
  4544. exit;
  4545. end;
  4546. end
  4547. end;
  4548. end;
  4549. end;
  4550. end;
  4551. end;
  4552. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4553. var
  4554. hp1 : tai;
  4555. begin
  4556. result:=false;
  4557. { replace
  4558. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4559. MovX %mreg2,%mreg1
  4560. dealloc %mreg2
  4561. by
  4562. <Op>X %mreg2,%mreg1
  4563. ?
  4564. }
  4565. if GetNextInstruction(p,hp1) and
  4566. { we mix single and double opperations here because we assume that the compiler
  4567. generates vmovapd only after double operations and vmovaps only after single operations }
  4568. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4569. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4570. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4571. (taicpu(p).oper[0]^.typ=top_reg) then
  4572. begin
  4573. TransferUsedRegs(TmpUsedRegs);
  4574. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4575. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4576. begin
  4577. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4578. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4579. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4580. RemoveInstruction(hp1);
  4581. result:=true;
  4582. end;
  4583. end;
  4584. end;
  4585. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4586. var
  4587. hp1, p_label, p_dist, hp1_dist: tai;
  4588. JumpLabel, JumpLabel_dist: TAsmLabel;
  4589. FirstValue, SecondValue: TCGInt;
  4590. TempBool: Boolean;
  4591. begin
  4592. Result := False;
  4593. if (taicpu(p).oper[0]^.typ = top_const) and
  4594. (taicpu(p).oper[0]^.val <> -1) then
  4595. begin
  4596. { Convert unsigned maximum constants to -1 to aid optimisation }
  4597. case taicpu(p).opsize of
  4598. S_B:
  4599. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4600. begin
  4601. taicpu(p).oper[0]^.val := -1;
  4602. Result := True;
  4603. Exit;
  4604. end;
  4605. S_W:
  4606. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4607. begin
  4608. taicpu(p).oper[0]^.val := -1;
  4609. Result := True;
  4610. Exit;
  4611. end;
  4612. S_L:
  4613. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4614. begin
  4615. taicpu(p).oper[0]^.val := -1;
  4616. Result := True;
  4617. Exit;
  4618. end;
  4619. {$ifdef x86_64}
  4620. S_Q:
  4621. { Storing anything greater than $7FFFFFFF is not possible so do
  4622. nothing };
  4623. {$endif x86_64}
  4624. else
  4625. InternalError(2021121001);
  4626. end;
  4627. end;
  4628. if GetNextInstruction(p, hp1) and
  4629. TrySwapMovCmp(p, hp1) then
  4630. begin
  4631. Result := True;
  4632. Exit;
  4633. end;
  4634. if MatchInstruction(hp1, A_Jcc, []) then
  4635. begin
  4636. TempBool := True;
  4637. if DoJumpOptimizations(hp1, TempBool) or
  4638. not TempBool then
  4639. begin
  4640. Result := True;
  4641. if Assigned(hp1) then
  4642. begin
  4643. if (hp1.typ in [ait_align]) then
  4644. SkipAligns(hp1, hp1);
  4645. { CollapseZeroDistJump will be set to the label after the
  4646. jump if it optimises, whether or not it's live or dead }
  4647. if (hp1.typ in [ait_label]) and
  4648. not (tai_label(hp1).labsym.is_used) then
  4649. GetNextInstruction(hp1, hp1);
  4650. end;
  4651. TransferUsedRegs(TmpUsedRegs);
  4652. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4653. if not Assigned(hp1) or
  4654. (
  4655. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4656. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4657. ) then
  4658. begin
  4659. { No more conditional jumps; conditional statement is no longer required }
  4660. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4661. RemoveCurrentP(p);
  4662. end;
  4663. Exit;
  4664. end;
  4665. end;
  4666. { Search for:
  4667. test $x,(reg/ref)
  4668. jne @lbl1
  4669. test $y,(reg/ref) (same register or reference)
  4670. jne @lbl1
  4671. Change to:
  4672. test $(x or y),(reg/ref)
  4673. jne @lbl1
  4674. (Note, this doesn't work with je instead of jne)
  4675. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4676. Also search for:
  4677. test $x,(reg/ref)
  4678. je @lbl1
  4679. test $y,(reg/ref)
  4680. je/jne @lbl2
  4681. If (x or y) = x, then the second jump is deterministic
  4682. }
  4683. if (
  4684. (
  4685. (taicpu(p).oper[0]^.typ = top_const) or
  4686. (
  4687. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4688. (taicpu(p).oper[0]^.typ = top_reg) and
  4689. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4690. )
  4691. ) and
  4692. MatchInstruction(hp1, A_JCC, [])
  4693. ) then
  4694. begin
  4695. if (taicpu(p).oper[0]^.typ = top_reg) and
  4696. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4697. FirstValue := -1
  4698. else
  4699. FirstValue := taicpu(p).oper[0]^.val;
  4700. { If we have several test/jne's in a row, it might be the case that
  4701. the second label doesn't go to the same location, but the one
  4702. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4703. so accommodate for this with a while loop.
  4704. }
  4705. hp1_dist := hp1;
  4706. if GetNextInstruction(hp1, p_dist) and
  4707. (p_dist.typ = ait_instruction) and
  4708. (
  4709. (
  4710. (taicpu(p_dist).opcode = A_TEST) and
  4711. (
  4712. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4713. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4714. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4715. )
  4716. ) or
  4717. (
  4718. { cmp 0,%reg = test %reg,%reg }
  4719. (taicpu(p_dist).opcode = A_CMP) and
  4720. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4721. )
  4722. ) and
  4723. { Make sure the destination operands are actually the same }
  4724. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4725. GetNextInstruction(p_dist, hp1_dist) and
  4726. MatchInstruction(hp1_dist, A_JCC, []) then
  4727. begin
  4728. if
  4729. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4730. (
  4731. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4732. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4733. ) then
  4734. SecondValue := -1
  4735. else
  4736. SecondValue := taicpu(p_dist).oper[0]^.val;
  4737. { If both of the TEST constants are identical, delete the second
  4738. TEST that is unnecessary. }
  4739. if (FirstValue = SecondValue) then
  4740. begin
  4741. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4742. RemoveInstruction(p_dist);
  4743. { Don't let the flags register become deallocated and reallocated between the jumps }
  4744. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4745. Result := True;
  4746. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4747. begin
  4748. { Since the second jump's condition is a subset of the first, we
  4749. know it will never branch because the first jump dominates it.
  4750. Get it out of the way now rather than wait for the jump
  4751. optimisations for a speed boost. }
  4752. if IsJumpToLabel(taicpu(hp1_dist)) then
  4753. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4754. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4755. RemoveInstruction(hp1_dist);
  4756. end
  4757. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4758. begin
  4759. { If the inverse of the first condition is a subset of the second,
  4760. the second one will definitely branch if the first one doesn't }
  4761. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4762. MakeUnconditional(taicpu(hp1_dist));
  4763. RemoveDeadCodeAfterJump(hp1_dist);
  4764. end;
  4765. Exit;
  4766. end;
  4767. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4768. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4769. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4770. then the second jump will never branch, so it can also be
  4771. removed regardless of where it goes }
  4772. (
  4773. (FirstValue = -1) or
  4774. (SecondValue = -1) or
  4775. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4776. ) then
  4777. begin
  4778. { Same jump location... can be a register since nothing's changed }
  4779. { If any of the entries are equivalent to test %reg,%reg, then the
  4780. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4781. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4782. if IsJumpToLabel(taicpu(hp1_dist)) then
  4783. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4784. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4785. RemoveInstruction(hp1_dist);
  4786. { Only remove the second test if no jumps or other conditional instructions follow }
  4787. TransferUsedRegs(TmpUsedRegs);
  4788. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4789. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4790. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4791. RemoveInstruction(p_dist);
  4792. Result := True;
  4793. Exit;
  4794. end;
  4795. end;
  4796. end;
  4797. { Search for:
  4798. test %reg,%reg
  4799. j(c1) @lbl1
  4800. ...
  4801. @lbl:
  4802. test %reg,%reg (same register)
  4803. j(c2) @lbl2
  4804. If c2 is a subset of c1, change to:
  4805. test %reg,%reg
  4806. j(c1) @lbl2
  4807. (@lbl1 may become a dead label as a result)
  4808. }
  4809. if (taicpu(p).oper[1]^.typ = top_reg) and
  4810. (taicpu(p).oper[0]^.typ = top_reg) and
  4811. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4812. MatchInstruction(hp1, A_JCC, []) and
  4813. IsJumpToLabel(taicpu(hp1)) then
  4814. begin
  4815. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4816. p_label := nil;
  4817. if Assigned(JumpLabel) then
  4818. p_label := getlabelwithsym(JumpLabel);
  4819. if Assigned(p_label) and
  4820. GetNextInstruction(p_label, p_dist) and
  4821. MatchInstruction(p_dist, A_TEST, []) and
  4822. { It's fine if the second test uses smaller sub-registers }
  4823. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4824. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4825. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4826. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4827. GetNextInstruction(p_dist, hp1_dist) and
  4828. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4829. begin
  4830. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4831. if JumpLabel = JumpLabel_dist then
  4832. { This is an infinite loop }
  4833. Exit;
  4834. { Best optimisation when the first condition is a subset (or equal) of the second }
  4835. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4836. begin
  4837. { Any registers used here will already be allocated }
  4838. if Assigned(JumpLabel) then
  4839. JumpLabel.DecRefs;
  4840. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4841. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4842. Result := True;
  4843. Exit;
  4844. end;
  4845. end;
  4846. end;
  4847. end;
  4848. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4849. var
  4850. hp1, hp2: tai;
  4851. ActiveReg: TRegister;
  4852. OldOffset: asizeint;
  4853. ThisConst: TCGInt;
  4854. function RegDeallocated: Boolean;
  4855. begin
  4856. TransferUsedRegs(TmpUsedRegs);
  4857. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4858. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4859. end;
  4860. begin
  4861. result:=false;
  4862. hp1 := nil;
  4863. { replace
  4864. addX const,%reg1
  4865. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4866. dealloc %reg1
  4867. by
  4868. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4869. }
  4870. if MatchOpType(taicpu(p),top_const,top_reg) then
  4871. begin
  4872. ActiveReg := taicpu(p).oper[1]^.reg;
  4873. { Ensures the entire register was updated }
  4874. if (taicpu(p).opsize >= S_L) and
  4875. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4876. MatchInstruction(hp1,A_LEA,[]) and
  4877. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4878. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4879. (
  4880. { Cover the case where the register in the reference is also the destination register }
  4881. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4882. (
  4883. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4884. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4885. RegDeallocated
  4886. )
  4887. ) then
  4888. begin
  4889. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4890. {$push}
  4891. {$R-}{$Q-}
  4892. { Explicitly disable overflow checking for these offset calculation
  4893. as those do not matter for the final result }
  4894. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4895. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4896. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4897. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4898. {$pop}
  4899. {$ifdef x86_64}
  4900. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4901. begin
  4902. { Overflow; abort }
  4903. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4904. end
  4905. else
  4906. {$endif x86_64}
  4907. begin
  4908. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4909. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4910. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4911. RemoveCurrentP(p, hp1)
  4912. else
  4913. RemoveCurrentP(p);
  4914. result:=true;
  4915. Exit;
  4916. end;
  4917. end;
  4918. if (
  4919. { Save calling GetNextInstructionUsingReg again }
  4920. Assigned(hp1) or
  4921. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4922. ) and
  4923. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4924. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4925. begin
  4926. if taicpu(hp1).oper[0]^.typ = top_const then
  4927. begin
  4928. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4929. if taicpu(hp1).opcode = A_ADD then
  4930. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4931. else
  4932. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4933. Result := True;
  4934. { Handle any overflows }
  4935. case taicpu(p).opsize of
  4936. S_B:
  4937. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4938. S_W:
  4939. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4940. S_L:
  4941. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4942. {$ifdef x86_64}
  4943. S_Q:
  4944. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4945. { Overflow; abort }
  4946. Result := False
  4947. else
  4948. taicpu(p).oper[0]^.val := ThisConst;
  4949. {$endif x86_64}
  4950. else
  4951. InternalError(2021102610);
  4952. end;
  4953. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4954. if Result then
  4955. begin
  4956. if (taicpu(p).oper[0]^.val < 0) and
  4957. (
  4958. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4959. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4960. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4961. ) then
  4962. begin
  4963. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4964. taicpu(p).opcode := A_SUB;
  4965. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4966. end
  4967. else
  4968. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4969. RemoveInstruction(hp1);
  4970. end;
  4971. end
  4972. else
  4973. begin
  4974. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4975. TransferUsedRegs(TmpUsedRegs);
  4976. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4977. hp2 := p;
  4978. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4979. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4980. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4981. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4982. begin
  4983. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4984. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4985. Asml.Remove(p);
  4986. Asml.InsertAfter(p, hp1);
  4987. p := hp1;
  4988. Result := True;
  4989. Exit;
  4990. end;
  4991. end;
  4992. end;
  4993. if DoArithCombineOpt(p) then
  4994. Result:=true;
  4995. end;
  4996. end;
  4997. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4998. var
  4999. hp1: tai;
  5000. ref: Integer;
  5001. saveref: treference;
  5002. Multiple: TCGInt;
  5003. Adjacent: Boolean;
  5004. begin
  5005. Result:=false;
  5006. { play save and throw an error if LEA uses a seg register prefix,
  5007. this is most likely an error somewhere else }
  5008. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5009. internalerror(2022022001);
  5010. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5011. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5012. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5013. (
  5014. { do not mess with leas accessing the stack pointer
  5015. unless it's a null operation }
  5016. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5017. (
  5018. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5019. (taicpu(p).oper[0]^.ref^.offset = 0)
  5020. )
  5021. ) and
  5022. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5023. begin
  5024. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5025. begin
  5026. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5027. begin
  5028. taicpu(p).opcode := A_MOV;
  5029. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5030. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5031. end
  5032. else
  5033. begin
  5034. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5035. RemoveCurrentP(p);
  5036. end;
  5037. Result:=true;
  5038. exit;
  5039. end
  5040. else if (
  5041. { continue to use lea to adjust the stack pointer,
  5042. it is the recommended way, but only if not optimizing for size }
  5043. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5044. (cs_opt_size in current_settings.optimizerswitches)
  5045. ) and
  5046. { If the flags register is in use, don't change the instruction
  5047. to an ADD otherwise this will scramble the flags. [Kit] }
  5048. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5049. ConvertLEA(taicpu(p)) then
  5050. begin
  5051. Result:=true;
  5052. exit;
  5053. end;
  5054. end;
  5055. { Don't optimise if the stack or frame pointer is the destination register }
  5056. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5057. Exit;
  5058. if GetNextInstruction(p,hp1) and
  5059. (hp1.typ=ait_instruction) then
  5060. begin
  5061. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5062. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5063. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5064. begin
  5065. TransferUsedRegs(TmpUsedRegs);
  5066. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5067. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5068. begin
  5069. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5070. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5071. RemoveInstruction(hp1);
  5072. result:=true;
  5073. exit;
  5074. end;
  5075. end;
  5076. { changes
  5077. lea <ref1>, reg1
  5078. <op> ...,<ref. with reg1>,...
  5079. to
  5080. <op> ...,<ref1>,... }
  5081. { find a reference which uses reg1 }
  5082. 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
  5083. ref:=0
  5084. 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
  5085. ref:=1
  5086. else
  5087. ref:=-1;
  5088. if (ref<>-1) and
  5089. { reg1 must be either the base or the index }
  5090. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5091. begin
  5092. { reg1 can be removed from the reference }
  5093. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5094. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5095. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5096. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5097. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5098. else
  5099. Internalerror(2019111201);
  5100. { check if the can insert all data of the lea into the second instruction }
  5101. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5102. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5103. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5104. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5105. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5106. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5107. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5108. {$ifdef x86_64}
  5109. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5110. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5111. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5112. )
  5113. {$endif x86_64}
  5114. then
  5115. begin
  5116. { reg1 might not used by the second instruction after it is remove from the reference }
  5117. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5118. begin
  5119. TransferUsedRegs(TmpUsedRegs);
  5120. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5121. { reg1 is not updated so it might not be used afterwards }
  5122. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5123. begin
  5124. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5125. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5126. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5127. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5128. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5129. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5130. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5131. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5132. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5133. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5134. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5135. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5136. RemoveCurrentP(p, hp1);
  5137. result:=true;
  5138. exit;
  5139. end
  5140. end;
  5141. end;
  5142. { recover }
  5143. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5144. end;
  5145. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5146. if Adjacent or
  5147. { Check further ahead (up to 2 instructions ahead for -O2) }
  5148. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5149. begin
  5150. { Check common LEA/LEA conditions }
  5151. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5152. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  5153. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5154. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5155. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5156. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5157. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5158. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5159. (
  5160. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5161. calling it (since it calls GetNextInstruction) }
  5162. Adjacent or
  5163. (
  5164. (
  5165. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5166. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5167. ) and (
  5168. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5169. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5170. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5171. )
  5172. )
  5173. ) then
  5174. begin
  5175. { changes
  5176. lea (regX,scale), reg1
  5177. lea offset(reg1,reg1), reg1
  5178. to
  5179. lea offset(regX,scale*2), reg1
  5180. and
  5181. lea (regX,scale1), reg1
  5182. lea offset(reg1,scale2), reg1
  5183. to
  5184. lea offset(regX,scale1*scale2), reg1
  5185. ... so long as the final scale does not exceed 8
  5186. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5187. }
  5188. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5189. (taicpu(p).oper[0]^.ref^.offset = 0) and
  5190. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5191. (
  5192. (
  5193. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5194. ) or (
  5195. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5196. (
  5197. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5198. (
  5199. { RegUsedBetween always returns False if p and hp1 are adjacent }
  5200. Adjacent or
  5201. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  5202. )
  5203. )
  5204. )
  5205. ) and (
  5206. (
  5207. { lea (reg1,scale2), reg1 variant }
  5208. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  5209. (
  5210. (
  5211. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5212. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5213. ) or (
  5214. { lea (regX,regX), reg1 variant }
  5215. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5216. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5217. )
  5218. )
  5219. ) or (
  5220. { lea (reg1,reg1), reg1 variant }
  5221. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5222. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5223. )
  5224. ) then
  5225. begin
  5226. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5227. { Make everything homogeneous to make calculations easier }
  5228. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5229. begin
  5230. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5231. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5232. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5233. else
  5234. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5235. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5236. end;
  5237. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  5238. begin
  5239. { Just to prevent miscalculations }
  5240. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5241. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5242. else
  5243. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  5244. end
  5245. else
  5246. begin
  5247. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5248. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5249. end;
  5250. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5251. RemoveCurrentP(p);
  5252. result:=true;
  5253. exit;
  5254. end
  5255. { changes
  5256. lea offset1(regX), reg1
  5257. lea offset2(reg1), reg1
  5258. to
  5259. lea offset1+offset2(regX), reg1 }
  5260. else if
  5261. (
  5262. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5263. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5264. ) or (
  5265. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5266. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5267. (
  5268. (
  5269. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5270. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5271. ) or (
  5272. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5273. (
  5274. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5275. (
  5276. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5277. (
  5278. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5279. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5280. )
  5281. )
  5282. )
  5283. )
  5284. )
  5285. ) then
  5286. begin
  5287. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5288. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5289. begin
  5290. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5291. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5292. { if the register is used as index and base, we have to increase for base as well
  5293. and adapt base }
  5294. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5295. begin
  5296. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5297. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5298. end;
  5299. end
  5300. else
  5301. begin
  5302. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5303. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5304. end;
  5305. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5306. begin
  5307. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5308. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5309. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5310. end;
  5311. RemoveCurrentP(p);
  5312. result:=true;
  5313. exit;
  5314. end;
  5315. end;
  5316. { Change:
  5317. leal/q $x(%reg1),%reg2
  5318. ...
  5319. shll/q $y,%reg2
  5320. To:
  5321. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5322. }
  5323. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5324. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5325. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5326. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5327. (taicpu(hp1).oper[0]^.val <= 3) then
  5328. begin
  5329. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5330. TransferUsedRegs(TmpUsedRegs);
  5331. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5332. if
  5333. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5334. (this works even if scalefactor is zero) }
  5335. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5336. { Ensure offset doesn't go out of bounds }
  5337. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5338. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5339. (
  5340. (
  5341. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5342. (
  5343. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5344. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5345. (
  5346. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5347. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5348. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5349. )
  5350. )
  5351. ) or (
  5352. (
  5353. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5354. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5355. ) and
  5356. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5357. )
  5358. ) then
  5359. begin
  5360. repeat
  5361. with taicpu(p).oper[0]^.ref^ do
  5362. begin
  5363. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5364. if index = base then
  5365. begin
  5366. if Multiple > 4 then
  5367. { Optimisation will no longer work because resultant
  5368. scale factor will exceed 8 }
  5369. Break;
  5370. base := NR_NO;
  5371. scalefactor := 2;
  5372. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5373. end
  5374. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5375. begin
  5376. { Scale factor only works on the index register }
  5377. index := base;
  5378. base := NR_NO;
  5379. end;
  5380. { For safety }
  5381. if scalefactor <= 1 then
  5382. begin
  5383. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5384. scalefactor := Multiple;
  5385. end
  5386. else
  5387. begin
  5388. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5389. scalefactor := scalefactor * Multiple;
  5390. end;
  5391. offset := offset * Multiple;
  5392. end;
  5393. RemoveInstruction(hp1);
  5394. Result := True;
  5395. Exit;
  5396. { This repeat..until loop exists for the benefit of Break }
  5397. until True;
  5398. end;
  5399. end;
  5400. end;
  5401. end;
  5402. end;
  5403. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5404. var
  5405. hp1 : tai;
  5406. SubInstr: Boolean;
  5407. ThisConst: TCGInt;
  5408. const
  5409. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5410. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5411. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5412. begin
  5413. Result := False;
  5414. if taicpu(p).oper[0]^.typ <> top_const then
  5415. { Should have been confirmed before calling }
  5416. InternalError(2021102601);
  5417. SubInstr := (taicpu(p).opcode = A_SUB);
  5418. if GetLastInstruction(p, hp1) and
  5419. (hp1.typ = ait_instruction) and
  5420. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5421. begin
  5422. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5423. { Bad size }
  5424. InternalError(2022042001);
  5425. case taicpu(hp1).opcode Of
  5426. A_INC:
  5427. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5428. begin
  5429. if SubInstr then
  5430. ThisConst := taicpu(p).oper[0]^.val - 1
  5431. else
  5432. ThisConst := taicpu(p).oper[0]^.val + 1;
  5433. end
  5434. else
  5435. Exit;
  5436. A_DEC:
  5437. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5438. begin
  5439. if SubInstr then
  5440. ThisConst := taicpu(p).oper[0]^.val + 1
  5441. else
  5442. ThisConst := taicpu(p).oper[0]^.val - 1;
  5443. end
  5444. else
  5445. Exit;
  5446. A_SUB:
  5447. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5448. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5449. begin
  5450. if SubInstr then
  5451. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5452. else
  5453. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5454. end
  5455. else
  5456. Exit;
  5457. A_ADD:
  5458. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5459. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5460. begin
  5461. if SubInstr then
  5462. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5463. else
  5464. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5465. end
  5466. else
  5467. Exit;
  5468. else
  5469. Exit;
  5470. end;
  5471. { Check that the values are in range }
  5472. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5473. { Overflow; abort }
  5474. Exit;
  5475. if (ThisConst = 0) then
  5476. begin
  5477. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5478. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5479. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5480. RemoveInstruction(hp1);
  5481. hp1 := tai(p.next);
  5482. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5483. if not GetLastInstruction(hp1, p) then
  5484. p := hp1;
  5485. end
  5486. else
  5487. begin
  5488. if taicpu(hp1).opercnt=1 then
  5489. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5490. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5491. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5492. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5493. else
  5494. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5495. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5496. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5497. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5498. RemoveInstruction(hp1);
  5499. taicpu(p).loadconst(0, ThisConst);
  5500. end;
  5501. Result := True;
  5502. end;
  5503. end;
  5504. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5505. begin
  5506. Result := False;
  5507. if UpdateTmpUsedRegs then
  5508. TransferUsedRegs(TmpUsedRegs);
  5509. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5510. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5511. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5512. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5513. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5514. (
  5515. (
  5516. (taicpu(hp1).opcode = A_TEST)
  5517. ) or (
  5518. (taicpu(hp1).opcode = A_CMP) and
  5519. { A sanity check more than anything }
  5520. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5521. )
  5522. ) then
  5523. begin
  5524. { change
  5525. mov mem, %reg
  5526. cmp/test x, %reg / test %reg,%reg
  5527. (reg deallocated)
  5528. to
  5529. cmp/test x, mem / cmp 0, mem
  5530. }
  5531. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5532. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5533. begin
  5534. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5535. if (taicpu(hp1).opcode = A_TEST) and
  5536. (
  5537. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5538. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5539. ) then
  5540. begin
  5541. taicpu(hp1).opcode := A_CMP;
  5542. taicpu(hp1).loadconst(0, 0);
  5543. end;
  5544. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5545. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5546. RemoveCurrentP(p, hp1);
  5547. Result := True;
  5548. Exit;
  5549. end;
  5550. end;
  5551. end;
  5552. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5553. var
  5554. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5555. ThisReg, SecondReg: TRegister;
  5556. JumpLoc: TAsmLabel;
  5557. NewSize: TOpSize;
  5558. begin
  5559. Result := False;
  5560. {
  5561. Convert:
  5562. j<c> .L1
  5563. .L2:
  5564. mov 1,reg
  5565. jmp .L3 (or ret, although it might not be a RET yet)
  5566. .L1:
  5567. mov 0,reg
  5568. jmp .L3 (or ret)
  5569. ( As long as .L3 <> .L1 or .L2)
  5570. To:
  5571. mov 0,reg
  5572. set<not(c)> reg
  5573. jmp .L3 (or ret)
  5574. .L2:
  5575. mov 1,reg
  5576. jmp .L3 (or ret)
  5577. .L1:
  5578. mov 0,reg
  5579. jmp .L3 (or ret)
  5580. }
  5581. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5582. Exit;
  5583. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5584. if GetNextInstruction(hp_label, hp2) and
  5585. MatchInstruction(hp2,A_MOV,[]) and
  5586. (taicpu(hp2).oper[0]^.typ = top_const) and
  5587. (
  5588. (
  5589. (taicpu(hp2).oper[1]^.typ = top_reg)
  5590. {$ifdef i386}
  5591. { Under i386, ESI, EDI, EBP and ESP
  5592. don't have an 8-bit representation }
  5593. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5594. {$endif i386}
  5595. ) or (
  5596. {$ifdef i386}
  5597. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5598. {$endif i386}
  5599. (taicpu(hp2).opsize = S_B)
  5600. )
  5601. ) and
  5602. GetNextInstruction(hp2, hp3) and
  5603. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5604. (
  5605. (taicpu(hp3).opcode=A_RET) or
  5606. (
  5607. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5608. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5609. )
  5610. ) and
  5611. GetNextInstruction(hp3, hp4) and
  5612. SkipAligns(hp4, hp4) and
  5613. (hp4.typ=ait_label) and
  5614. (tai_label(hp4).labsym=JumpLoc) and
  5615. (
  5616. not (cs_opt_size in current_settings.optimizerswitches) or
  5617. { If the initial jump is the label's only reference, then it will
  5618. become a dead label if the other conditions are met and hence
  5619. remove at least 2 instructions, including a jump }
  5620. (JumpLoc.getrefs = 1)
  5621. ) and
  5622. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5623. that will be optimised out }
  5624. GetNextInstruction(hp4, hp5) and
  5625. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5626. (taicpu(hp5).oper[0]^.typ = top_const) and
  5627. (
  5628. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5629. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5630. ) and
  5631. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5632. GetNextInstruction(hp5,hp6) and
  5633. (
  5634. (hp6.typ<>ait_label) or
  5635. SkipLabels(hp6, hp6)
  5636. ) and
  5637. (hp6.typ=ait_instruction) then
  5638. begin
  5639. { First, let's look at the two jumps that are hp3 and hp6 }
  5640. if not
  5641. (
  5642. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5643. (
  5644. (taicpu(hp6).opcode=A_RET) or
  5645. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5646. )
  5647. ) then
  5648. { If condition is False, then the JMP/RET instructions matched conventionally }
  5649. begin
  5650. { See if one of the jumps can be instantly converted into a RET }
  5651. if (taicpu(hp3).opcode=A_JMP) then
  5652. begin
  5653. { Reuse hp5 }
  5654. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5655. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5656. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5657. Exit;
  5658. if MatchInstruction(hp5, A_RET, []) then
  5659. begin
  5660. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5661. ConvertJumpToRET(hp3, hp5);
  5662. Result := True;
  5663. end
  5664. else
  5665. Exit;
  5666. end;
  5667. if (taicpu(hp6).opcode=A_JMP) then
  5668. begin
  5669. { Reuse hp5 }
  5670. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5671. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5672. Exit;
  5673. if MatchInstruction(hp5, A_RET, []) then
  5674. begin
  5675. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5676. ConvertJumpToRET(hp6, hp5);
  5677. Result := True;
  5678. end
  5679. else
  5680. Exit;
  5681. end;
  5682. if not
  5683. (
  5684. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5685. (
  5686. (taicpu(hp6).opcode=A_RET) or
  5687. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5688. )
  5689. ) then
  5690. { Still doesn't match }
  5691. Exit;
  5692. end;
  5693. if (taicpu(hp2).oper[0]^.val = 1) then
  5694. begin
  5695. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5696. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5697. end
  5698. else
  5699. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5700. if taicpu(hp2).opsize=S_B then
  5701. begin
  5702. if taicpu(hp2).oper[1]^.typ = top_reg then
  5703. begin
  5704. SecondReg := taicpu(hp2).oper[1]^.reg;
  5705. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  5706. end
  5707. else
  5708. begin
  5709. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5710. SecondReg := NR_NO;
  5711. end;
  5712. hp_pos := p;
  5713. hp_allocstart := hp4;
  5714. end
  5715. else
  5716. begin
  5717. { Will be a register because the size can't be S_B otherwise }
  5718. SecondReg:=taicpu(hp2).oper[1]^.reg;
  5719. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  5720. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5721. if (cs_opt_size in current_settings.optimizerswitches) then
  5722. begin
  5723. { Favour using MOVZX when optimising for size }
  5724. case taicpu(hp2).opsize of
  5725. S_W:
  5726. NewSize := S_BW;
  5727. S_L:
  5728. NewSize := S_BL;
  5729. {$ifdef x86_64}
  5730. S_Q:
  5731. begin
  5732. NewSize := S_BL;
  5733. { Will implicitly zero-extend to 64-bit }
  5734. setsubreg(SecondReg, R_SUBD);
  5735. end;
  5736. {$endif x86_64}
  5737. else
  5738. InternalError(2022101301);
  5739. end;
  5740. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  5741. { Inserting it right before p will guarantee that the flags are also tracked }
  5742. Asml.InsertBefore(hp5, p);
  5743. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  5744. hp_pos := hp5;
  5745. hp_allocstart := hp4;
  5746. end
  5747. else
  5748. begin
  5749. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  5750. { Inserting it right before p will guarantee that the flags are also tracked }
  5751. Asml.InsertBefore(hp5, p);
  5752. hp_pos := p;
  5753. hp_allocstart := hp5;
  5754. end;
  5755. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  5756. end;
  5757. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  5758. taicpu(hp4).condition := taicpu(p).condition;
  5759. asml.InsertBefore(hp4, hp_pos);
  5760. if taicpu(hp3).is_jmp then
  5761. begin
  5762. JumpLoc.decrefs;
  5763. MakeUnconditional(taicpu(p));
  5764. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5765. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5766. end
  5767. else
  5768. ConvertJumpToRET(p, hp3);
  5769. if SecondReg <> NR_NO then
  5770. { Ensure the destination register is allocated over this region }
  5771. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  5772. if (JumpLoc.getrefs = 0) then
  5773. RemoveDeadCodeAfterJump(hp3);
  5774. Result:=true;
  5775. exit;
  5776. end;
  5777. end;
  5778. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5779. var
  5780. hp1, hp2: tai;
  5781. ActiveReg: TRegister;
  5782. OldOffset: asizeint;
  5783. ThisConst: TCGInt;
  5784. function RegDeallocated: Boolean;
  5785. begin
  5786. TransferUsedRegs(TmpUsedRegs);
  5787. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5788. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5789. end;
  5790. begin
  5791. Result:=false;
  5792. hp1 := nil;
  5793. { replace
  5794. subX const,%reg1
  5795. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5796. dealloc %reg1
  5797. by
  5798. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5799. }
  5800. if MatchOpType(taicpu(p),top_const,top_reg) then
  5801. begin
  5802. ActiveReg := taicpu(p).oper[1]^.reg;
  5803. { Ensures the entire register was updated }
  5804. if (taicpu(p).opsize >= S_L) and
  5805. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5806. MatchInstruction(hp1,A_LEA,[]) and
  5807. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5808. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5809. (
  5810. { Cover the case where the register in the reference is also the destination register }
  5811. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5812. (
  5813. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5814. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5815. RegDeallocated
  5816. )
  5817. ) then
  5818. begin
  5819. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5820. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5821. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5822. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5823. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5824. {$ifdef x86_64}
  5825. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5826. begin
  5827. { Overflow; abort }
  5828. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5829. end
  5830. else
  5831. {$endif x86_64}
  5832. begin
  5833. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5834. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5835. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5836. RemoveCurrentP(p, hp1)
  5837. else
  5838. RemoveCurrentP(p);
  5839. result:=true;
  5840. Exit;
  5841. end;
  5842. end;
  5843. if (
  5844. { Save calling GetNextInstructionUsingReg again }
  5845. Assigned(hp1) or
  5846. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5847. ) and
  5848. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5849. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5850. begin
  5851. if taicpu(hp1).oper[0]^.typ = top_const then
  5852. begin
  5853. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5854. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5855. Result := True;
  5856. { Handle any overflows }
  5857. case taicpu(p).opsize of
  5858. S_B:
  5859. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5860. S_W:
  5861. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5862. S_L:
  5863. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5864. {$ifdef x86_64}
  5865. S_Q:
  5866. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5867. { Overflow; abort }
  5868. Result := False
  5869. else
  5870. taicpu(p).oper[0]^.val := ThisConst;
  5871. {$endif x86_64}
  5872. else
  5873. InternalError(2021102611);
  5874. end;
  5875. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5876. if Result then
  5877. begin
  5878. if (taicpu(p).oper[0]^.val < 0) and
  5879. (
  5880. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5881. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5882. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5883. ) then
  5884. begin
  5885. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5886. taicpu(p).opcode := A_SUB;
  5887. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5888. end
  5889. else
  5890. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5891. RemoveInstruction(hp1);
  5892. end;
  5893. end
  5894. else
  5895. begin
  5896. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5897. TransferUsedRegs(TmpUsedRegs);
  5898. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5899. hp2 := p;
  5900. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5901. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5902. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5903. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5904. begin
  5905. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5906. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5907. Asml.Remove(p);
  5908. Asml.InsertAfter(p, hp1);
  5909. p := hp1;
  5910. Result := True;
  5911. Exit;
  5912. end;
  5913. end;
  5914. end;
  5915. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5916. { * change "sub/add const1, reg" or "dec reg" followed by
  5917. "sub const2, reg" to one "sub ..., reg" }
  5918. {$ifdef i386}
  5919. if (taicpu(p).oper[0]^.val = 2) and
  5920. (ActiveReg = NR_ESP) and
  5921. { Don't do the sub/push optimization if the sub }
  5922. { comes from setting up the stack frame (JM) }
  5923. (not(GetLastInstruction(p,hp1)) or
  5924. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5925. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5926. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5927. begin
  5928. hp1 := tai(p.next);
  5929. while Assigned(hp1) and
  5930. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5931. not RegReadByInstruction(NR_ESP,hp1) and
  5932. not RegModifiedByInstruction(NR_ESP,hp1) do
  5933. hp1 := tai(hp1.next);
  5934. if Assigned(hp1) and
  5935. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5936. begin
  5937. taicpu(hp1).changeopsize(S_L);
  5938. if taicpu(hp1).oper[0]^.typ=top_reg then
  5939. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5940. hp1 := tai(p.next);
  5941. RemoveCurrentp(p, hp1);
  5942. Result:=true;
  5943. exit;
  5944. end;
  5945. end;
  5946. {$endif i386}
  5947. if DoArithCombineOpt(p) then
  5948. Result:=true;
  5949. end;
  5950. end;
  5951. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5952. var
  5953. TmpBool1,TmpBool2 : Boolean;
  5954. tmpref : treference;
  5955. hp1,hp2: tai;
  5956. mask, shiftval: tcgint;
  5957. begin
  5958. Result:=false;
  5959. { All these optimisations work on "shl/sal const,%reg" }
  5960. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5961. Exit;
  5962. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5963. (taicpu(p).oper[0]^.val <= 3) then
  5964. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5965. begin
  5966. { should we check the next instruction? }
  5967. TmpBool1 := True;
  5968. { have we found an add/sub which could be
  5969. integrated in the lea? }
  5970. TmpBool2 := False;
  5971. reference_reset(tmpref,2,[]);
  5972. TmpRef.index := taicpu(p).oper[1]^.reg;
  5973. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5974. while TmpBool1 and
  5975. GetNextInstruction(p, hp1) and
  5976. (tai(hp1).typ = ait_instruction) and
  5977. ((((taicpu(hp1).opcode = A_ADD) or
  5978. (taicpu(hp1).opcode = A_SUB)) and
  5979. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5980. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5981. (((taicpu(hp1).opcode = A_INC) or
  5982. (taicpu(hp1).opcode = A_DEC)) and
  5983. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5984. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5985. ((taicpu(hp1).opcode = A_LEA) and
  5986. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5987. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5988. (not GetNextInstruction(hp1,hp2) or
  5989. not instrReadsFlags(hp2)) Do
  5990. begin
  5991. TmpBool1 := False;
  5992. if taicpu(hp1).opcode=A_LEA then
  5993. begin
  5994. if (TmpRef.base = NR_NO) and
  5995. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5996. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5997. { Segment register isn't a concern here }
  5998. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5999. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6000. begin
  6001. TmpBool1 := True;
  6002. TmpBool2 := True;
  6003. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6004. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6005. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6006. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6007. RemoveInstruction(hp1);
  6008. end
  6009. end
  6010. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6011. begin
  6012. TmpBool1 := True;
  6013. TmpBool2 := True;
  6014. case taicpu(hp1).opcode of
  6015. A_ADD:
  6016. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6017. A_SUB:
  6018. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6019. else
  6020. internalerror(2019050536);
  6021. end;
  6022. RemoveInstruction(hp1);
  6023. end
  6024. else
  6025. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6026. (((taicpu(hp1).opcode = A_ADD) and
  6027. (TmpRef.base = NR_NO)) or
  6028. (taicpu(hp1).opcode = A_INC) or
  6029. (taicpu(hp1).opcode = A_DEC)) then
  6030. begin
  6031. TmpBool1 := True;
  6032. TmpBool2 := True;
  6033. case taicpu(hp1).opcode of
  6034. A_ADD:
  6035. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6036. A_INC:
  6037. inc(TmpRef.offset);
  6038. A_DEC:
  6039. dec(TmpRef.offset);
  6040. else
  6041. internalerror(2019050535);
  6042. end;
  6043. RemoveInstruction(hp1);
  6044. end;
  6045. end;
  6046. if TmpBool2
  6047. {$ifndef x86_64}
  6048. or
  6049. ((current_settings.optimizecputype < cpu_Pentium2) and
  6050. (taicpu(p).oper[0]^.val <= 3) and
  6051. not(cs_opt_size in current_settings.optimizerswitches))
  6052. {$endif x86_64}
  6053. then
  6054. begin
  6055. if not(TmpBool2) and
  6056. (taicpu(p).oper[0]^.val=1) then
  6057. begin
  6058. taicpu(p).opcode := A_ADD;
  6059. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6060. end
  6061. else
  6062. begin
  6063. taicpu(p).opcode := A_LEA;
  6064. taicpu(p).loadref(0, TmpRef);
  6065. end;
  6066. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6067. Result := True;
  6068. end;
  6069. end
  6070. {$ifndef x86_64}
  6071. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6072. begin
  6073. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6074. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6075. (unlike shl, which is only Tairable in the U pipe) }
  6076. if taicpu(p).oper[0]^.val=1 then
  6077. begin
  6078. taicpu(p).opcode := A_ADD;
  6079. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6080. Result := True;
  6081. end
  6082. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6083. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6084. else if (taicpu(p).opsize = S_L) and
  6085. (taicpu(p).oper[0]^.val<= 3) then
  6086. begin
  6087. reference_reset(tmpref,2,[]);
  6088. TmpRef.index := taicpu(p).oper[1]^.reg;
  6089. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6090. taicpu(p).opcode := A_LEA;
  6091. taicpu(p).loadref(0, TmpRef);
  6092. Result := True;
  6093. end;
  6094. end
  6095. {$endif x86_64}
  6096. else if
  6097. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6098. (
  6099. (
  6100. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6101. SetAndTest(hp1, hp2)
  6102. {$ifdef x86_64}
  6103. ) or
  6104. (
  6105. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6106. GetNextInstruction(hp1, hp2) and
  6107. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6108. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6109. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6110. {$endif x86_64}
  6111. )
  6112. ) and
  6113. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6114. begin
  6115. { Change:
  6116. shl x, %reg1
  6117. mov -(1<<x), %reg2
  6118. and %reg2, %reg1
  6119. Or:
  6120. shl x, %reg1
  6121. and -(1<<x), %reg1
  6122. To just:
  6123. shl x, %reg1
  6124. Since the and operation only zeroes bits that are already zero from the shl operation
  6125. }
  6126. case taicpu(p).oper[0]^.val of
  6127. 8:
  6128. mask:=$FFFFFFFFFFFFFF00;
  6129. 16:
  6130. mask:=$FFFFFFFFFFFF0000;
  6131. 32:
  6132. mask:=$FFFFFFFF00000000;
  6133. 63:
  6134. { Constant pre-calculated to prevent overflow errors with Int64 }
  6135. mask:=$8000000000000000;
  6136. else
  6137. begin
  6138. if taicpu(p).oper[0]^.val >= 64 then
  6139. { Shouldn't happen realistically, since the register
  6140. is guaranteed to be set to zero at this point }
  6141. mask := 0
  6142. else
  6143. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6144. end;
  6145. end;
  6146. if taicpu(hp1).oper[0]^.val = mask then
  6147. begin
  6148. { Everything checks out, perform the optimisation, as long as
  6149. the FLAGS register isn't being used}
  6150. TransferUsedRegs(TmpUsedRegs);
  6151. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6152. {$ifdef x86_64}
  6153. if (hp1 <> hp2) then
  6154. begin
  6155. { "shl/mov/and" version }
  6156. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6157. { Don't do the optimisation if the FLAGS register is in use }
  6158. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6159. begin
  6160. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6161. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6162. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6163. begin
  6164. RemoveInstruction(hp1);
  6165. Result := True;
  6166. end;
  6167. { Only set Result to True if the 'mov' instruction was removed }
  6168. RemoveInstruction(hp2);
  6169. end;
  6170. end
  6171. else
  6172. {$endif x86_64}
  6173. begin
  6174. { "shl/and" version }
  6175. { Don't do the optimisation if the FLAGS register is in use }
  6176. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6177. begin
  6178. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6179. RemoveInstruction(hp1);
  6180. Result := True;
  6181. end;
  6182. end;
  6183. Exit;
  6184. end
  6185. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6186. begin
  6187. { Even if the mask doesn't allow for its removal, we might be
  6188. able to optimise the mask for the "shl/and" version, which
  6189. may permit other peephole optimisations }
  6190. {$ifdef DEBUG_AOPTCPU}
  6191. mask := taicpu(hp1).oper[0]^.val and mask;
  6192. if taicpu(hp1).oper[0]^.val <> mask then
  6193. begin
  6194. DebugMsg(
  6195. SPeepholeOptimization +
  6196. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6197. ' to $' + debug_tostr(mask) +
  6198. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6199. taicpu(hp1).oper[0]^.val := mask;
  6200. end;
  6201. {$else DEBUG_AOPTCPU}
  6202. { If debugging is off, just set the operand even if it's the same }
  6203. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6204. {$endif DEBUG_AOPTCPU}
  6205. end;
  6206. end;
  6207. {
  6208. change
  6209. shl/sal const,reg
  6210. <op> ...(...,reg,1),...
  6211. into
  6212. <op> ...(...,reg,1 shl const),...
  6213. if const in 1..3
  6214. }
  6215. if MatchOpType(taicpu(p), top_const, top_reg) and
  6216. (taicpu(p).oper[0]^.val in [1..3]) and
  6217. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6218. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6219. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6220. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6221. MatchOpType(taicpu(hp1),top_ref))
  6222. ) and
  6223. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6224. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6225. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6226. begin
  6227. TransferUsedRegs(TmpUsedRegs);
  6228. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6229. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6230. begin
  6231. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6232. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6233. RemoveCurrentP(p);
  6234. Result:=true;
  6235. exit;
  6236. end;
  6237. end;
  6238. if MatchOpType(taicpu(p), top_const, top_reg) and
  6239. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6240. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6241. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6242. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6243. begin
  6244. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6245. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6246. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6247. {$ifdef x86_64}
  6248. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6249. {$endif x86_64}
  6250. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6251. begin
  6252. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6253. taicpu(hp1).opcode:=A_MOV;
  6254. taicpu(hp1).oper[0]^.val:=0;
  6255. end
  6256. else
  6257. begin
  6258. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6259. taicpu(hp1).oper[0]^.val:=shiftval;
  6260. end;
  6261. RemoveCurrentP(p);
  6262. Result:=true;
  6263. exit;
  6264. end;
  6265. end;
  6266. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6267. begin
  6268. case shr_size of
  6269. S_B:
  6270. { No valid combinations }
  6271. Result := False;
  6272. S_W:
  6273. Result := (Shift >= 8) and (movz_size = S_BW);
  6274. S_L:
  6275. Result :=
  6276. (Shift >= 24) { Any opsize is valid for this shift } or
  6277. ((Shift >= 16) and (movz_size = S_WL));
  6278. {$ifdef x86_64}
  6279. S_Q:
  6280. Result :=
  6281. (Shift >= 56) { Any opsize is valid for this shift } or
  6282. ((Shift >= 48) and (movz_size = S_WL));
  6283. {$endif x86_64}
  6284. else
  6285. InternalError(2022081510);
  6286. end;
  6287. end;
  6288. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6289. var
  6290. hp1, hp2: tai;
  6291. Shift: TCGInt;
  6292. LimitSize: Topsize;
  6293. DoNotMerge: Boolean;
  6294. begin
  6295. Result := False;
  6296. { All these optimisations work on "shr const,%reg" }
  6297. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6298. Exit;
  6299. DoNotMerge := False;
  6300. Shift := taicpu(p).oper[0]^.val;
  6301. LimitSize := taicpu(p).opsize;
  6302. hp1 := p;
  6303. repeat
  6304. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6305. Exit;
  6306. case taicpu(hp1).opcode of
  6307. A_TEST, A_CMP, A_Jcc:
  6308. { Skip over conditional jumps and relevant comparisons }
  6309. Continue;
  6310. A_MOVZX:
  6311. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6312. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6313. begin
  6314. { Since the original register is being read as is, subsequent
  6315. SHRs must not be merged at this point }
  6316. DoNotMerge := True;
  6317. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6318. begin
  6319. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6320. begin
  6321. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6322. taicpu(hp1).opcode := A_MOV;
  6323. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6324. case taicpu(hp1).opsize of
  6325. S_BW:
  6326. taicpu(hp1).opsize := S_W;
  6327. S_BL, S_WL:
  6328. taicpu(hp1).opsize := S_L;
  6329. else
  6330. InternalError(2022081503);
  6331. end;
  6332. { p itself hasn't changed, so no need to set Result to True }
  6333. Include(OptsToCheck, aoc_ForceNewIteration);
  6334. { See if there's anything afterwards that can be
  6335. optimised, since the input register hasn't changed }
  6336. Continue;
  6337. end;
  6338. { NOTE: If the MOVZX instruction reads and writes the same
  6339. register, defer this to the post-peephole optimisation stage }
  6340. Exit;
  6341. end;
  6342. end;
  6343. A_SHL, A_SAL, A_SHR:
  6344. if (taicpu(hp1).opsize <= LimitSize) and
  6345. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6346. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6347. begin
  6348. { Make sure the sizes don't exceed the register size limit
  6349. (measured by the shift value falling below the limit) }
  6350. if taicpu(hp1).opsize < LimitSize then
  6351. LimitSize := taicpu(hp1).opsize;
  6352. if taicpu(hp1).opcode = A_SHR then
  6353. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6354. else
  6355. begin
  6356. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6357. DoNotMerge := True;
  6358. end;
  6359. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6360. Exit;
  6361. { Since we've established that the combined shift is within
  6362. limits, we can actually combine the adjacent SHR
  6363. instructions even if they're different sizes }
  6364. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6365. begin
  6366. hp2 := tai(hp1.Previous);
  6367. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6368. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6369. RemoveInstruction(hp1);
  6370. hp1 := hp2;
  6371. { Though p has changed, only the constant has, and its
  6372. effects can still be detected on the next iteration of
  6373. the repeat..until loop }
  6374. Include(OptsToCheck, aoc_ForceNewIteration);
  6375. end;
  6376. { Move onto the next instruction }
  6377. Continue;
  6378. end;
  6379. else
  6380. ;
  6381. end;
  6382. Break;
  6383. until False;
  6384. end;
  6385. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6386. var
  6387. CurrentRef: TReference;
  6388. FullReg: TRegister;
  6389. hp1, hp2: tai;
  6390. begin
  6391. Result := False;
  6392. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6393. Exit;
  6394. { We assume you've checked if the operand is actually a reference by
  6395. this point. If it isn't, you'll most likely get an access violation }
  6396. CurrentRef := first_mov.oper[1]^.ref^;
  6397. { Memory must be aligned }
  6398. if (CurrentRef.offset mod 4) <> 0 then
  6399. Exit;
  6400. Inc(CurrentRef.offset);
  6401. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6402. if MatchOperand(second_mov.oper[0]^, 0) and
  6403. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6404. GetNextInstruction(second_mov, hp1) and
  6405. (hp1.typ = ait_instruction) and
  6406. (taicpu(hp1).opcode = A_MOV) and
  6407. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6408. (taicpu(hp1).oper[0]^.val = 0) then
  6409. begin
  6410. Inc(CurrentRef.offset);
  6411. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6412. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6413. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6414. begin
  6415. case taicpu(hp1).opsize of
  6416. S_B:
  6417. if GetNextInstruction(hp1, hp2) and
  6418. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6419. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6420. (taicpu(hp2).oper[0]^.val = 0) then
  6421. begin
  6422. Inc(CurrentRef.offset);
  6423. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6424. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6425. (taicpu(hp2).opsize = S_B) then
  6426. begin
  6427. RemoveInstruction(hp1);
  6428. RemoveInstruction(hp2);
  6429. first_mov.opsize := S_L;
  6430. if first_mov.oper[0]^.typ = top_reg then
  6431. begin
  6432. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6433. { Reuse second_mov as a MOVZX instruction }
  6434. second_mov.opcode := A_MOVZX;
  6435. second_mov.opsize := S_BL;
  6436. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6437. second_mov.loadreg(1, FullReg);
  6438. first_mov.oper[0]^.reg := FullReg;
  6439. asml.Remove(second_mov);
  6440. asml.InsertBefore(second_mov, first_mov);
  6441. end
  6442. else
  6443. { It's a value }
  6444. begin
  6445. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6446. RemoveInstruction(second_mov);
  6447. end;
  6448. Result := True;
  6449. Exit;
  6450. end;
  6451. end;
  6452. S_W:
  6453. begin
  6454. RemoveInstruction(hp1);
  6455. first_mov.opsize := S_L;
  6456. if first_mov.oper[0]^.typ = top_reg then
  6457. begin
  6458. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6459. { Reuse second_mov as a MOVZX instruction }
  6460. second_mov.opcode := A_MOVZX;
  6461. second_mov.opsize := S_BL;
  6462. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6463. second_mov.loadreg(1, FullReg);
  6464. first_mov.oper[0]^.reg := FullReg;
  6465. asml.Remove(second_mov);
  6466. asml.InsertBefore(second_mov, first_mov);
  6467. end
  6468. else
  6469. { It's a value }
  6470. begin
  6471. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6472. RemoveInstruction(second_mov);
  6473. end;
  6474. Result := True;
  6475. Exit;
  6476. end;
  6477. else
  6478. ;
  6479. end;
  6480. end;
  6481. end;
  6482. end;
  6483. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6484. { returns true if a "continue" should be done after this optimization }
  6485. var
  6486. hp1, hp2, hp3: tai;
  6487. begin
  6488. Result := false;
  6489. hp3 := nil;
  6490. if MatchOpType(taicpu(p),top_ref) and
  6491. GetNextInstruction(p, hp1) and
  6492. (hp1.typ = ait_instruction) and
  6493. (((taicpu(hp1).opcode = A_FLD) and
  6494. (taicpu(p).opcode = A_FSTP)) or
  6495. ((taicpu(p).opcode = A_FISTP) and
  6496. (taicpu(hp1).opcode = A_FILD))) and
  6497. MatchOpType(taicpu(hp1),top_ref) and
  6498. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6499. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6500. begin
  6501. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6502. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6503. GetNextInstruction(hp1, hp2) and
  6504. (((hp2.typ = ait_instruction) and
  6505. IsExitCode(hp2) and
  6506. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6507. not(assigned(current_procinfo.procdef.funcretsym) and
  6508. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6509. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6510. { fstp <temp>
  6511. fld <temp>
  6512. <dealloc> <temp>
  6513. }
  6514. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6515. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6516. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6517. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6518. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6519. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6520. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6521. )
  6522. )
  6523. ) then
  6524. begin
  6525. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6526. RemoveInstruction(hp1);
  6527. RemoveCurrentP(p, hp2);
  6528. { first case: exit code }
  6529. if hp2.typ = ait_instruction then
  6530. RemoveLastDeallocForFuncRes(p);
  6531. Result := true;
  6532. end
  6533. else
  6534. { we can do this only in fast math mode as fstp is rounding ...
  6535. ... still disabled as it breaks the compiler and/or rtl }
  6536. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6537. { ... or if another fstp equal to the first one follows }
  6538. GetNextInstruction(hp1,hp2) and
  6539. (hp2.typ = ait_instruction) and
  6540. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6541. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6542. begin
  6543. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6544. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6545. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6546. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6547. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6548. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6549. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6550. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6551. ) then
  6552. begin
  6553. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6554. RemoveCurrentP(p,hp2);
  6555. RemoveInstruction(hp1);
  6556. Result := true;
  6557. end
  6558. else if { fst can't store an extended/comp value }
  6559. (taicpu(p).opsize <> S_FX) and
  6560. (taicpu(p).opsize <> S_IQ) then
  6561. begin
  6562. if (taicpu(p).opcode = A_FSTP) then
  6563. taicpu(p).opcode := A_FST
  6564. else
  6565. taicpu(p).opcode := A_FIST;
  6566. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6567. RemoveInstruction(hp1);
  6568. Result := true;
  6569. end;
  6570. end;
  6571. end;
  6572. end;
  6573. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6574. var
  6575. hp1, hp2, hp3: tai;
  6576. begin
  6577. result:=false;
  6578. if MatchOpType(taicpu(p),top_reg) and
  6579. GetNextInstruction(p, hp1) and
  6580. (hp1.typ = Ait_Instruction) and
  6581. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6582. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6583. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6584. { change to
  6585. fld reg fxxx reg,st
  6586. fxxxp st, st1 (hp1)
  6587. Remark: non commutative operations must be reversed!
  6588. }
  6589. begin
  6590. case taicpu(hp1).opcode Of
  6591. A_FMULP,A_FADDP,
  6592. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6593. begin
  6594. case taicpu(hp1).opcode Of
  6595. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6596. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6597. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6598. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6599. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6600. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6601. else
  6602. internalerror(2019050534);
  6603. end;
  6604. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6605. taicpu(hp1).oper[1]^.reg := NR_ST;
  6606. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6607. RemoveCurrentP(p, hp1);
  6608. Result:=true;
  6609. exit;
  6610. end;
  6611. else
  6612. ;
  6613. end;
  6614. end
  6615. else
  6616. if MatchOpType(taicpu(p),top_ref) and
  6617. GetNextInstruction(p, hp2) and
  6618. (hp2.typ = Ait_Instruction) and
  6619. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6620. (taicpu(p).opsize in [S_FS, S_FL]) and
  6621. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6622. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6623. if GetLastInstruction(p, hp1) and
  6624. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6625. MatchOpType(taicpu(hp1),top_ref) and
  6626. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6627. if ((taicpu(hp2).opcode = A_FMULP) or
  6628. (taicpu(hp2).opcode = A_FADDP)) then
  6629. { change to
  6630. fld/fst mem1 (hp1) fld/fst mem1
  6631. fld mem1 (p) fadd/
  6632. faddp/ fmul st, st
  6633. fmulp st, st1 (hp2) }
  6634. begin
  6635. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6636. RemoveCurrentP(p, hp1);
  6637. if (taicpu(hp2).opcode = A_FADDP) then
  6638. taicpu(hp2).opcode := A_FADD
  6639. else
  6640. taicpu(hp2).opcode := A_FMUL;
  6641. taicpu(hp2).oper[1]^.reg := NR_ST;
  6642. end
  6643. else
  6644. { change to
  6645. fld/fst mem1 (hp1) fld/fst mem1
  6646. fld mem1 (p) fld st
  6647. }
  6648. begin
  6649. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6650. taicpu(p).changeopsize(S_FL);
  6651. taicpu(p).loadreg(0,NR_ST);
  6652. end
  6653. else
  6654. begin
  6655. case taicpu(hp2).opcode Of
  6656. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6657. { change to
  6658. fld/fst mem1 (hp1) fld/fst mem1
  6659. fld mem2 (p) fxxx mem2
  6660. fxxxp st, st1 (hp2) }
  6661. begin
  6662. case taicpu(hp2).opcode Of
  6663. A_FADDP: taicpu(p).opcode := A_FADD;
  6664. A_FMULP: taicpu(p).opcode := A_FMUL;
  6665. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6666. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6667. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6668. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6669. else
  6670. internalerror(2019050533);
  6671. end;
  6672. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6673. RemoveInstruction(hp2);
  6674. end
  6675. else
  6676. ;
  6677. end
  6678. end
  6679. end;
  6680. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6681. begin
  6682. Result := condition_in(cond1, cond2) or
  6683. { Not strictly subsets due to the actual flags checked, but because we're
  6684. comparing integers, E is a subset of AE and GE and their aliases }
  6685. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6686. end;
  6687. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6688. var
  6689. v: TCGInt;
  6690. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6691. FirstMatch, TempBool: Boolean;
  6692. NewReg: TRegister;
  6693. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6694. begin
  6695. Result:=false;
  6696. { All these optimisations need a next instruction }
  6697. if not GetNextInstruction(p, hp1) then
  6698. Exit;
  6699. { Search for:
  6700. cmp ###,###
  6701. j(c1) @lbl1
  6702. ...
  6703. @lbl:
  6704. cmp ###,### (same comparison as above)
  6705. j(c2) @lbl2
  6706. If c1 is a subset of c2, change to:
  6707. cmp ###,###
  6708. j(c1) @lbl2
  6709. (@lbl1 may become a dead label as a result)
  6710. }
  6711. { Also handle cases where there are multiple jumps in a row }
  6712. p_jump := hp1;
  6713. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6714. begin
  6715. if IsJumpToLabel(taicpu(p_jump)) then
  6716. begin
  6717. { Do jump optimisations first in case the condition becomes
  6718. unnecessary }
  6719. TempBool := True;
  6720. if DoJumpOptimizations(p_jump, TempBool) or
  6721. not TempBool then
  6722. begin
  6723. if Assigned(p_jump) then
  6724. begin
  6725. hp1 := p_jump;
  6726. if (p_jump.typ in [ait_align]) then
  6727. SkipAligns(p_jump, p_jump);
  6728. { CollapseZeroDistJump will be set to the label after the
  6729. jump if it optimises, whether or not it's live or dead }
  6730. if (p_jump.typ in [ait_label]) and
  6731. not (tai_label(p_jump).labsym.is_used) then
  6732. GetNextInstruction(p_jump, p_jump);
  6733. end;
  6734. TransferUsedRegs(TmpUsedRegs);
  6735. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6736. if not Assigned(p_jump) or
  6737. (
  6738. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  6739. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  6740. ) then
  6741. begin
  6742. { No more conditional jumps; conditional statement is no longer required }
  6743. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  6744. RemoveCurrentP(p);
  6745. Result := True;
  6746. Exit;
  6747. end;
  6748. hp1 := p_jump;
  6749. Include(OptsToCheck, aoc_ForceNewIteration);
  6750. Continue;
  6751. end;
  6752. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6753. if GetNextInstruction(p_jump, hp2) and
  6754. (
  6755. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  6756. not TempBool
  6757. ) then
  6758. begin
  6759. hp1 := p_jump;
  6760. Include(OptsToCheck, aoc_ForceNewIteration);
  6761. Continue;
  6762. end;
  6763. p_label := nil;
  6764. if Assigned(JumpLabel) then
  6765. p_label := getlabelwithsym(JumpLabel);
  6766. if Assigned(p_label) and
  6767. GetNextInstruction(p_label, p_dist) and
  6768. MatchInstruction(p_dist, A_CMP, []) and
  6769. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6770. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6771. GetNextInstruction(p_dist, hp1_dist) and
  6772. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6773. begin
  6774. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6775. if JumpLabel = JumpLabel_dist then
  6776. { This is an infinite loop }
  6777. Exit;
  6778. { Best optimisation when the first condition is a subset (or equal) of the second }
  6779. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6780. begin
  6781. { Any registers used here will already be allocated }
  6782. if Assigned(JumpLabel) then
  6783. JumpLabel.DecRefs;
  6784. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6785. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6786. Result := True;
  6787. { Don't exit yet. Since p and p_jump haven't actually been
  6788. removed, we can check for more on this iteration }
  6789. end
  6790. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6791. GetNextInstruction(hp1_dist, hp1_label) and
  6792. SkipAligns(hp1_label, hp1_label) and
  6793. (hp1_label.typ = ait_label) then
  6794. begin
  6795. JumpLabel_far := tai_label(hp1_label).labsym;
  6796. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6797. { This is an infinite loop }
  6798. Exit;
  6799. if Assigned(JumpLabel_far) then
  6800. begin
  6801. { In this situation, if the first jump branches, the second one will never,
  6802. branch so change the destination label to after the second jump }
  6803. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6804. if Assigned(JumpLabel) then
  6805. JumpLabel.DecRefs;
  6806. JumpLabel_far.IncRefs;
  6807. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6808. Result := True;
  6809. { Don't exit yet. Since p and p_jump haven't actually been
  6810. removed, we can check for more on this iteration }
  6811. Continue;
  6812. end;
  6813. end;
  6814. end;
  6815. end;
  6816. { Search for:
  6817. cmp ###,###
  6818. j(c1) @lbl1
  6819. cmp ###,### (same as first)
  6820. Remove second cmp
  6821. }
  6822. if GetNextInstruction(p_jump, hp2) and
  6823. (
  6824. (
  6825. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6826. (
  6827. (
  6828. MatchOpType(taicpu(p), top_const, top_reg) and
  6829. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6830. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6831. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6832. ) or (
  6833. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6834. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6835. )
  6836. )
  6837. ) or (
  6838. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6839. MatchOperand(taicpu(p).oper[0]^, 0) and
  6840. (taicpu(p).oper[1]^.typ = top_reg) and
  6841. MatchInstruction(hp2, A_TEST, []) and
  6842. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6843. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6844. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6845. )
  6846. ) then
  6847. begin
  6848. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6849. RemoveInstruction(hp2);
  6850. Result := True;
  6851. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6852. end;
  6853. GetNextInstruction(p_jump, p_jump);
  6854. end;
  6855. if (
  6856. { Don't call GetNextInstruction again if we already have it }
  6857. (hp1 = p_jump) or
  6858. GetNextInstruction(p, hp1)
  6859. ) and
  6860. MatchInstruction(hp1, A_Jcc, []) and
  6861. IsJumpToLabel(taicpu(hp1)) and
  6862. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  6863. GetNextInstruction(hp1, hp2) then
  6864. begin
  6865. {
  6866. cmp x, y (or "cmp y, x")
  6867. je @lbl
  6868. mov x, y
  6869. @lbl:
  6870. (x and y can be constants, registers or references)
  6871. Change to:
  6872. mov x, y (x and y will always be equal in the end)
  6873. @lbl: (may beceome a dead label)
  6874. Also:
  6875. cmp x, y (or "cmp y, x")
  6876. jne @lbl
  6877. mov x, y
  6878. @lbl:
  6879. (x and y can be constants, registers or references)
  6880. Change to:
  6881. Absolutely nothing! (Except @lbl if it's still live)
  6882. }
  6883. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  6884. (
  6885. (
  6886. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  6887. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  6888. ) or (
  6889. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  6890. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  6891. )
  6892. ) and
  6893. GetNextInstruction(hp2, hp1_label) and
  6894. SkipAligns(hp1_label, hp1_label) and
  6895. (hp1_label.typ = ait_label) and
  6896. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  6897. begin
  6898. tai_label(hp1_label).labsym.DecRefs;
  6899. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  6900. begin
  6901. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  6902. RemoveInstruction(hp2);
  6903. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  6904. end
  6905. else
  6906. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  6907. RemoveInstruction(hp1);
  6908. RemoveCurrentp(p, hp2);
  6909. Result := True;
  6910. Exit;
  6911. end;
  6912. {
  6913. Try to optimise the following:
  6914. cmp $x,### ($x and $y can be registers or constants)
  6915. je @lbl1 (only reference)
  6916. cmp $y,### (### are identical)
  6917. @Lbl:
  6918. sete %reg1
  6919. Change to:
  6920. cmp $x,###
  6921. sete %reg2 (allocate new %reg2)
  6922. cmp $y,###
  6923. sete %reg1
  6924. orb %reg2,%reg1
  6925. (dealloc %reg2)
  6926. This adds an instruction (so don't perform under -Os), but it removes
  6927. a conditional branch.
  6928. }
  6929. if not (cs_opt_size in current_settings.optimizerswitches) and
  6930. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6931. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6932. { The first operand of CMP instructions can only be a register or
  6933. immediate anyway, so no need to check }
  6934. GetNextInstruction(hp2, p_label) and
  6935. (p_label.typ = ait_label) and
  6936. (tai_label(p_label).labsym.getrefs = 1) and
  6937. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6938. GetNextInstruction(p_label, p_dist) and
  6939. MatchInstruction(p_dist, A_SETcc, []) and
  6940. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6941. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  6942. begin
  6943. TransferUsedRegs(TmpUsedRegs);
  6944. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6945. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6946. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6947. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6948. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  6949. { Get the instruction after the SETcc instruction so we can
  6950. allocate a new register over the entire range }
  6951. GetNextInstruction(p_dist, hp1_dist) then
  6952. begin
  6953. { Register can appear in p if it's not used afterwards, so only
  6954. allocate between hp1 and hp1_dist }
  6955. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  6956. if NewReg <> NR_NO then
  6957. begin
  6958. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6959. { Change the jump instruction into a SETcc instruction }
  6960. taicpu(hp1).opcode := A_SETcc;
  6961. taicpu(hp1).opsize := S_B;
  6962. taicpu(hp1).loadreg(0, NewReg);
  6963. { This is now a dead label }
  6964. tai_label(p_label).labsym.decrefs;
  6965. { Prefer adding before the next instruction so the FLAGS
  6966. register is deallicated first }
  6967. AsmL.InsertBefore(
  6968. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  6969. hp1_dist
  6970. );
  6971. Result := True;
  6972. { Don't exit yet, as p wasn't changed and hp1, while
  6973. modified, is still intact and might be optimised by the
  6974. SETcc optimisation below }
  6975. end;
  6976. end;
  6977. end;
  6978. end;
  6979. if taicpu(p).oper[0]^.typ = top_const then
  6980. begin
  6981. if (taicpu(p).oper[0]^.val = 0) and
  6982. (taicpu(p).oper[1]^.typ = top_reg) and
  6983. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6984. begin
  6985. hp2 := p;
  6986. FirstMatch := True;
  6987. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6988. anything meaningful once it's converted to "test %reg,%reg";
  6989. additionally, some jumps will always (or never) branch, so
  6990. evaluate every jump immediately following the
  6991. comparison, optimising the conditions if possible.
  6992. Similarly with SETcc... those that are always set to 0 or 1
  6993. are changed to MOV instructions }
  6994. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6995. (
  6996. GetNextInstruction(hp2, hp1) and
  6997. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6998. ) do
  6999. begin
  7000. FirstMatch := False;
  7001. case taicpu(hp1).condition of
  7002. C_B, C_C, C_NAE, C_O:
  7003. { For B/NAE:
  7004. Will never branch since an unsigned integer can never be below zero
  7005. For C/O:
  7006. Result cannot overflow because 0 is being subtracted
  7007. }
  7008. begin
  7009. if taicpu(hp1).opcode = A_Jcc then
  7010. begin
  7011. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7012. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7013. RemoveInstruction(hp1);
  7014. { Since hp1 was deleted, hp2 must not be updated }
  7015. Continue;
  7016. end
  7017. else
  7018. begin
  7019. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7020. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7021. taicpu(hp1).opcode := A_MOV;
  7022. taicpu(hp1).ops := 2;
  7023. taicpu(hp1).condition := C_None;
  7024. taicpu(hp1).opsize := S_B;
  7025. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7026. taicpu(hp1).loadconst(0, 0);
  7027. end;
  7028. end;
  7029. C_BE, C_NA:
  7030. begin
  7031. { Will only branch if equal to zero }
  7032. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7033. taicpu(hp1).condition := C_E;
  7034. end;
  7035. C_A, C_NBE:
  7036. begin
  7037. { Will only branch if not equal to zero }
  7038. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7039. taicpu(hp1).condition := C_NE;
  7040. end;
  7041. C_AE, C_NB, C_NC, C_NO:
  7042. begin
  7043. { Will always branch }
  7044. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7045. if taicpu(hp1).opcode = A_Jcc then
  7046. begin
  7047. MakeUnconditional(taicpu(hp1));
  7048. { Any jumps/set that follow will now be dead code }
  7049. RemoveDeadCodeAfterJump(taicpu(hp1));
  7050. Break;
  7051. end
  7052. else
  7053. begin
  7054. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7055. taicpu(hp1).opcode := A_MOV;
  7056. taicpu(hp1).ops := 2;
  7057. taicpu(hp1).condition := C_None;
  7058. taicpu(hp1).opsize := S_B;
  7059. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7060. taicpu(hp1).loadconst(0, 1);
  7061. end;
  7062. end;
  7063. C_None:
  7064. InternalError(2020012201);
  7065. C_P, C_PE, C_NP, C_PO:
  7066. { We can't handle parity checks and they should never be generated
  7067. after a general-purpose CMP (it's used in some floating-point
  7068. comparisons that don't use CMP) }
  7069. InternalError(2020012202);
  7070. else
  7071. { Zero/Equality, Sign, their complements and all of the
  7072. signed comparisons do not need to be converted };
  7073. end;
  7074. hp2 := hp1;
  7075. end;
  7076. { Convert the instruction to a TEST }
  7077. taicpu(p).opcode := A_TEST;
  7078. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7079. Result := True;
  7080. Exit;
  7081. end
  7082. else if (taicpu(p).oper[0]^.val = 1) and
  7083. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7084. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7085. begin
  7086. { Convert; To:
  7087. cmp $1,r/m cmp $0,r/m
  7088. jl @lbl jle @lbl
  7089. (Also do inverted conditions)
  7090. }
  7091. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7092. taicpu(p).oper[0]^.val := 0;
  7093. if taicpu(hp1).condition in [C_L, C_NGE] then
  7094. taicpu(hp1).condition := C_LE
  7095. else
  7096. taicpu(hp1).condition := C_NLE;
  7097. { If the instruction is now "cmp $0,%reg", convert it to a
  7098. TEST (and effectively do the work of the "cmp $0,%reg" in
  7099. the block above)
  7100. }
  7101. if (taicpu(p).oper[1]^.typ = top_reg) then
  7102. begin
  7103. taicpu(p).opcode := A_TEST;
  7104. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7105. end;
  7106. Result := True;
  7107. Exit;
  7108. end
  7109. else if (taicpu(p).oper[1]^.typ = top_reg)
  7110. {$ifdef x86_64}
  7111. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7112. {$endif x86_64}
  7113. then
  7114. begin
  7115. { cmp register,$8000 neg register
  7116. je target --> jo target
  7117. .... only if register is deallocated before jump.}
  7118. case Taicpu(p).opsize of
  7119. S_B: v:=$80;
  7120. S_W: v:=$8000;
  7121. S_L: v:=qword($80000000);
  7122. else
  7123. internalerror(2013112905);
  7124. end;
  7125. if (taicpu(p).oper[0]^.val=v) and
  7126. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7127. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7128. begin
  7129. TransferUsedRegs(TmpUsedRegs);
  7130. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7131. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7132. begin
  7133. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7134. Taicpu(p).opcode:=A_NEG;
  7135. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7136. Taicpu(p).clearop(1);
  7137. Taicpu(p).ops:=1;
  7138. if Taicpu(hp1).condition=C_E then
  7139. Taicpu(hp1).condition:=C_O
  7140. else
  7141. Taicpu(hp1).condition:=C_NO;
  7142. Result:=true;
  7143. exit;
  7144. end;
  7145. end;
  7146. end;
  7147. end;
  7148. if TrySwapMovCmp(p, hp1) then
  7149. begin
  7150. Result := True;
  7151. Exit;
  7152. end;
  7153. end;
  7154. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7155. var
  7156. hp1: tai;
  7157. begin
  7158. {
  7159. remove the second (v)pxor from
  7160. pxor reg,reg
  7161. ...
  7162. pxor reg,reg
  7163. }
  7164. Result:=false;
  7165. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7166. MatchOpType(taicpu(p),top_reg,top_reg) and
  7167. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7168. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7169. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7170. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7171. begin
  7172. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7173. RemoveInstruction(hp1);
  7174. Result:=true;
  7175. Exit;
  7176. end
  7177. {
  7178. replace
  7179. pxor reg1,reg1
  7180. movapd/s reg1,reg2
  7181. dealloc reg1
  7182. by
  7183. pxor reg2,reg2
  7184. }
  7185. else if GetNextInstruction(p,hp1) and
  7186. { we mix single and double opperations here because we assume that the compiler
  7187. generates vmovapd only after double operations and vmovaps only after single operations }
  7188. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7189. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7190. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7191. (taicpu(p).oper[0]^.typ=top_reg) then
  7192. begin
  7193. TransferUsedRegs(TmpUsedRegs);
  7194. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7195. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7196. begin
  7197. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7198. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7199. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7200. RemoveInstruction(hp1);
  7201. result:=true;
  7202. end;
  7203. end;
  7204. end;
  7205. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7206. var
  7207. hp1: tai;
  7208. begin
  7209. {
  7210. remove the second (v)pxor from
  7211. (v)pxor reg,reg
  7212. ...
  7213. (v)pxor reg,reg
  7214. }
  7215. Result:=false;
  7216. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7217. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7218. begin
  7219. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7220. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7221. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7222. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7223. begin
  7224. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7225. RemoveInstruction(hp1);
  7226. Result:=true;
  7227. Exit;
  7228. end;
  7229. {$ifdef x86_64}
  7230. {
  7231. replace
  7232. vpxor reg1,reg1,reg1
  7233. vmov reg,mem
  7234. by
  7235. movq $0,mem
  7236. }
  7237. if GetNextInstruction(p,hp1) and
  7238. MatchInstruction(hp1,A_VMOVSD,[]) and
  7239. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7240. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7241. begin
  7242. TransferUsedRegs(TmpUsedRegs);
  7243. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7244. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7245. begin
  7246. taicpu(hp1).loadconst(0,0);
  7247. taicpu(hp1).opcode:=A_MOV;
  7248. taicpu(hp1).opsize:=S_Q;
  7249. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7250. RemoveCurrentP(p);
  7251. result:=true;
  7252. Exit;
  7253. end;
  7254. end;
  7255. {$endif x86_64}
  7256. end
  7257. {
  7258. replace
  7259. vpxor reg1,reg1,reg2
  7260. by
  7261. vpxor reg2,reg2,reg2
  7262. to avoid unncessary data dependencies
  7263. }
  7264. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7265. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7266. begin
  7267. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7268. { avoid unncessary data dependency }
  7269. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7270. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7271. result:=true;
  7272. exit;
  7273. end;
  7274. Result:=OptPass1VOP(p);
  7275. end;
  7276. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7277. var
  7278. hp1 : tai;
  7279. begin
  7280. result:=false;
  7281. { replace
  7282. IMul const,%mreg1,%mreg2
  7283. Mov %reg2,%mreg3
  7284. dealloc %mreg3
  7285. by
  7286. Imul const,%mreg1,%mreg23
  7287. }
  7288. if (taicpu(p).ops=3) and
  7289. GetNextInstruction(p,hp1) and
  7290. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7291. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7292. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7293. begin
  7294. TransferUsedRegs(TmpUsedRegs);
  7295. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7296. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7297. begin
  7298. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7299. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7300. RemoveInstruction(hp1);
  7301. result:=true;
  7302. end;
  7303. end;
  7304. end;
  7305. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7306. var
  7307. hp1 : tai;
  7308. begin
  7309. result:=false;
  7310. { replace
  7311. IMul %reg0,%reg1,%reg2
  7312. Mov %reg2,%reg3
  7313. dealloc %reg2
  7314. by
  7315. Imul %reg0,%reg1,%reg3
  7316. }
  7317. if GetNextInstruction(p,hp1) and
  7318. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7319. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7320. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7321. begin
  7322. TransferUsedRegs(TmpUsedRegs);
  7323. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7324. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7325. begin
  7326. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7327. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7328. RemoveInstruction(hp1);
  7329. result:=true;
  7330. end;
  7331. end;
  7332. end;
  7333. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7334. var
  7335. hp1: tai;
  7336. begin
  7337. Result:=false;
  7338. { get rid of
  7339. (v)cvtss2sd reg0,<reg1,>reg2
  7340. (v)cvtss2sd reg2,<reg2,>reg0
  7341. }
  7342. if GetNextInstruction(p,hp1) and
  7343. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7344. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7345. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7346. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7347. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7348. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7349. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7350. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7351. )
  7352. ) then
  7353. begin
  7354. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7355. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7356. begin
  7357. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7358. RemoveCurrentP(p);
  7359. RemoveInstruction(hp1);
  7360. end
  7361. else
  7362. begin
  7363. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7364. if taicpu(hp1).opcode=A_CVTSD2SS then
  7365. begin
  7366. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7367. taicpu(p).opcode:=A_MOVAPS;
  7368. end
  7369. else
  7370. begin
  7371. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7372. taicpu(p).opcode:=A_VMOVAPS;
  7373. end;
  7374. taicpu(p).ops:=2;
  7375. RemoveInstruction(hp1);
  7376. end;
  7377. Result:=true;
  7378. Exit;
  7379. end;
  7380. end;
  7381. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7382. var
  7383. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7384. ThisReg: TRegister;
  7385. begin
  7386. Result := False;
  7387. if not GetNextInstruction(p,hp1) then
  7388. Exit;
  7389. {
  7390. convert
  7391. j<c> .L1
  7392. mov 1,reg
  7393. jmp .L2
  7394. .L1
  7395. mov 0,reg
  7396. .L2
  7397. into
  7398. mov 0,reg
  7399. set<not(c)> reg
  7400. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7401. would destroy the flag contents
  7402. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7403. executed at the same time as a previous comparison.
  7404. set<not(c)> reg
  7405. movzx reg, reg
  7406. }
  7407. if MatchInstruction(hp1,A_MOV,[]) and
  7408. (taicpu(hp1).oper[0]^.typ = top_const) and
  7409. (
  7410. (
  7411. (taicpu(hp1).oper[1]^.typ = top_reg)
  7412. {$ifdef i386}
  7413. { Under i386, ESI, EDI, EBP and ESP
  7414. don't have an 8-bit representation }
  7415. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7416. {$endif i386}
  7417. ) or (
  7418. {$ifdef i386}
  7419. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7420. {$endif i386}
  7421. (taicpu(hp1).opsize = S_B)
  7422. )
  7423. ) and
  7424. GetNextInstruction(hp1,hp2) and
  7425. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7426. GetNextInstruction(hp2,hp3) and
  7427. SkipAligns(hp3, hp3) and
  7428. (hp3.typ=ait_label) and
  7429. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7430. GetNextInstruction(hp3,hp4) and
  7431. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7432. (taicpu(hp4).oper[0]^.typ = top_const) and
  7433. (
  7434. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7435. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7436. ) and
  7437. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7438. GetNextInstruction(hp4,hp5) and
  7439. SkipAligns(hp5, hp5) and
  7440. (hp5.typ=ait_label) and
  7441. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7442. begin
  7443. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7444. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7445. tai_label(hp3).labsym.DecRefs;
  7446. { If this isn't the only reference to the middle label, we can
  7447. still make a saving - only that the first jump and everything
  7448. that follows will remain. }
  7449. if (tai_label(hp3).labsym.getrefs = 0) then
  7450. begin
  7451. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7452. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7453. else
  7454. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7455. { remove jump, first label and second MOV (also catching any aligns) }
  7456. repeat
  7457. if not GetNextInstruction(hp2, hp3) then
  7458. InternalError(2021040810);
  7459. RemoveInstruction(hp2);
  7460. hp2 := hp3;
  7461. until hp2 = hp5;
  7462. { Don't decrement reference count before the removal loop
  7463. above, otherwise GetNextInstruction won't stop on the
  7464. the label }
  7465. tai_label(hp5).labsym.DecRefs;
  7466. end
  7467. else
  7468. begin
  7469. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7470. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7471. else
  7472. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7473. end;
  7474. taicpu(p).opcode:=A_SETcc;
  7475. taicpu(p).opsize:=S_B;
  7476. taicpu(p).is_jmp:=False;
  7477. if taicpu(hp1).opsize=S_B then
  7478. begin
  7479. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7480. if taicpu(hp1).oper[1]^.typ = top_reg then
  7481. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7482. RemoveInstruction(hp1);
  7483. end
  7484. else
  7485. begin
  7486. { Will be a register because the size can't be S_B otherwise }
  7487. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7488. taicpu(p).loadreg(0, ThisReg);
  7489. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7490. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7491. begin
  7492. case taicpu(hp1).opsize of
  7493. S_W:
  7494. taicpu(hp1).opsize := S_BW;
  7495. S_L:
  7496. taicpu(hp1).opsize := S_BL;
  7497. {$ifdef x86_64}
  7498. S_Q:
  7499. begin
  7500. taicpu(hp1).opsize := S_BL;
  7501. { Change the destination register to 32-bit }
  7502. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7503. end;
  7504. {$endif x86_64}
  7505. else
  7506. InternalError(2021040820);
  7507. end;
  7508. taicpu(hp1).opcode := A_MOVZX;
  7509. taicpu(hp1).loadreg(0, ThisReg);
  7510. end
  7511. else
  7512. begin
  7513. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7514. { hp1 is already a MOV instruction with the correct register }
  7515. taicpu(hp1).loadconst(0, 0);
  7516. { Inserting it right before p will guarantee that the flags are also tracked }
  7517. asml.Remove(hp1);
  7518. asml.InsertBefore(hp1, p);
  7519. end;
  7520. end;
  7521. Result:=true;
  7522. exit;
  7523. end
  7524. else if (hp1.typ = ait_label) then
  7525. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7526. end;
  7527. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7528. var
  7529. hp1, hp2, hp3: tai;
  7530. SourceRef, TargetRef: TReference;
  7531. CurrentReg: TRegister;
  7532. begin
  7533. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7534. if not UseAVX then
  7535. InternalError(2021100501);
  7536. Result := False;
  7537. { Look for the following to simplify:
  7538. vmovdqa/u x(mem1), %xmmreg
  7539. vmovdqa/u %xmmreg, y(mem2)
  7540. vmovdqa/u x+16(mem1), %xmmreg
  7541. vmovdqa/u %xmmreg, y+16(mem2)
  7542. Change to:
  7543. vmovdqa/u x(mem1), %ymmreg
  7544. vmovdqa/u %ymmreg, y(mem2)
  7545. vpxor %ymmreg, %ymmreg, %ymmreg
  7546. ( The VPXOR instruction is to zero the upper half, thus removing the
  7547. need to call the potentially expensive VZEROUPPER instruction. Other
  7548. peephole optimisations can remove VPXOR if it's unnecessary )
  7549. }
  7550. TransferUsedRegs(TmpUsedRegs);
  7551. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7552. { NOTE: In the optimisations below, if the references dictate that an
  7553. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7554. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7555. if (taicpu(p).opsize = S_XMM) and
  7556. MatchOpType(taicpu(p), top_ref, top_reg) and
  7557. GetNextInstruction(p, hp1) and
  7558. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7559. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7560. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7561. begin
  7562. SourceRef := taicpu(p).oper[0]^.ref^;
  7563. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7564. if GetNextInstruction(hp1, hp2) and
  7565. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7566. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7567. begin
  7568. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7569. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7570. Inc(SourceRef.offset, 16);
  7571. { Reuse the register in the first block move }
  7572. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7573. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7574. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7575. begin
  7576. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7577. Inc(TargetRef.offset, 16);
  7578. if GetNextInstruction(hp2, hp3) and
  7579. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7580. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7581. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7582. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7583. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7584. begin
  7585. { Update the register tracking to the new size }
  7586. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7587. { Remember that the offsets are 16 ahead }
  7588. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7589. if not (
  7590. ((SourceRef.offset mod 32) = 16) and
  7591. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7592. ) then
  7593. taicpu(p).opcode := A_VMOVDQU;
  7594. taicpu(p).opsize := S_YMM;
  7595. taicpu(p).oper[1]^.reg := CurrentReg;
  7596. if not (
  7597. ((TargetRef.offset mod 32) = 16) and
  7598. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7599. ) then
  7600. taicpu(hp1).opcode := A_VMOVDQU;
  7601. taicpu(hp1).opsize := S_YMM;
  7602. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7603. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7604. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7605. if (pi_uses_ymm in current_procinfo.flags) then
  7606. RemoveInstruction(hp2)
  7607. else
  7608. begin
  7609. taicpu(hp2).opcode := A_VPXOR;
  7610. taicpu(hp2).opsize := S_YMM;
  7611. taicpu(hp2).loadreg(0, CurrentReg);
  7612. taicpu(hp2).loadreg(1, CurrentReg);
  7613. taicpu(hp2).loadreg(2, CurrentReg);
  7614. taicpu(hp2).ops := 3;
  7615. end;
  7616. RemoveInstruction(hp3);
  7617. Result := True;
  7618. Exit;
  7619. end;
  7620. end
  7621. else
  7622. begin
  7623. { See if the next references are 16 less rather than 16 greater }
  7624. Dec(SourceRef.offset, 32); { -16 the other way }
  7625. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7626. begin
  7627. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7628. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7629. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7630. GetNextInstruction(hp2, hp3) and
  7631. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7632. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7633. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7634. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7635. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7636. begin
  7637. { Update the register tracking to the new size }
  7638. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7639. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7640. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7641. if not(
  7642. ((SourceRef.offset mod 32) = 0) and
  7643. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7644. ) then
  7645. taicpu(hp2).opcode := A_VMOVDQU;
  7646. taicpu(hp2).opsize := S_YMM;
  7647. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7648. if not (
  7649. ((TargetRef.offset mod 32) = 0) and
  7650. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7651. ) then
  7652. taicpu(hp3).opcode := A_VMOVDQU;
  7653. taicpu(hp3).opsize := S_YMM;
  7654. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7655. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7656. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7657. if (pi_uses_ymm in current_procinfo.flags) then
  7658. RemoveInstruction(hp1)
  7659. else
  7660. begin
  7661. taicpu(hp1).opcode := A_VPXOR;
  7662. taicpu(hp1).opsize := S_YMM;
  7663. taicpu(hp1).loadreg(0, CurrentReg);
  7664. taicpu(hp1).loadreg(1, CurrentReg);
  7665. taicpu(hp1).loadreg(2, CurrentReg);
  7666. taicpu(hp1).ops := 3;
  7667. Asml.Remove(hp1);
  7668. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7669. end;
  7670. RemoveCurrentP(p, hp2);
  7671. Result := True;
  7672. Exit;
  7673. end;
  7674. end;
  7675. end;
  7676. end;
  7677. end;
  7678. end;
  7679. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7680. var
  7681. hp2, hp3, first_assignment: tai;
  7682. IncCount, OperIdx: Integer;
  7683. OrigLabel: TAsmLabel;
  7684. begin
  7685. Count := 0;
  7686. Result := False;
  7687. first_assignment := nil;
  7688. if (LoopCount >= 20) then
  7689. begin
  7690. { Guard against infinite loops }
  7691. Exit;
  7692. end;
  7693. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7694. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7695. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7696. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7697. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7698. Exit;
  7699. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7700. {
  7701. change
  7702. jmp .L1
  7703. ...
  7704. .L1:
  7705. mov ##, ## ( multiple movs possible )
  7706. jmp/ret
  7707. into
  7708. mov ##, ##
  7709. jmp/ret
  7710. }
  7711. if not Assigned(hp1) then
  7712. begin
  7713. hp1 := GetLabelWithSym(OrigLabel);
  7714. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7715. Exit;
  7716. end;
  7717. hp2 := hp1;
  7718. while Assigned(hp2) do
  7719. begin
  7720. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7721. SkipLabels(hp2,hp2);
  7722. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7723. Break;
  7724. case taicpu(hp2).opcode of
  7725. A_MOVSD:
  7726. begin
  7727. if taicpu(hp2).ops = 0 then
  7728. { Wrong MOVSD }
  7729. Break;
  7730. Inc(Count);
  7731. if Count >= 5 then
  7732. { Too many to be worthwhile }
  7733. Break;
  7734. GetNextInstruction(hp2, hp2);
  7735. Continue;
  7736. end;
  7737. A_MOV,
  7738. A_MOVD,
  7739. A_MOVQ,
  7740. A_MOVSX,
  7741. {$ifdef x86_64}
  7742. A_MOVSXD,
  7743. {$endif x86_64}
  7744. A_MOVZX,
  7745. A_MOVAPS,
  7746. A_MOVUPS,
  7747. A_MOVSS,
  7748. A_MOVAPD,
  7749. A_MOVUPD,
  7750. A_MOVDQA,
  7751. A_MOVDQU,
  7752. A_VMOVSS,
  7753. A_VMOVAPS,
  7754. A_VMOVUPS,
  7755. A_VMOVSD,
  7756. A_VMOVAPD,
  7757. A_VMOVUPD,
  7758. A_VMOVDQA,
  7759. A_VMOVDQU:
  7760. begin
  7761. Inc(Count);
  7762. if Count >= 5 then
  7763. { Too many to be worthwhile }
  7764. Break;
  7765. GetNextInstruction(hp2, hp2);
  7766. Continue;
  7767. end;
  7768. A_JMP:
  7769. begin
  7770. { Guard against infinite loops }
  7771. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7772. Exit;
  7773. { Analyse this jump first in case it also duplicates assignments }
  7774. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7775. begin
  7776. { Something did change! }
  7777. Result := True;
  7778. Inc(Count, IncCount);
  7779. if Count >= 5 then
  7780. begin
  7781. { Too many to be worthwhile }
  7782. Exit;
  7783. end;
  7784. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7785. Break;
  7786. end;
  7787. Result := True;
  7788. Break;
  7789. end;
  7790. A_RET:
  7791. begin
  7792. Result := True;
  7793. Break;
  7794. end;
  7795. else
  7796. Break;
  7797. end;
  7798. end;
  7799. if Result then
  7800. begin
  7801. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7802. if Count = 0 then
  7803. begin
  7804. Result := False;
  7805. Exit;
  7806. end;
  7807. hp3 := p;
  7808. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7809. while True do
  7810. begin
  7811. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7812. SkipLabels(hp1,hp1);
  7813. if (hp1.typ <> ait_instruction) then
  7814. InternalError(2021040720);
  7815. case taicpu(hp1).opcode of
  7816. A_JMP:
  7817. begin
  7818. { Change the original jump to the new destination }
  7819. OrigLabel.decrefs;
  7820. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7821. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7822. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7823. if not Assigned(first_assignment) then
  7824. InternalError(2021040810)
  7825. else
  7826. p := first_assignment;
  7827. Exit;
  7828. end;
  7829. A_RET:
  7830. begin
  7831. { Now change the jump into a RET instruction }
  7832. ConvertJumpToRET(p, hp1);
  7833. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7834. if not Assigned(first_assignment) then
  7835. InternalError(2021040811)
  7836. else
  7837. p := first_assignment;
  7838. Exit;
  7839. end;
  7840. else
  7841. begin
  7842. { Duplicate the MOV instruction }
  7843. hp3:=tai(hp1.getcopy);
  7844. if first_assignment = nil then
  7845. first_assignment := hp3;
  7846. asml.InsertBefore(hp3, p);
  7847. { Make sure the compiler knows about any final registers written here }
  7848. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7849. with taicpu(hp3).oper[OperIdx]^ do
  7850. begin
  7851. case typ of
  7852. top_ref:
  7853. begin
  7854. if (ref^.base <> NR_NO) and
  7855. (getsupreg(ref^.base) <> RS_ESP) and
  7856. (getsupreg(ref^.base) <> RS_EBP)
  7857. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7858. then
  7859. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7860. if (ref^.index <> NR_NO) and
  7861. (getsupreg(ref^.index) <> RS_ESP) and
  7862. (getsupreg(ref^.index) <> RS_EBP)
  7863. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7864. (ref^.index <> ref^.base) then
  7865. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7866. end;
  7867. top_reg:
  7868. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7869. else
  7870. ;
  7871. end;
  7872. end;
  7873. end;
  7874. end;
  7875. if not GetNextInstruction(hp1, hp1) then
  7876. { Should have dropped out earlier }
  7877. InternalError(2021040710);
  7878. end;
  7879. end;
  7880. end;
  7881. const
  7882. WriteOp: array[0..3] of set of TInsChange = (
  7883. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  7884. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  7885. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  7886. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  7887. RegWriteFlags: array[0..7] of set of TInsChange = (
  7888. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  7889. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  7890. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  7891. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  7892. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  7893. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  7894. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  7895. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  7896. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  7897. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  7898. var
  7899. hp2: tai;
  7900. X: Integer;
  7901. begin
  7902. { If we have something like:
  7903. op ###,###
  7904. mov ###,###
  7905. Try to move the MOV instruction to before OP as long as OP and MOV don't
  7906. interfere in regards to what they write to.
  7907. NOTE: p must be a 2-operand instruction
  7908. }
  7909. Result := False;
  7910. if (hp1.typ <> ait_instruction) or
  7911. taicpu(hp1).is_jmp or
  7912. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  7913. Exit;
  7914. { NOP is a pipeline fence, likely marking the beginning of the function
  7915. epilogue, so drop out. Similarly, drop out if POP or RET are
  7916. encountered }
  7917. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  7918. Exit;
  7919. if (taicpu(hp1).opcode = A_MOVSD) and
  7920. (taicpu(hp1).ops = 0) then
  7921. { Wrong MOVSD }
  7922. Exit;
  7923. { Check for writes to specific registers first }
  7924. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7925. for X := 0 to 7 do
  7926. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7927. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7928. Exit;
  7929. for X := 0 to taicpu(hp1).ops - 1 do
  7930. begin
  7931. { Check to see if this operand writes to something }
  7932. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7933. { And matches something in the CMP/TEST instruction }
  7934. (
  7935. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7936. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7937. (
  7938. { If it's a register, make sure the register written to doesn't
  7939. appear in the cmp instruction as part of a reference }
  7940. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7941. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7942. )
  7943. ) then
  7944. Exit;
  7945. end;
  7946. { Check p to make sure it doesn't write to something that affects hp1 }
  7947. { Check for writes to specific registers first }
  7948. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7949. for X := 0 to 7 do
  7950. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  7951. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  7952. Exit;
  7953. for X := 0 to taicpu(p).ops - 1 do
  7954. begin
  7955. { Check to see if this operand writes to something }
  7956. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  7957. { And matches something in hp1 }
  7958. (taicpu(p).oper[X]^.typ = top_reg) and
  7959. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  7960. Exit;
  7961. end;
  7962. { The instruction can be safely moved }
  7963. asml.Remove(hp1);
  7964. { Try to insert after the last instructions where the FLAGS register is not
  7965. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  7966. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  7967. asml.InsertBefore(hp1, hp2)
  7968. { Failing that, try to insert after the last instructions where the
  7969. FLAGS register is not yet in use }
  7970. else if GetLastInstruction(p, hp2) and
  7971. (
  7972. (hp2.typ <> ait_instruction) or
  7973. { Don't insert after an instruction that uses the flags when p doesn't use them }
  7974. RegInInstruction(NR_DEFAULTFLAGS, p) or
  7975. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  7976. ) then
  7977. asml.InsertAfter(hp1, hp2)
  7978. else
  7979. { Note, if p.Previous is nil (even if it should logically never be the
  7980. case), FindRegAllocBackward immediately exits with False and so we
  7981. safely land here (we can't just pass p because FindRegAllocBackward
  7982. immediately exits on an instruction). [Kit] }
  7983. asml.InsertBefore(hp1, p);
  7984. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7985. { We can't trust UsedRegs because we're looking backwards, although we
  7986. know the registers are allocated after p at the very least, so manually
  7987. create tai_regalloc objects if needed }
  7988. for X := 0 to taicpu(hp1).ops - 1 do
  7989. case taicpu(hp1).oper[X]^.typ of
  7990. top_reg:
  7991. begin
  7992. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  7993. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  7994. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7995. end;
  7996. top_ref:
  7997. begin
  7998. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7999. begin
  8000. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8001. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8002. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8003. end;
  8004. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8005. begin
  8006. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8007. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8008. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8009. end;
  8010. end;
  8011. else
  8012. ;
  8013. end;
  8014. Result := True;
  8015. end;
  8016. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8017. var
  8018. hp2: tai;
  8019. X: Integer;
  8020. begin
  8021. { If we have something like:
  8022. cmp ###,%reg1
  8023. mov 0,%reg2
  8024. And no modified registers are shared, move the instruction to before
  8025. the comparison as this means it can be optimised without worrying
  8026. about the FLAGS register. (CMP/MOV is generated by
  8027. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8028. As long as the second instruction doesn't use the flags or one of the
  8029. registers used by CMP or TEST (also check any references that use the
  8030. registers), then it can be moved prior to the comparison.
  8031. }
  8032. Result := False;
  8033. if not TrySwapMovOp(p, hp1) then
  8034. Exit;
  8035. if taicpu(hp1).opcode = A_LEA then
  8036. { The flags will be overwritten by the CMP/TEST instruction }
  8037. ConvertLEA(taicpu(hp1));
  8038. Result := True;
  8039. { Can we move it one further back? }
  8040. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8041. { Check to see if CMP/TEST is a comparison against zero }
  8042. (
  8043. (
  8044. (taicpu(p).opcode = A_CMP) and
  8045. MatchOperand(taicpu(p).oper[0]^, 0)
  8046. ) or
  8047. (
  8048. (taicpu(p).opcode = A_TEST) and
  8049. (
  8050. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8051. MatchOperand(taicpu(p).oper[0]^, -1)
  8052. )
  8053. )
  8054. ) and
  8055. { These instructions set the zero flag if the result is zero }
  8056. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8057. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8058. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8059. TrySwapMovOp(hp2, hp1);
  8060. end;
  8061. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8062. function IsXCHGAcceptable: Boolean; inline;
  8063. begin
  8064. { Always accept if optimising for size }
  8065. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8066. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8067. than 3, so it becomes a saving compared to three MOVs with two of
  8068. them able to execute simultaneously. [Kit] }
  8069. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8070. end;
  8071. var
  8072. NewRef: TReference;
  8073. hp1, hp2, hp3, hp4: Tai;
  8074. {$ifndef x86_64}
  8075. OperIdx: Integer;
  8076. {$endif x86_64}
  8077. NewInstr : Taicpu;
  8078. NewAligh : Tai_align;
  8079. DestLabel: TAsmLabel;
  8080. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8081. var
  8082. NextInstr: tai;
  8083. begin
  8084. Result := False;
  8085. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8086. if not GetNextInstruction(InputInstr, NextInstr) or
  8087. (
  8088. { The FLAGS register isn't always tracked properly, so do not
  8089. perform this optimisation if a conditional statement follows }
  8090. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8091. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8092. ) then
  8093. begin
  8094. reference_reset(NewRef, 1, []);
  8095. NewRef.base := taicpu(p).oper[0]^.reg;
  8096. NewRef.scalefactor := 1;
  8097. if taicpu(InputInstr).opcode = A_ADD then
  8098. begin
  8099. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8100. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8101. end
  8102. else
  8103. begin
  8104. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8105. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8106. end;
  8107. taicpu(p).opcode := A_LEA;
  8108. taicpu(p).loadref(0, NewRef);
  8109. RemoveInstruction(InputInstr);
  8110. Result := True;
  8111. end;
  8112. end;
  8113. begin
  8114. Result:=false;
  8115. { This optimisation adds an instruction, so only do it for speed }
  8116. if not (cs_opt_size in current_settings.optimizerswitches) and
  8117. MatchOpType(taicpu(p), top_const, top_reg) and
  8118. (taicpu(p).oper[0]^.val = 0) then
  8119. begin
  8120. { To avoid compiler warning }
  8121. DestLabel := nil;
  8122. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8123. InternalError(2021040750);
  8124. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8125. Exit;
  8126. case hp1.typ of
  8127. ait_align,
  8128. ait_label:
  8129. begin
  8130. { Change:
  8131. mov $0,%reg mov $0,%reg
  8132. @Lbl1: @Lbl1:
  8133. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8134. je @Lbl2 jne @Lbl2
  8135. To: To:
  8136. mov $0,%reg mov $0,%reg
  8137. jmp @Lbl2 jmp @Lbl3
  8138. (align) (align)
  8139. @Lbl1: @Lbl1:
  8140. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8141. je @Lbl2 je @Lbl2
  8142. @Lbl3: <-- Only if label exists
  8143. (Not if it's optimised for size)
  8144. }
  8145. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8146. Exit;
  8147. if (hp2.typ = ait_instruction) and
  8148. (
  8149. { Register sizes must exactly match }
  8150. (
  8151. (taicpu(hp2).opcode = A_CMP) and
  8152. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8153. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8154. ) or (
  8155. (taicpu(hp2).opcode = A_TEST) and
  8156. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8157. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8158. )
  8159. ) and GetNextInstruction(hp2, hp3) and
  8160. (hp3.typ = ait_instruction) and
  8161. (taicpu(hp3).opcode = A_JCC) and
  8162. (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
  8163. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8164. begin
  8165. { Check condition of jump }
  8166. { Always true? }
  8167. if condition_in(C_E, taicpu(hp3).condition) then
  8168. begin
  8169. { Copy label symbol and obtain matching label entry for the
  8170. conditional jump, as this will be our destination}
  8171. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8172. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8173. Result := True;
  8174. end
  8175. { Always false? }
  8176. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8177. begin
  8178. { This is only worth it if there's a jump to take }
  8179. case hp2.typ of
  8180. ait_instruction:
  8181. begin
  8182. if taicpu(hp2).opcode = A_JMP then
  8183. begin
  8184. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8185. { An unconditional jump follows the conditional jump which will always be false,
  8186. so use this jump's destination for the new jump }
  8187. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8188. Result := True;
  8189. end
  8190. else if taicpu(hp2).opcode = A_JCC then
  8191. begin
  8192. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8193. if condition_in(C_E, taicpu(hp2).condition) then
  8194. begin
  8195. { A second conditional jump follows the conditional jump which will always be false,
  8196. while the second jump is always True, so use this jump's destination for the new jump }
  8197. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8198. Result := True;
  8199. end;
  8200. { Don't risk it if the jump isn't always true (Result remains False) }
  8201. end;
  8202. end;
  8203. else
  8204. { If anything else don't optimise };
  8205. end;
  8206. end;
  8207. if Result then
  8208. begin
  8209. { Just so we have something to insert as a paremeter}
  8210. reference_reset(NewRef, 1, []);
  8211. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8212. { Now actually load the correct parameter (this also
  8213. increases the reference count) }
  8214. NewInstr.loadsymbol(0, DestLabel, 0);
  8215. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8216. begin
  8217. { Get instruction before original label (may not be p under -O3) }
  8218. if not GetLastInstruction(hp1, hp2) then
  8219. { Shouldn't fail here }
  8220. InternalError(2021040701);
  8221. { Before the aligns too }
  8222. while (hp2.typ = ait_align) do
  8223. if not GetLastInstruction(hp2, hp2) then
  8224. { Shouldn't fail here }
  8225. InternalError(2021040702);
  8226. end
  8227. else
  8228. hp2 := p;
  8229. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8230. AsmL.InsertAfter(NewInstr, hp2);
  8231. { Add new alignment field }
  8232. (* AsmL.InsertAfter(
  8233. cai_align.create_max(
  8234. current_settings.alignment.jumpalign,
  8235. current_settings.alignment.jumpalignskipmax
  8236. ),
  8237. NewInstr
  8238. ); *)
  8239. end;
  8240. Exit;
  8241. end;
  8242. end;
  8243. else
  8244. ;
  8245. end;
  8246. end;
  8247. if not GetNextInstruction(p, hp1) then
  8248. Exit;
  8249. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8250. and DoMovCmpMemOpt(p, hp1, True) then
  8251. begin
  8252. Result := True;
  8253. Exit;
  8254. end
  8255. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8256. begin
  8257. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8258. further, but we can't just put this jump optimisation in pass 1
  8259. because it tends to perform worse when conditional jumps are
  8260. nearby (e.g. when converting CMOV instructions). [Kit] }
  8261. if OptPass2JMP(hp1) then
  8262. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8263. Result := OptPass1MOV(p)
  8264. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8265. returned True and the instruction is still a MOV, thus checking
  8266. the optimisations below }
  8267. { If OptPass2JMP returned False, no optimisations were done to
  8268. the jump and there are no further optimisations that can be done
  8269. to the MOV instruction on this pass }
  8270. end
  8271. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8272. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8273. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8274. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8275. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8276. begin
  8277. { Change:
  8278. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8279. addl/q $x,%reg2 subl/q $x,%reg2
  8280. To:
  8281. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8282. }
  8283. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8284. { be lazy, checking separately for sub would be slightly better }
  8285. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8286. begin
  8287. TransferUsedRegs(TmpUsedRegs);
  8288. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8289. if TryMovArith2Lea(hp1) then
  8290. begin
  8291. Result := True;
  8292. Exit;
  8293. end
  8294. end
  8295. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8296. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8297. { Same as above, but also adds or subtracts to %reg2 in between.
  8298. It's still valid as long as the flags aren't in use }
  8299. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8300. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8301. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8302. { be lazy, checking separately for sub would be slightly better }
  8303. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8304. begin
  8305. TransferUsedRegs(TmpUsedRegs);
  8306. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8307. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8308. if TryMovArith2Lea(hp2) then
  8309. begin
  8310. Result := True;
  8311. Exit;
  8312. end;
  8313. end;
  8314. end
  8315. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8316. {$ifdef x86_64}
  8317. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8318. {$else x86_64}
  8319. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8320. {$endif x86_64}
  8321. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8322. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8323. { mov reg1, reg2 mov reg1, reg2
  8324. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8325. begin
  8326. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8327. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8328. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8329. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8330. TransferUsedRegs(TmpUsedRegs);
  8331. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8332. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8333. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8334. then
  8335. begin
  8336. RemoveCurrentP(p, hp1);
  8337. Result:=true;
  8338. end;
  8339. exit;
  8340. end
  8341. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8342. IsXCHGAcceptable and
  8343. { XCHG doesn't support 8-byte registers }
  8344. (taicpu(p).opsize <> S_B) and
  8345. MatchInstruction(hp1, A_MOV, []) and
  8346. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8347. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8348. GetNextInstruction(hp1, hp2) and
  8349. MatchInstruction(hp2, A_MOV, []) and
  8350. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8351. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8352. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8353. begin
  8354. { mov %reg1,%reg2
  8355. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8356. mov %reg2,%reg3
  8357. (%reg2 not used afterwards)
  8358. Note that xchg takes 3 cycles to execute, and generally mov's take
  8359. only one cycle apiece, but the first two mov's can be executed in
  8360. parallel, only taking 2 cycles overall. Older processors should
  8361. therefore only optimise for size. [Kit]
  8362. }
  8363. TransferUsedRegs(TmpUsedRegs);
  8364. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8365. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8366. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8367. begin
  8368. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8369. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8370. taicpu(hp1).opcode := A_XCHG;
  8371. RemoveCurrentP(p, hp1);
  8372. RemoveInstruction(hp2);
  8373. Result := True;
  8374. Exit;
  8375. end;
  8376. end
  8377. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8378. MatchInstruction(hp1, A_SAR, []) then
  8379. begin
  8380. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8381. begin
  8382. { the use of %edx also covers the opsize being S_L }
  8383. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8384. begin
  8385. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8386. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8387. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8388. begin
  8389. { Change:
  8390. movl %eax,%edx
  8391. sarl $31,%edx
  8392. To:
  8393. cltd
  8394. }
  8395. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8396. RemoveInstruction(hp1);
  8397. taicpu(p).opcode := A_CDQ;
  8398. taicpu(p).opsize := S_NO;
  8399. taicpu(p).clearop(1);
  8400. taicpu(p).clearop(0);
  8401. taicpu(p).ops:=0;
  8402. Result := True;
  8403. end
  8404. else if (cs_opt_size in current_settings.optimizerswitches) and
  8405. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8406. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8407. begin
  8408. { Change:
  8409. movl %edx,%eax
  8410. sarl $31,%edx
  8411. To:
  8412. movl %edx,%eax
  8413. cltd
  8414. Note that this creates a dependency between the two instructions,
  8415. so only perform if optimising for size.
  8416. }
  8417. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8418. taicpu(hp1).opcode := A_CDQ;
  8419. taicpu(hp1).opsize := S_NO;
  8420. taicpu(hp1).clearop(1);
  8421. taicpu(hp1).clearop(0);
  8422. taicpu(hp1).ops:=0;
  8423. end;
  8424. {$ifndef x86_64}
  8425. end
  8426. { Don't bother if CMOV is supported, because a more optimal
  8427. sequence would have been generated for the Abs() intrinsic }
  8428. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8429. { the use of %eax also covers the opsize being S_L }
  8430. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8431. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8432. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8433. GetNextInstruction(hp1, hp2) and
  8434. MatchInstruction(hp2, A_XOR, [S_L]) and
  8435. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8436. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8437. GetNextInstruction(hp2, hp3) and
  8438. MatchInstruction(hp3, A_SUB, [S_L]) and
  8439. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8440. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8441. begin
  8442. { Change:
  8443. movl %eax,%edx
  8444. sarl $31,%eax
  8445. xorl %eax,%edx
  8446. subl %eax,%edx
  8447. (Instruction that uses %edx)
  8448. (%eax deallocated)
  8449. (%edx deallocated)
  8450. To:
  8451. cltd
  8452. xorl %edx,%eax <-- Note the registers have swapped
  8453. subl %edx,%eax
  8454. (Instruction that uses %eax) <-- %eax rather than %edx
  8455. }
  8456. TransferUsedRegs(TmpUsedRegs);
  8457. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8458. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8459. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8460. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8461. begin
  8462. if GetNextInstruction(hp3, hp4) and
  8463. not RegModifiedByInstruction(NR_EDX, hp4) and
  8464. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8465. begin
  8466. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8467. taicpu(p).opcode := A_CDQ;
  8468. taicpu(p).clearop(1);
  8469. taicpu(p).clearop(0);
  8470. taicpu(p).ops:=0;
  8471. RemoveInstruction(hp1);
  8472. taicpu(hp2).loadreg(0, NR_EDX);
  8473. taicpu(hp2).loadreg(1, NR_EAX);
  8474. taicpu(hp3).loadreg(0, NR_EDX);
  8475. taicpu(hp3).loadreg(1, NR_EAX);
  8476. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8477. { Convert references in the following instruction (hp4) from %edx to %eax }
  8478. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8479. with taicpu(hp4).oper[OperIdx]^ do
  8480. case typ of
  8481. top_reg:
  8482. if getsupreg(reg) = RS_EDX then
  8483. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8484. top_ref:
  8485. begin
  8486. if getsupreg(reg) = RS_EDX then
  8487. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8488. if getsupreg(reg) = RS_EDX then
  8489. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8490. end;
  8491. else
  8492. ;
  8493. end;
  8494. end;
  8495. end;
  8496. {$else x86_64}
  8497. end;
  8498. end
  8499. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8500. { the use of %rdx also covers the opsize being S_Q }
  8501. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8502. begin
  8503. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8504. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8505. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8506. begin
  8507. { Change:
  8508. movq %rax,%rdx
  8509. sarq $63,%rdx
  8510. To:
  8511. cqto
  8512. }
  8513. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8514. RemoveInstruction(hp1);
  8515. taicpu(p).opcode := A_CQO;
  8516. taicpu(p).opsize := S_NO;
  8517. taicpu(p).clearop(1);
  8518. taicpu(p).clearop(0);
  8519. taicpu(p).ops:=0;
  8520. Result := True;
  8521. end
  8522. else if (cs_opt_size in current_settings.optimizerswitches) and
  8523. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8524. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8525. begin
  8526. { Change:
  8527. movq %rdx,%rax
  8528. sarq $63,%rdx
  8529. To:
  8530. movq %rdx,%rax
  8531. cqto
  8532. Note that this creates a dependency between the two instructions,
  8533. so only perform if optimising for size.
  8534. }
  8535. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8536. taicpu(hp1).opcode := A_CQO;
  8537. taicpu(hp1).opsize := S_NO;
  8538. taicpu(hp1).clearop(1);
  8539. taicpu(hp1).clearop(0);
  8540. taicpu(hp1).ops:=0;
  8541. {$endif x86_64}
  8542. end;
  8543. end;
  8544. end
  8545. else if MatchInstruction(hp1, A_MOV, []) and
  8546. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8547. { Though "GetNextInstruction" could be factored out, along with
  8548. the instructions that depend on hp2, it is an expensive call that
  8549. should be delayed for as long as possible, hence we do cheaper
  8550. checks first that are likely to be False. [Kit] }
  8551. begin
  8552. if (
  8553. (
  8554. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8555. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8556. (
  8557. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8558. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8559. )
  8560. ) or
  8561. (
  8562. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8563. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8564. (
  8565. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8566. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8567. )
  8568. )
  8569. ) and
  8570. GetNextInstruction(hp1, hp2) and
  8571. MatchInstruction(hp2, A_SAR, []) and
  8572. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8573. begin
  8574. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8575. begin
  8576. { Change:
  8577. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8578. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8579. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8580. To:
  8581. movl r/m,%eax <- Note the change in register
  8582. cltd
  8583. }
  8584. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8585. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8586. taicpu(p).loadreg(1, NR_EAX);
  8587. taicpu(hp1).opcode := A_CDQ;
  8588. taicpu(hp1).clearop(1);
  8589. taicpu(hp1).clearop(0);
  8590. taicpu(hp1).ops:=0;
  8591. RemoveInstruction(hp2);
  8592. (*
  8593. {$ifdef x86_64}
  8594. end
  8595. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8596. { This code sequence does not get generated - however it might become useful
  8597. if and when 128-bit signed integer types make an appearance, so the code
  8598. is kept here for when it is eventually needed. [Kit] }
  8599. (
  8600. (
  8601. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8602. (
  8603. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8604. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8605. )
  8606. ) or
  8607. (
  8608. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8609. (
  8610. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8611. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8612. )
  8613. )
  8614. ) and
  8615. GetNextInstruction(hp1, hp2) and
  8616. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8617. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8618. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8619. begin
  8620. { Change:
  8621. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8622. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8623. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8624. To:
  8625. movq r/m,%rax <- Note the change in register
  8626. cqto
  8627. }
  8628. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8629. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8630. taicpu(p).loadreg(1, NR_RAX);
  8631. taicpu(hp1).opcode := A_CQO;
  8632. taicpu(hp1).clearop(1);
  8633. taicpu(hp1).clearop(0);
  8634. taicpu(hp1).ops:=0;
  8635. RemoveInstruction(hp2);
  8636. {$endif x86_64}
  8637. *)
  8638. end;
  8639. end;
  8640. {$ifdef x86_64}
  8641. end
  8642. else if (taicpu(p).opsize = S_L) and
  8643. (taicpu(p).oper[1]^.typ = top_reg) and
  8644. (
  8645. MatchInstruction(hp1, A_MOV,[]) and
  8646. (taicpu(hp1).opsize = S_L) and
  8647. (taicpu(hp1).oper[1]^.typ = top_reg)
  8648. ) and (
  8649. GetNextInstruction(hp1, hp2) and
  8650. (tai(hp2).typ=ait_instruction) and
  8651. (taicpu(hp2).opsize = S_Q) and
  8652. (
  8653. (
  8654. MatchInstruction(hp2, A_ADD,[]) and
  8655. (taicpu(hp2).opsize = S_Q) and
  8656. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8657. (
  8658. (
  8659. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8660. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8661. ) or (
  8662. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8663. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8664. )
  8665. )
  8666. ) or (
  8667. MatchInstruction(hp2, A_LEA,[]) and
  8668. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8669. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8670. (
  8671. (
  8672. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8673. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8674. ) or (
  8675. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8676. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8677. )
  8678. ) and (
  8679. (
  8680. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8681. ) or (
  8682. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8683. )
  8684. )
  8685. )
  8686. )
  8687. ) and (
  8688. GetNextInstruction(hp2, hp3) and
  8689. MatchInstruction(hp3, A_SHR,[]) and
  8690. (taicpu(hp3).opsize = S_Q) and
  8691. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8692. (taicpu(hp3).oper[0]^.val = 1) and
  8693. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8694. ) then
  8695. begin
  8696. { Change movl x, reg1d movl x, reg1d
  8697. movl y, reg2d movl y, reg2d
  8698. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8699. shrq $1, reg1q shrq $1, reg1q
  8700. ( reg1d and reg2d can be switched around in the first two instructions )
  8701. To movl x, reg1d
  8702. addl y, reg1d
  8703. rcrl $1, reg1d
  8704. This corresponds to the common expression (x + y) shr 1, where
  8705. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  8706. smaller code, but won't account for x + y causing an overflow). [Kit]
  8707. }
  8708. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  8709. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8710. { Change first MOV command to have the same register as the final output }
  8711. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  8712. else
  8713. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  8714. { Change second MOV command to an ADD command. This is easier than
  8715. converting the existing command because it means we don't have to
  8716. touch 'y', which might be a complicated reference, and also the
  8717. fact that the third command might either be ADD or LEA. [Kit] }
  8718. taicpu(hp1).opcode := A_ADD;
  8719. { Delete old ADD/LEA instruction }
  8720. RemoveInstruction(hp2);
  8721. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  8722. taicpu(hp3).opcode := A_RCR;
  8723. taicpu(hp3).changeopsize(S_L);
  8724. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  8725. {$endif x86_64}
  8726. end;
  8727. if FuncMov2Func(p, hp1) then
  8728. begin
  8729. Result := True;
  8730. Exit;
  8731. end;
  8732. end;
  8733. {$push}
  8734. {$q-}{$r-}
  8735. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  8736. var
  8737. ThisReg: TRegister;
  8738. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  8739. TargetSubReg: TSubRegister;
  8740. hp1, hp2: tai;
  8741. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  8742. { Store list of found instructions so we don't have to call
  8743. GetNextInstructionUsingReg multiple times }
  8744. InstrList: array of taicpu;
  8745. InstrMax, Index: Integer;
  8746. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  8747. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  8748. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  8749. WorkingValue: TCgInt;
  8750. PreMessage: string;
  8751. { Data flow analysis }
  8752. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  8753. BitwiseOnly, OrXorUsed,
  8754. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  8755. function CheckOverflowConditions: Boolean;
  8756. begin
  8757. Result := True;
  8758. if (TestValSignedMax > SignedUpperLimit) then
  8759. UpperSignedOverflow := True;
  8760. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  8761. LowerSignedOverflow := True;
  8762. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  8763. LowerUnsignedOverflow := True;
  8764. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  8765. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  8766. begin
  8767. { Absolute overflow }
  8768. Result := False;
  8769. Exit;
  8770. end;
  8771. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  8772. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8773. ShiftDownOverflow := True;
  8774. if (TestValMin < 0) or (TestValMax < 0) then
  8775. begin
  8776. LowerUnsignedOverflow := True;
  8777. UpperUnsignedOverflow := True;
  8778. end;
  8779. end;
  8780. function AdjustInitialLoadAndSize: Boolean;
  8781. begin
  8782. Result := False;
  8783. if not p_removed then
  8784. begin
  8785. if TargetSize = MinSize then
  8786. begin
  8787. { Convert the input MOVZX to a MOV }
  8788. if (taicpu(p).oper[0]^.typ = top_reg) and
  8789. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8790. begin
  8791. { Or remove it completely! }
  8792. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8793. RemoveCurrentP(p);
  8794. p_removed := True;
  8795. end
  8796. else
  8797. begin
  8798. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8799. taicpu(p).opcode := A_MOV;
  8800. taicpu(p).oper[1]^.reg := ThisReg;
  8801. taicpu(p).opsize := TargetSize;
  8802. end;
  8803. Result := True;
  8804. end
  8805. else if TargetSize <> MaxSize then
  8806. begin
  8807. case MaxSize of
  8808. S_L:
  8809. if TargetSize = S_W then
  8810. begin
  8811. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8812. taicpu(p).opsize := S_BW;
  8813. taicpu(p).oper[1]^.reg := ThisReg;
  8814. Result := True;
  8815. end
  8816. else
  8817. InternalError(2020112341);
  8818. S_W:
  8819. if TargetSize = S_L then
  8820. begin
  8821. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8822. taicpu(p).opsize := S_BL;
  8823. taicpu(p).oper[1]^.reg := ThisReg;
  8824. Result := True;
  8825. end
  8826. else
  8827. InternalError(2020112342);
  8828. else
  8829. ;
  8830. end;
  8831. end
  8832. else if not hp1_removed and not RegInUse then
  8833. begin
  8834. { If we have something like:
  8835. movzbl (oper),%regd
  8836. add x, %regd
  8837. movzbl %regb, %regd
  8838. We can reduce the register size to the input of the final
  8839. movzbl instruction. Overflows won't have any effect.
  8840. }
  8841. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8842. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8843. begin
  8844. TargetSize := S_B;
  8845. setsubreg(ThisReg, R_SUBL);
  8846. Result := True;
  8847. end
  8848. else if (taicpu(p).opsize = S_WL) and
  8849. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8850. begin
  8851. TargetSize := S_W;
  8852. setsubreg(ThisReg, R_SUBW);
  8853. Result := True;
  8854. end;
  8855. if Result then
  8856. begin
  8857. { Convert the input MOVZX to a MOV }
  8858. if (taicpu(p).oper[0]^.typ = top_reg) and
  8859. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8860. begin
  8861. { Or remove it completely! }
  8862. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8863. RemoveCurrentP(p);
  8864. p_removed := True;
  8865. end
  8866. else
  8867. begin
  8868. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8869. taicpu(p).opcode := A_MOV;
  8870. taicpu(p).oper[1]^.reg := ThisReg;
  8871. taicpu(p).opsize := TargetSize;
  8872. end;
  8873. end;
  8874. end;
  8875. end;
  8876. end;
  8877. procedure AdjustFinalLoad;
  8878. begin
  8879. if not LowerUnsignedOverflow then
  8880. begin
  8881. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  8882. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  8883. begin
  8884. { Convert the output MOVZX to a MOV }
  8885. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8886. begin
  8887. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  8888. if (MinSize = S_B) or
  8889. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  8890. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  8891. begin
  8892. { Remove it completely! }
  8893. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  8894. { Be careful; if p = hp1 and p was also removed, p
  8895. will become a dangling pointer }
  8896. if p = hp1 then
  8897. begin
  8898. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8899. p_removed := True;
  8900. end
  8901. else
  8902. RemoveInstruction(hp1);
  8903. hp1_removed := True;
  8904. end;
  8905. end
  8906. else
  8907. begin
  8908. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  8909. taicpu(hp1).opcode := A_MOV;
  8910. taicpu(hp1).oper[0]^.reg := ThisReg;
  8911. taicpu(hp1).opsize := TargetSize;
  8912. end;
  8913. end
  8914. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  8915. begin
  8916. { Need to change the size of the output }
  8917. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  8918. taicpu(hp1).oper[0]^.reg := ThisReg;
  8919. taicpu(hp1).opsize := S_BL;
  8920. end;
  8921. end;
  8922. end;
  8923. function CompressInstructions: Boolean;
  8924. var
  8925. LocalIndex: Integer;
  8926. begin
  8927. Result := False;
  8928. { The objective here is to try to find a combination that
  8929. removes one of the MOV/Z instructions. }
  8930. if (
  8931. (taicpu(p).oper[0]^.typ <> top_reg) or
  8932. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  8933. ) and
  8934. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8935. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8936. begin
  8937. { Make a preference to remove the second MOVZX instruction }
  8938. case taicpu(hp1).opsize of
  8939. S_BL, S_WL:
  8940. begin
  8941. TargetSize := S_L;
  8942. TargetSubReg := R_SUBD;
  8943. end;
  8944. S_BW:
  8945. begin
  8946. TargetSize := S_W;
  8947. TargetSubReg := R_SUBW;
  8948. end;
  8949. else
  8950. InternalError(2020112302);
  8951. end;
  8952. end
  8953. else
  8954. begin
  8955. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8956. begin
  8957. { Exceeded lower bound but not upper bound }
  8958. TargetSize := MaxSize;
  8959. end
  8960. else if not LowerUnsignedOverflow then
  8961. begin
  8962. { Size didn't exceed lower bound }
  8963. TargetSize := MinSize;
  8964. end
  8965. else
  8966. Exit;
  8967. end;
  8968. case TargetSize of
  8969. S_B:
  8970. TargetSubReg := R_SUBL;
  8971. S_W:
  8972. TargetSubReg := R_SUBW;
  8973. S_L:
  8974. TargetSubReg := R_SUBD;
  8975. else
  8976. InternalError(2020112350);
  8977. end;
  8978. { Update the register to its new size }
  8979. setsubreg(ThisReg, TargetSubReg);
  8980. RegInUse := False;
  8981. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8982. begin
  8983. { Check to see if the active register is used afterwards;
  8984. if not, we can change it and make a saving. }
  8985. TransferUsedRegs(TmpUsedRegs);
  8986. { The target register may be marked as in use to cross
  8987. a jump to a distant label, so exclude it }
  8988. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8989. hp2 := p;
  8990. repeat
  8991. { Explicitly check for the excluded register (don't include the first
  8992. instruction as it may be reading from here }
  8993. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8994. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8995. begin
  8996. RegInUse := True;
  8997. Break;
  8998. end;
  8999. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9000. if not GetNextInstruction(hp2, hp2) then
  9001. InternalError(2020112340);
  9002. until (hp2 = hp1);
  9003. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9004. { We might still be able to get away with this }
  9005. RegInUse := not
  9006. (
  9007. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9008. (hp2.typ = ait_instruction) and
  9009. (
  9010. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9011. instruction that doesn't actually contain ThisReg }
  9012. (cs_opt_level3 in current_settings.optimizerswitches) or
  9013. RegInInstruction(ThisReg, hp2)
  9014. ) and
  9015. RegLoadedWithNewValue(ThisReg, hp2)
  9016. );
  9017. if not RegInUse then
  9018. begin
  9019. { Force the register size to the same as this instruction so it can be removed}
  9020. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9021. begin
  9022. TargetSize := S_L;
  9023. TargetSubReg := R_SUBD;
  9024. end
  9025. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9026. begin
  9027. TargetSize := S_W;
  9028. TargetSubReg := R_SUBW;
  9029. end;
  9030. ThisReg := taicpu(hp1).oper[1]^.reg;
  9031. setsubreg(ThisReg, TargetSubReg);
  9032. RegChanged := True;
  9033. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9034. TransferUsedRegs(TmpUsedRegs);
  9035. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9036. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9037. if p = hp1 then
  9038. begin
  9039. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9040. p_removed := True;
  9041. end
  9042. else
  9043. RemoveInstruction(hp1);
  9044. hp1_removed := True;
  9045. { Instruction will become "mov %reg,%reg" }
  9046. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9047. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9048. begin
  9049. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9050. RemoveCurrentP(p);
  9051. p_removed := True;
  9052. end
  9053. else
  9054. taicpu(p).oper[1]^.reg := ThisReg;
  9055. Result := True;
  9056. end
  9057. else
  9058. begin
  9059. if TargetSize <> MaxSize then
  9060. begin
  9061. { Since the register is in use, we have to force it to
  9062. MaxSize otherwise part of it may become undefined later on }
  9063. TargetSize := MaxSize;
  9064. case TargetSize of
  9065. S_B:
  9066. TargetSubReg := R_SUBL;
  9067. S_W:
  9068. TargetSubReg := R_SUBW;
  9069. S_L:
  9070. TargetSubReg := R_SUBD;
  9071. else
  9072. InternalError(2020112351);
  9073. end;
  9074. setsubreg(ThisReg, TargetSubReg);
  9075. end;
  9076. AdjustFinalLoad;
  9077. end;
  9078. end
  9079. else
  9080. AdjustFinalLoad;
  9081. Result := AdjustInitialLoadAndSize or Result;
  9082. { Now go through every instruction we found and change the
  9083. size. If TargetSize = MaxSize, then almost no changes are
  9084. needed and Result can remain False if it hasn't been set
  9085. yet.
  9086. If RegChanged is True, then the register requires changing
  9087. and so the point about TargetSize = MaxSize doesn't apply. }
  9088. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9089. begin
  9090. for LocalIndex := 0 to InstrMax do
  9091. begin
  9092. { If p_removed is true, then the original MOV/Z was removed
  9093. and removing the AND instruction may not be safe if it
  9094. appears first }
  9095. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9096. InternalError(2020112310);
  9097. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9098. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9099. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9100. InstrList[LocalIndex].opsize := TargetSize;
  9101. end;
  9102. Result := True;
  9103. end;
  9104. end;
  9105. begin
  9106. Result := False;
  9107. p_removed := False;
  9108. hp1_removed := False;
  9109. ThisReg := taicpu(p).oper[1]^.reg;
  9110. { Check for:
  9111. movs/z ###,%ecx (or %cx or %rcx)
  9112. ...
  9113. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9114. (dealloc %ecx)
  9115. Change to:
  9116. mov ###,%cl (if ### = %cl, then remove completely)
  9117. ...
  9118. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9119. }
  9120. if (getsupreg(ThisReg) = RS_ECX) and
  9121. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9122. (hp1.typ = ait_instruction) and
  9123. (
  9124. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9125. instruction that doesn't actually contain ECX }
  9126. (cs_opt_level3 in current_settings.optimizerswitches) or
  9127. RegInInstruction(NR_ECX, hp1) or
  9128. (
  9129. { It's common for the shift/rotate's read/write register to be
  9130. initialised in between, so under -O2 and under, search ahead
  9131. one more instruction
  9132. }
  9133. GetNextInstruction(hp1, hp1) and
  9134. (hp1.typ = ait_instruction) and
  9135. RegInInstruction(NR_ECX, hp1)
  9136. )
  9137. ) and
  9138. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9139. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9140. begin
  9141. TransferUsedRegs(TmpUsedRegs);
  9142. hp2 := p;
  9143. repeat
  9144. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9145. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9146. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9147. begin
  9148. case taicpu(p).opsize of
  9149. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9150. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9151. begin
  9152. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9153. RemoveCurrentP(p);
  9154. end
  9155. else
  9156. begin
  9157. taicpu(p).opcode := A_MOV;
  9158. taicpu(p).opsize := S_B;
  9159. taicpu(p).oper[1]^.reg := NR_CL;
  9160. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9161. end;
  9162. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9163. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9164. begin
  9165. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9166. RemoveCurrentP(p);
  9167. end
  9168. else
  9169. begin
  9170. taicpu(p).opcode := A_MOV;
  9171. taicpu(p).opsize := S_W;
  9172. taicpu(p).oper[1]^.reg := NR_CX;
  9173. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9174. end;
  9175. {$ifdef x86_64}
  9176. S_LQ:
  9177. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9178. begin
  9179. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9180. RemoveCurrentP(p);
  9181. end
  9182. else
  9183. begin
  9184. taicpu(p).opcode := A_MOV;
  9185. taicpu(p).opsize := S_L;
  9186. taicpu(p).oper[1]^.reg := NR_ECX;
  9187. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9188. end;
  9189. {$endif x86_64}
  9190. else
  9191. InternalError(2021120401);
  9192. end;
  9193. Result := True;
  9194. Exit;
  9195. end;
  9196. end;
  9197. { This is anything but quick! }
  9198. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9199. Exit;
  9200. SetLength(InstrList, 0);
  9201. InstrMax := -1;
  9202. case taicpu(p).opsize of
  9203. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9204. begin
  9205. {$if defined(i386) or defined(i8086)}
  9206. { If the target size is 8-bit, make sure we can actually encode it }
  9207. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9208. Exit;
  9209. {$endif i386 or i8086}
  9210. LowerLimit := $FF;
  9211. SignedLowerLimit := $7F;
  9212. SignedLowerLimitBottom := -128;
  9213. MinSize := S_B;
  9214. if taicpu(p).opsize = S_BW then
  9215. begin
  9216. MaxSize := S_W;
  9217. UpperLimit := $FFFF;
  9218. SignedUpperLimit := $7FFF;
  9219. SignedUpperLimitBottom := -32768;
  9220. end
  9221. else
  9222. begin
  9223. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9224. MaxSize := S_L;
  9225. UpperLimit := $FFFFFFFF;
  9226. SignedUpperLimit := $7FFFFFFF;
  9227. SignedUpperLimitBottom := -2147483648;
  9228. end;
  9229. end;
  9230. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9231. begin
  9232. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9233. LowerLimit := $FFFF;
  9234. SignedLowerLimit := $7FFF;
  9235. SignedLowerLimitBottom := -32768;
  9236. UpperLimit := $FFFFFFFF;
  9237. SignedUpperLimit := $7FFFFFFF;
  9238. SignedUpperLimitBottom := -2147483648;
  9239. MinSize := S_W;
  9240. MaxSize := S_L;
  9241. end;
  9242. {$ifdef x86_64}
  9243. S_LQ:
  9244. begin
  9245. { Both the lower and upper limits are set to 32-bit. If a limit
  9246. is breached, then optimisation is impossible }
  9247. LowerLimit := $FFFFFFFF;
  9248. SignedLowerLimit := $7FFFFFFF;
  9249. SignedLowerLimitBottom := -2147483648;
  9250. UpperLimit := $FFFFFFFF;
  9251. SignedUpperLimit := $7FFFFFFF;
  9252. SignedUpperLimitBottom := -2147483648;
  9253. MinSize := S_L;
  9254. MaxSize := S_L;
  9255. end;
  9256. {$endif x86_64}
  9257. else
  9258. InternalError(2020112301);
  9259. end;
  9260. TestValMin := 0;
  9261. TestValMax := LowerLimit;
  9262. TestValSignedMax := SignedLowerLimit;
  9263. TryShiftDownLimit := LowerLimit;
  9264. TryShiftDown := S_NO;
  9265. ShiftDownOverflow := False;
  9266. RegChanged := False;
  9267. BitwiseOnly := True;
  9268. OrXorUsed := False;
  9269. UpperSignedOverflow := False;
  9270. LowerSignedOverflow := False;
  9271. UpperUnsignedOverflow := False;
  9272. LowerUnsignedOverflow := False;
  9273. hp1 := p;
  9274. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9275. (hp1.typ = ait_instruction) and
  9276. (
  9277. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9278. instruction that doesn't actually contain ThisReg }
  9279. (cs_opt_level3 in current_settings.optimizerswitches) or
  9280. { This allows this Movx optimisation to work through the SETcc instructions
  9281. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9282. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9283. skip over these SETcc instructions). }
  9284. (taicpu(hp1).opcode = A_SETcc) or
  9285. RegInInstruction(ThisReg, hp1)
  9286. ) do
  9287. begin
  9288. case taicpu(hp1).opcode of
  9289. A_INC,A_DEC:
  9290. begin
  9291. { Has to be an exact match on the register }
  9292. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9293. Break;
  9294. if taicpu(hp1).opcode = A_INC then
  9295. begin
  9296. Inc(TestValMin);
  9297. Inc(TestValMax);
  9298. Inc(TestValSignedMax);
  9299. end
  9300. else
  9301. begin
  9302. Dec(TestValMin);
  9303. Dec(TestValMax);
  9304. Dec(TestValSignedMax);
  9305. end;
  9306. end;
  9307. A_TEST, A_CMP:
  9308. begin
  9309. if (
  9310. { Too high a risk of non-linear behaviour that breaks DFA
  9311. here, unless it's cmp $0,%reg, which is equivalent to
  9312. test %reg,%reg }
  9313. OrXorUsed and
  9314. (taicpu(hp1).opcode = A_CMP) and
  9315. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9316. ) or
  9317. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9318. { Has to be an exact match on the register }
  9319. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9320. (
  9321. { Permit "test %reg,%reg" }
  9322. (taicpu(hp1).opcode = A_TEST) and
  9323. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9324. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9325. ) or
  9326. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9327. { Make sure the comparison value is not smaller than the
  9328. smallest allowed signed value for the minimum size (e.g.
  9329. -128 for 8-bit) }
  9330. not (
  9331. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9332. { Is it in the negative range? }
  9333. (
  9334. (taicpu(hp1).oper[0]^.val < 0) and
  9335. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9336. )
  9337. ) then
  9338. Break;
  9339. { Check to see if the active register is used afterwards }
  9340. TransferUsedRegs(TmpUsedRegs);
  9341. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9342. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9343. begin
  9344. { Make sure the comparison or any previous instructions
  9345. hasn't pushed the test values outside of the range of
  9346. MinSize }
  9347. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9348. begin
  9349. { Exceeded lower bound but not upper bound }
  9350. Exit;
  9351. end
  9352. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9353. begin
  9354. { Size didn't exceed lower bound }
  9355. TargetSize := MinSize;
  9356. end
  9357. else
  9358. Break;
  9359. case TargetSize of
  9360. S_B:
  9361. TargetSubReg := R_SUBL;
  9362. S_W:
  9363. TargetSubReg := R_SUBW;
  9364. S_L:
  9365. TargetSubReg := R_SUBD;
  9366. else
  9367. InternalError(2021051002);
  9368. end;
  9369. if TargetSize <> MaxSize then
  9370. begin
  9371. { Update the register to its new size }
  9372. setsubreg(ThisReg, TargetSubReg);
  9373. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9374. taicpu(hp1).oper[1]^.reg := ThisReg;
  9375. taicpu(hp1).opsize := TargetSize;
  9376. { Convert the input MOVZX to a MOV if necessary }
  9377. AdjustInitialLoadAndSize;
  9378. if (InstrMax >= 0) then
  9379. begin
  9380. for Index := 0 to InstrMax do
  9381. begin
  9382. { If p_removed is true, then the original MOV/Z was removed
  9383. and removing the AND instruction may not be safe if it
  9384. appears first }
  9385. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9386. InternalError(2020112311);
  9387. if InstrList[Index].oper[0]^.typ = top_reg then
  9388. InstrList[Index].oper[0]^.reg := ThisReg;
  9389. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9390. InstrList[Index].opsize := MinSize;
  9391. end;
  9392. end;
  9393. Result := True;
  9394. end;
  9395. Exit;
  9396. end;
  9397. end;
  9398. A_SETcc:
  9399. begin
  9400. { This allows this Movx optimisation to work through the SETcc instructions
  9401. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9402. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9403. skip over these SETcc instructions). }
  9404. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9405. { Of course, break out if the current register is used }
  9406. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9407. Break
  9408. else
  9409. { We must use Continue so the instruction doesn't get added
  9410. to InstrList }
  9411. Continue;
  9412. end;
  9413. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9414. begin
  9415. if
  9416. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9417. { Has to be an exact match on the register }
  9418. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9419. (
  9420. (
  9421. (taicpu(hp1).oper[0]^.typ = top_const) and
  9422. (
  9423. (
  9424. (taicpu(hp1).opcode = A_SHL) and
  9425. (
  9426. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9427. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9428. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9429. )
  9430. ) or (
  9431. (taicpu(hp1).opcode <> A_SHL) and
  9432. (
  9433. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9434. { Is it in the negative range? }
  9435. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9436. )
  9437. )
  9438. )
  9439. ) or (
  9440. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9441. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9442. )
  9443. ) then
  9444. Break;
  9445. { Only process OR and XOR if there are only bitwise operations,
  9446. since otherwise they can too easily fool the data flow
  9447. analysis (they can cause non-linear behaviour) }
  9448. case taicpu(hp1).opcode of
  9449. A_ADD:
  9450. begin
  9451. if OrXorUsed then
  9452. { Too high a risk of non-linear behaviour that breaks DFA here }
  9453. Break
  9454. else
  9455. BitwiseOnly := False;
  9456. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9457. begin
  9458. TestValMin := TestValMin * 2;
  9459. TestValMax := TestValMax * 2;
  9460. TestValSignedMax := TestValSignedMax * 2;
  9461. end
  9462. else
  9463. begin
  9464. WorkingValue := taicpu(hp1).oper[0]^.val;
  9465. TestValMin := TestValMin + WorkingValue;
  9466. TestValMax := TestValMax + WorkingValue;
  9467. TestValSignedMax := TestValSignedMax + WorkingValue;
  9468. end;
  9469. end;
  9470. A_SUB:
  9471. begin
  9472. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9473. begin
  9474. TestValMin := 0;
  9475. TestValMax := 0;
  9476. TestValSignedMax := 0;
  9477. end
  9478. else
  9479. begin
  9480. if OrXorUsed then
  9481. { Too high a risk of non-linear behaviour that breaks DFA here }
  9482. Break
  9483. else
  9484. BitwiseOnly := False;
  9485. WorkingValue := taicpu(hp1).oper[0]^.val;
  9486. TestValMin := TestValMin - WorkingValue;
  9487. TestValMax := TestValMax - WorkingValue;
  9488. TestValSignedMax := TestValSignedMax - WorkingValue;
  9489. end;
  9490. end;
  9491. A_AND:
  9492. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9493. begin
  9494. { we might be able to go smaller if AND appears first }
  9495. if InstrMax = -1 then
  9496. case MinSize of
  9497. S_B:
  9498. ;
  9499. S_W:
  9500. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9501. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9502. begin
  9503. TryShiftDown := S_B;
  9504. TryShiftDownLimit := $FF;
  9505. end;
  9506. S_L:
  9507. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9508. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9509. begin
  9510. TryShiftDown := S_B;
  9511. TryShiftDownLimit := $FF;
  9512. end
  9513. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9514. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9515. begin
  9516. TryShiftDown := S_W;
  9517. TryShiftDownLimit := $FFFF;
  9518. end;
  9519. else
  9520. InternalError(2020112320);
  9521. end;
  9522. WorkingValue := taicpu(hp1).oper[0]^.val;
  9523. TestValMin := TestValMin and WorkingValue;
  9524. TestValMax := TestValMax and WorkingValue;
  9525. TestValSignedMax := TestValSignedMax and WorkingValue;
  9526. end;
  9527. A_OR:
  9528. begin
  9529. if not BitwiseOnly then
  9530. Break;
  9531. OrXorUsed := True;
  9532. WorkingValue := taicpu(hp1).oper[0]^.val;
  9533. TestValMin := TestValMin or WorkingValue;
  9534. TestValMax := TestValMax or WorkingValue;
  9535. TestValSignedMax := TestValSignedMax or WorkingValue;
  9536. end;
  9537. A_XOR:
  9538. begin
  9539. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9540. begin
  9541. TestValMin := 0;
  9542. TestValMax := 0;
  9543. TestValSignedMax := 0;
  9544. end
  9545. else
  9546. begin
  9547. if not BitwiseOnly then
  9548. Break;
  9549. OrXorUsed := True;
  9550. WorkingValue := taicpu(hp1).oper[0]^.val;
  9551. TestValMin := TestValMin xor WorkingValue;
  9552. TestValMax := TestValMax xor WorkingValue;
  9553. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9554. end;
  9555. end;
  9556. A_SHL:
  9557. begin
  9558. BitwiseOnly := False;
  9559. WorkingValue := taicpu(hp1).oper[0]^.val;
  9560. TestValMin := TestValMin shl WorkingValue;
  9561. TestValMax := TestValMax shl WorkingValue;
  9562. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9563. end;
  9564. A_SHR,
  9565. { The first instruction was MOVZX, so the value won't be negative }
  9566. A_SAR:
  9567. begin
  9568. if InstrMax <> -1 then
  9569. BitwiseOnly := False
  9570. else
  9571. { we might be able to go smaller if SHR appears first }
  9572. case MinSize of
  9573. S_B:
  9574. ;
  9575. S_W:
  9576. if (taicpu(hp1).oper[0]^.val >= 8) then
  9577. begin
  9578. TryShiftDown := S_B;
  9579. TryShiftDownLimit := $FF;
  9580. TryShiftDownSignedLimit := $7F;
  9581. TryShiftDownSignedLimitLower := -128;
  9582. end;
  9583. S_L:
  9584. if (taicpu(hp1).oper[0]^.val >= 24) then
  9585. begin
  9586. TryShiftDown := S_B;
  9587. TryShiftDownLimit := $FF;
  9588. TryShiftDownSignedLimit := $7F;
  9589. TryShiftDownSignedLimitLower := -128;
  9590. end
  9591. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9592. begin
  9593. TryShiftDown := S_W;
  9594. TryShiftDownLimit := $FFFF;
  9595. TryShiftDownSignedLimit := $7FFF;
  9596. TryShiftDownSignedLimitLower := -32768;
  9597. end;
  9598. else
  9599. InternalError(2020112321);
  9600. end;
  9601. WorkingValue := taicpu(hp1).oper[0]^.val;
  9602. if taicpu(hp1).opcode = A_SAR then
  9603. begin
  9604. TestValMin := SarInt64(TestValMin, WorkingValue);
  9605. TestValMax := SarInt64(TestValMax, WorkingValue);
  9606. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9607. end
  9608. else
  9609. begin
  9610. TestValMin := TestValMin shr WorkingValue;
  9611. TestValMax := TestValMax shr WorkingValue;
  9612. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9613. end;
  9614. end;
  9615. else
  9616. InternalError(2020112303);
  9617. end;
  9618. end;
  9619. (*
  9620. A_IMUL:
  9621. case taicpu(hp1).ops of
  9622. 2:
  9623. begin
  9624. if not MatchOpType(hp1, top_reg, top_reg) or
  9625. { Has to be an exact match on the register }
  9626. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9627. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9628. Break;
  9629. TestValMin := TestValMin * TestValMin;
  9630. TestValMax := TestValMax * TestValMax;
  9631. TestValSignedMax := TestValSignedMax * TestValMax;
  9632. end;
  9633. 3:
  9634. begin
  9635. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9636. { Has to be an exact match on the register }
  9637. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9638. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9639. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9640. { Is it in the negative range? }
  9641. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9642. Break;
  9643. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9644. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9645. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9646. end;
  9647. else
  9648. Break;
  9649. end;
  9650. A_IDIV:
  9651. case taicpu(hp1).ops of
  9652. 3:
  9653. begin
  9654. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9655. { Has to be an exact match on the register }
  9656. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9657. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9658. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9659. { Is it in the negative range? }
  9660. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9661. Break;
  9662. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9663. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9664. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9665. end;
  9666. else
  9667. Break;
  9668. end;
  9669. *)
  9670. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9671. begin
  9672. { If there are no instructions in between, then we might be able to make a saving }
  9673. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9674. Break;
  9675. { We have something like:
  9676. movzbw %dl,%dx
  9677. ...
  9678. movswl %dx,%edx
  9679. Change the latter to a zero-extension then enter the
  9680. A_MOVZX case branch.
  9681. }
  9682. {$ifdef x86_64}
  9683. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9684. begin
  9685. { this becomes a zero extension from 32-bit to 64-bit, but
  9686. the upper 32 bits are already zero, so just delete the
  9687. instruction }
  9688. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9689. RemoveInstruction(hp1);
  9690. Result := True;
  9691. Exit;
  9692. end
  9693. else
  9694. {$endif x86_64}
  9695. begin
  9696. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9697. taicpu(hp1).opcode := A_MOVZX;
  9698. {$ifdef x86_64}
  9699. case taicpu(hp1).opsize of
  9700. S_BQ:
  9701. begin
  9702. taicpu(hp1).opsize := S_BL;
  9703. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9704. end;
  9705. S_WQ:
  9706. begin
  9707. taicpu(hp1).opsize := S_WL;
  9708. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9709. end;
  9710. S_LQ:
  9711. begin
  9712. taicpu(hp1).opcode := A_MOV;
  9713. taicpu(hp1).opsize := S_L;
  9714. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9715. { In this instance, we need to break out because the
  9716. instruction is no longer MOVZX or MOVSXD }
  9717. Result := True;
  9718. Exit;
  9719. end;
  9720. else
  9721. ;
  9722. end;
  9723. {$endif x86_64}
  9724. Result := CompressInstructions;
  9725. Exit;
  9726. end;
  9727. end;
  9728. A_MOVZX:
  9729. begin
  9730. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  9731. Break;
  9732. if (InstrMax = -1) then
  9733. begin
  9734. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  9735. begin
  9736. { Optimise around i40003 }
  9737. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  9738. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  9739. {$ifndef x86_64}
  9740. and (
  9741. (taicpu(p).oper[0]^.typ <> top_reg) or
  9742. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  9743. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  9744. )
  9745. {$endif not x86_64}
  9746. then
  9747. begin
  9748. if (taicpu(p).oper[0]^.typ = top_reg) then
  9749. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  9750. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  9751. taicpu(p).opsize := S_BL;
  9752. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  9753. RemoveInstruction(hp1);
  9754. Result := True;
  9755. Exit;
  9756. end;
  9757. end
  9758. else
  9759. begin
  9760. { Will return false if the second parameter isn't ThisReg
  9761. (can happen on -O2 and under) }
  9762. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9763. begin
  9764. { The two MOVZX instructions are adjacent, so remove the first one }
  9765. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  9766. RemoveCurrentP(p);
  9767. Result := True;
  9768. Exit;
  9769. end;
  9770. Break;
  9771. end;
  9772. end;
  9773. Result := CompressInstructions;
  9774. Exit;
  9775. end;
  9776. else
  9777. { This includes ADC, SBB and IDIV }
  9778. Break;
  9779. end;
  9780. if not CheckOverflowConditions then
  9781. Break;
  9782. { Contains highest index (so instruction count - 1) }
  9783. Inc(InstrMax);
  9784. if InstrMax > High(InstrList) then
  9785. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9786. InstrList[InstrMax] := taicpu(hp1);
  9787. end;
  9788. end;
  9789. {$pop}
  9790. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  9791. var
  9792. hp1 : tai;
  9793. begin
  9794. Result:=false;
  9795. if (taicpu(p).ops >= 2) and
  9796. ((taicpu(p).oper[0]^.typ = top_const) or
  9797. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  9798. (taicpu(p).oper[1]^.typ = top_reg) and
  9799. ((taicpu(p).ops = 2) or
  9800. ((taicpu(p).oper[2]^.typ = top_reg) and
  9801. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  9802. GetLastInstruction(p,hp1) and
  9803. MatchInstruction(hp1,A_MOV,[]) and
  9804. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9805. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9806. begin
  9807. TransferUsedRegs(TmpUsedRegs);
  9808. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  9809. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  9810. { change
  9811. mov reg1,reg2
  9812. imul y,reg2 to imul y,reg1,reg2 }
  9813. begin
  9814. taicpu(p).ops := 3;
  9815. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  9816. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  9817. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  9818. RemoveInstruction(hp1);
  9819. result:=true;
  9820. end;
  9821. end;
  9822. end;
  9823. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  9824. var
  9825. ThisLabel: TAsmLabel;
  9826. begin
  9827. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  9828. ThisLabel.decrefs;
  9829. taicpu(p).condition := C_None;
  9830. taicpu(p).opcode := A_RET;
  9831. taicpu(p).is_jmp := false;
  9832. taicpu(p).ops := taicpu(ret_p).ops;
  9833. case taicpu(ret_p).ops of
  9834. 0:
  9835. taicpu(p).clearop(0);
  9836. 1:
  9837. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  9838. else
  9839. internalerror(2016041301);
  9840. end;
  9841. { If the original label is now dead, it might turn out that the label
  9842. immediately follows p. As a result, everything beyond it, which will
  9843. be just some final register configuration and a RET instruction, is
  9844. now dead code. [Kit] }
  9845. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9846. running RemoveDeadCodeAfterJump for each RET instruction, because
  9847. this optimisation rarely happens and most RETs appear at the end of
  9848. routines where there is nothing that can be stripped. [Kit] }
  9849. if not ThisLabel.is_used then
  9850. RemoveDeadCodeAfterJump(p);
  9851. end;
  9852. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9853. var
  9854. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9855. Unconditional, PotentialModified: Boolean;
  9856. OperPtr: POper;
  9857. NewRef: TReference;
  9858. InstrList: array of taicpu;
  9859. InstrMax, Index: Integer;
  9860. const
  9861. {$ifdef DEBUG_AOPTCPU}
  9862. SNoFlags: shortstring = ' so the flags aren''t modified';
  9863. {$else DEBUG_AOPTCPU}
  9864. SNoFlags = '';
  9865. {$endif DEBUG_AOPTCPU}
  9866. begin
  9867. Result:=false;
  9868. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9869. begin
  9870. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9871. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9872. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9873. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9874. GetNextInstruction(hp1, hp2) and
  9875. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  9876. { Change from: To:
  9877. set(C) %reg j(~C) label
  9878. test %reg,%reg/cmp $0,%reg
  9879. je label
  9880. set(C) %reg j(C) label
  9881. test %reg,%reg/cmp $0,%reg
  9882. jne label
  9883. (Also do something similar with sete/setne instead of je/jne)
  9884. }
  9885. begin
  9886. { Before we do anything else, we need to check the instructions
  9887. in between SETcc and TEST to make sure they don't modify the
  9888. FLAGS register - if -O2 or under, there won't be any
  9889. instructions between SET and TEST }
  9890. TransferUsedRegs(TmpUsedRegs);
  9891. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9892. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9893. begin
  9894. next := p;
  9895. SetLength(InstrList, 0);
  9896. InstrMax := -1;
  9897. PotentialModified := False;
  9898. { Make a note of every instruction that modifies the FLAGS
  9899. register }
  9900. while GetNextInstruction(next, next) and (next <> hp1) do
  9901. begin
  9902. if next.typ <> ait_instruction then
  9903. { GetNextInstructionUsingReg should have returned False }
  9904. InternalError(2021051701);
  9905. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  9906. begin
  9907. case taicpu(next).opcode of
  9908. A_SETcc,
  9909. A_CMOVcc,
  9910. A_Jcc:
  9911. begin
  9912. if PotentialModified then
  9913. { Not safe because the flags were modified earlier }
  9914. Exit
  9915. else
  9916. { Condition is the same as the initial SETcc, so this is safe
  9917. (don't add to instruction list though) }
  9918. Continue;
  9919. end;
  9920. A_ADD:
  9921. begin
  9922. if (taicpu(next).opsize = S_B) or
  9923. { LEA doesn't support 8-bit operands }
  9924. (taicpu(next).oper[1]^.typ <> top_reg) or
  9925. { Must write to a register }
  9926. (taicpu(next).oper[0]^.typ = top_ref) then
  9927. { Require a constant or a register }
  9928. Exit;
  9929. PotentialModified := True;
  9930. end;
  9931. A_SUB:
  9932. begin
  9933. if (taicpu(next).opsize = S_B) or
  9934. { LEA doesn't support 8-bit operands }
  9935. (taicpu(next).oper[1]^.typ <> top_reg) or
  9936. { Must write to a register }
  9937. (taicpu(next).oper[0]^.typ <> top_const) or
  9938. (taicpu(next).oper[0]^.val = $80000000) then
  9939. { Can't subtract a register with LEA - also
  9940. check that the value isn't -2^31, as this
  9941. can't be negated }
  9942. Exit;
  9943. PotentialModified := True;
  9944. end;
  9945. A_SAL,
  9946. A_SHL:
  9947. begin
  9948. if (taicpu(next).opsize = S_B) or
  9949. { LEA doesn't support 8-bit operands }
  9950. (taicpu(next).oper[1]^.typ <> top_reg) or
  9951. { Must write to a register }
  9952. (taicpu(next).oper[0]^.typ <> top_const) or
  9953. (taicpu(next).oper[0]^.val < 0) or
  9954. (taicpu(next).oper[0]^.val > 3) then
  9955. Exit;
  9956. PotentialModified := True;
  9957. end;
  9958. A_IMUL:
  9959. begin
  9960. if (taicpu(next).ops <> 3) or
  9961. (taicpu(next).oper[1]^.typ <> top_reg) or
  9962. { Must write to a register }
  9963. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  9964. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  9965. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  9966. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  9967. Exit
  9968. else
  9969. PotentialModified := True;
  9970. end;
  9971. else
  9972. { Don't know how to change this, so abort }
  9973. Exit;
  9974. end;
  9975. { Contains highest index (so instruction count - 1) }
  9976. Inc(InstrMax);
  9977. if InstrMax > High(InstrList) then
  9978. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9979. InstrList[InstrMax] := taicpu(next);
  9980. end;
  9981. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  9982. end;
  9983. if not Assigned(next) or (next <> hp1) then
  9984. { It should be equal to hp1 }
  9985. InternalError(2021051702);
  9986. { Cycle through each instruction and check to see if we can
  9987. change them to versions that don't modify the flags }
  9988. if (InstrMax >= 0) then
  9989. begin
  9990. for Index := 0 to InstrMax do
  9991. case InstrList[Index].opcode of
  9992. A_ADD:
  9993. begin
  9994. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  9995. InstrList[Index].opcode := A_LEA;
  9996. reference_reset(NewRef, 1, []);
  9997. NewRef.base := InstrList[Index].oper[1]^.reg;
  9998. if InstrList[Index].oper[0]^.typ = top_reg then
  9999. begin
  10000. NewRef.index := InstrList[Index].oper[0]^.reg;
  10001. NewRef.scalefactor := 1;
  10002. end
  10003. else
  10004. NewRef.offset := InstrList[Index].oper[0]^.val;
  10005. InstrList[Index].loadref(0, NewRef);
  10006. end;
  10007. A_SUB:
  10008. begin
  10009. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10010. InstrList[Index].opcode := A_LEA;
  10011. reference_reset(NewRef, 1, []);
  10012. NewRef.base := InstrList[Index].oper[1]^.reg;
  10013. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10014. InstrList[Index].loadref(0, NewRef);
  10015. end;
  10016. A_SHL,
  10017. A_SAL:
  10018. begin
  10019. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10020. InstrList[Index].opcode := A_LEA;
  10021. reference_reset(NewRef, 1, []);
  10022. NewRef.index := InstrList[Index].oper[1]^.reg;
  10023. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10024. InstrList[Index].loadref(0, NewRef);
  10025. end;
  10026. A_IMUL:
  10027. begin
  10028. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10029. InstrList[Index].opcode := A_LEA;
  10030. reference_reset(NewRef, 1, []);
  10031. NewRef.index := InstrList[Index].oper[1]^.reg;
  10032. case InstrList[Index].oper[0]^.val of
  10033. 2, 4, 8:
  10034. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10035. else {3, 5 and 9}
  10036. begin
  10037. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10038. NewRef.base := InstrList[Index].oper[1]^.reg;
  10039. end;
  10040. end;
  10041. InstrList[Index].loadref(0, NewRef);
  10042. end;
  10043. else
  10044. InternalError(2021051710);
  10045. end;
  10046. end;
  10047. { Mark the FLAGS register as used across this whole block }
  10048. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10049. end;
  10050. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10051. JumpC := taicpu(hp2).condition;
  10052. Unconditional := False;
  10053. if conditions_equal(JumpC, C_E) then
  10054. SetC := inverse_cond(taicpu(p).condition)
  10055. else if conditions_equal(JumpC, C_NE) then
  10056. SetC := taicpu(p).condition
  10057. else
  10058. { We've got something weird here (and inefficent) }
  10059. begin
  10060. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10061. SetC := C_NONE;
  10062. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10063. if condition_in(C_AE, JumpC) then
  10064. Unconditional := True
  10065. else
  10066. { Not sure what to do with this jump - drop out }
  10067. Exit;
  10068. end;
  10069. RemoveInstruction(hp1);
  10070. if Unconditional then
  10071. MakeUnconditional(taicpu(hp2))
  10072. else
  10073. begin
  10074. if SetC = C_NONE then
  10075. InternalError(2018061402);
  10076. taicpu(hp2).SetCondition(SetC);
  10077. end;
  10078. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10079. TmpUsedRegs }
  10080. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10081. begin
  10082. RemoveCurrentp(p, hp2);
  10083. if taicpu(hp2).opcode = A_SETcc then
  10084. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10085. else
  10086. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10087. end
  10088. else
  10089. if taicpu(hp2).opcode = A_SETcc then
  10090. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10091. else
  10092. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10093. Result := True;
  10094. end
  10095. else if
  10096. { Make sure the instructions are adjacent }
  10097. (
  10098. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10099. GetNextInstruction(p, hp1)
  10100. ) and
  10101. MatchInstruction(hp1, A_MOV, [S_B]) and
  10102. { Writing to memory is allowed }
  10103. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10104. begin
  10105. {
  10106. Watch out for sequences such as:
  10107. set(c)b %regb
  10108. movb %regb,(ref)
  10109. movb $0,1(ref)
  10110. movb $0,2(ref)
  10111. movb $0,3(ref)
  10112. Much more efficient to turn it into:
  10113. movl $0,%regl
  10114. set(c)b %regb
  10115. movl %regl,(ref)
  10116. Or:
  10117. set(c)b %regb
  10118. movzbl %regb,%regl
  10119. movl %regl,(ref)
  10120. }
  10121. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10122. GetNextInstruction(hp1, hp2) and
  10123. MatchInstruction(hp2, A_MOV, [S_B]) and
  10124. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10125. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10126. begin
  10127. { Don't do anything else except set Result to True }
  10128. end
  10129. else
  10130. begin
  10131. if taicpu(p).oper[0]^.typ = top_reg then
  10132. begin
  10133. TransferUsedRegs(TmpUsedRegs);
  10134. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10135. end;
  10136. { If it's not a register, it's a memory address }
  10137. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10138. begin
  10139. { Even if the register is still in use, we can minimise the
  10140. pipeline stall by changing the MOV into another SETcc. }
  10141. taicpu(hp1).opcode := A_SETcc;
  10142. taicpu(hp1).condition := taicpu(p).condition;
  10143. if taicpu(hp1).oper[1]^.typ = top_ref then
  10144. begin
  10145. { Swapping the operand pointers like this is probably a
  10146. bit naughty, but it is far faster than using loadoper
  10147. to transfer the reference from oper[1] to oper[0] if
  10148. you take into account the extra procedure calls and
  10149. the memory allocation and deallocation required }
  10150. OperPtr := taicpu(hp1).oper[1];
  10151. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10152. taicpu(hp1).oper[0] := OperPtr;
  10153. end
  10154. else
  10155. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10156. taicpu(hp1).clearop(1);
  10157. taicpu(hp1).ops := 1;
  10158. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10159. end
  10160. else
  10161. begin
  10162. if taicpu(hp1).oper[1]^.typ = top_reg then
  10163. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10164. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10165. RemoveInstruction(hp1);
  10166. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10167. end
  10168. end;
  10169. Result := True;
  10170. end;
  10171. end;
  10172. end;
  10173. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10174. var
  10175. hp1: tai;
  10176. Count: Integer;
  10177. OrigLabel: TAsmLabel;
  10178. begin
  10179. result := False;
  10180. { Sometimes, the optimisations below can permit this }
  10181. RemoveDeadCodeAfterJump(p);
  10182. 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
  10183. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10184. begin
  10185. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10186. { Also a side-effect of optimisations }
  10187. if CollapseZeroDistJump(p, OrigLabel) then
  10188. begin
  10189. Result := True;
  10190. Exit;
  10191. end;
  10192. hp1 := GetLabelWithSym(OrigLabel);
  10193. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10194. begin
  10195. if taicpu(hp1).opcode = A_RET then
  10196. begin
  10197. {
  10198. change
  10199. jmp .L1
  10200. ...
  10201. .L1:
  10202. ret
  10203. into
  10204. ret
  10205. }
  10206. begin
  10207. ConvertJumpToRET(p, hp1);
  10208. result:=true;
  10209. end;
  10210. end
  10211. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10212. not (cs_opt_size in current_settings.optimizerswitches) and
  10213. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10214. begin
  10215. Result := True;
  10216. Exit;
  10217. end;
  10218. end;
  10219. end;
  10220. end;
  10221. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  10222. begin
  10223. CanBeCMOV:=assigned(p) and
  10224. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10225. (taicpu(p).oper[1]^.typ = top_reg) and
  10226. (
  10227. (taicpu(p).oper[0]^.typ = top_reg) or
  10228. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10229. it is not expected that this can cause a seg. violation }
  10230. (
  10231. (taicpu(p).oper[0]^.typ = top_ref) and
  10232. { TODO: Can we detect which references become constants at this
  10233. stage so we don't have to do a blanket ban? }
  10234. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10235. IsRefSafe(taicpu(p).oper[0]^.ref)
  10236. )
  10237. );
  10238. end;
  10239. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10240. begin
  10241. { Update integer registers, ignoring deallocations }
  10242. repeat
  10243. while assigned(p) and
  10244. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10245. (p.typ = ait_label) or
  10246. ((p.typ = ait_marker) and
  10247. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10248. p := tai(p.next);
  10249. while assigned(p) and
  10250. (p.typ=ait_RegAlloc) Do
  10251. begin
  10252. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10253. begin
  10254. case tai_regalloc(p).ratype of
  10255. ra_alloc :
  10256. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10257. else
  10258. ;
  10259. end;
  10260. end;
  10261. p := tai(p.next);
  10262. end;
  10263. until not(assigned(p)) or
  10264. (not(p.typ in SkipInstr) and
  10265. not((p.typ = ait_label) and
  10266. labelCanBeSkipped(tai_label(p))));
  10267. end;
  10268. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10269. var
  10270. hp1,hp2: tai;
  10271. carryadd_opcode : TAsmOp;
  10272. symbol: TAsmSymbol;
  10273. increg, tmpreg: TRegister;
  10274. {$ifndef i8086}
  10275. { Code and variables specific to CMOV optimisations }
  10276. hp3,hp4,hp5,
  10277. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10278. l, c, w, x : Longint;
  10279. condition, second_condition : TAsmCond;
  10280. FoundMatchingJump, RegMatch: Boolean;
  10281. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10282. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10283. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10284. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10285. new register to store the constant }
  10286. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10287. var
  10288. RegSize: TSubRegister;
  10289. CurrentVal: TCGInt;
  10290. NewReg: TRegister;
  10291. X: ShortInt;
  10292. begin
  10293. Result := False;
  10294. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10295. Exit;
  10296. if StoredCount >= MAX_CMOV_REGISTERS then
  10297. { Arrays are full }
  10298. Exit;
  10299. { Remember that CMOV can't encode 8-bit registers }
  10300. case taicpu(p).opsize of
  10301. S_W:
  10302. RegSize := R_SUBW;
  10303. S_L:
  10304. RegSize := R_SUBD;
  10305. S_Q:
  10306. RegSize := R_SUBQ;
  10307. else
  10308. InternalError(2021100401);
  10309. end;
  10310. { See if the value has already been reserved for another CMOV instruction }
  10311. CurrentVal := taicpu(p).oper[0]^.val;
  10312. for X := 0 to StoredCount - 1 do
  10313. if ConstVals[X] = CurrentVal then
  10314. begin
  10315. ConstRegs[StoredCount] := ConstRegs[X];
  10316. ConstVals[StoredCount] := CurrentVal;
  10317. Result := True;
  10318. Inc(StoredCount);
  10319. { Don't increase CMOVCount this time, since we're re-using a register }
  10320. Exit;
  10321. end;
  10322. NewReg := GetIntRegisterBetween(RegSize, TmpUsedRegs, search_start_p, stop_search_p, True);
  10323. if NewReg = NR_NO then
  10324. { No free registers }
  10325. Exit;
  10326. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10327. up vying for the same register }
  10328. IncludeRegInUsedRegs(NewReg, TmpUsedRegs);
  10329. ConstRegs[StoredCount] := NewReg;
  10330. ConstVals[StoredCount] := CurrentVal;
  10331. Inc(StoredCount);
  10332. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10333. MOV required adds complexity and will cause diminishing returns
  10334. sooner than normal. This is more of an approximate weighting than
  10335. anything else. }
  10336. Inc(CMOVCount);
  10337. Result := True;
  10338. end;
  10339. {$endif i8086}
  10340. begin
  10341. result:=false;
  10342. if GetNextInstruction(p,hp1) then
  10343. begin
  10344. if (hp1.typ=ait_label) then
  10345. begin
  10346. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10347. Exit;
  10348. end
  10349. else if (hp1.typ<>ait_instruction) then
  10350. Exit;
  10351. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10352. if (
  10353. (
  10354. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10355. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10356. (Taicpu(hp1).oper[0]^.val=1)
  10357. ) or
  10358. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10359. ) and
  10360. GetNextInstruction(hp1,hp2) and
  10361. SkipAligns(hp2, hp2) and
  10362. (hp2.typ = ait_label) and
  10363. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10364. { jb @@1 cmc
  10365. inc/dec operand --> adc/sbb operand,0
  10366. @@1:
  10367. ... and ...
  10368. jnb @@1
  10369. inc/dec operand --> adc/sbb operand,0
  10370. @@1: }
  10371. begin
  10372. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10373. begin
  10374. case taicpu(hp1).opcode of
  10375. A_INC,
  10376. A_ADD:
  10377. carryadd_opcode:=A_ADC;
  10378. A_DEC,
  10379. A_SUB:
  10380. carryadd_opcode:=A_SBB;
  10381. else
  10382. InternalError(2021011001);
  10383. end;
  10384. Taicpu(p).clearop(0);
  10385. Taicpu(p).ops:=0;
  10386. Taicpu(p).is_jmp:=false;
  10387. Taicpu(p).opcode:=A_CMC;
  10388. Taicpu(p).condition:=C_NONE;
  10389. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10390. Taicpu(hp1).ops:=2;
  10391. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10392. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10393. else
  10394. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10395. Taicpu(hp1).loadconst(0,0);
  10396. Taicpu(hp1).opcode:=carryadd_opcode;
  10397. result:=true;
  10398. exit;
  10399. end
  10400. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10401. begin
  10402. case taicpu(hp1).opcode of
  10403. A_INC,
  10404. A_ADD:
  10405. carryadd_opcode:=A_ADC;
  10406. A_DEC,
  10407. A_SUB:
  10408. carryadd_opcode:=A_SBB;
  10409. else
  10410. InternalError(2021011002);
  10411. end;
  10412. Taicpu(hp1).ops:=2;
  10413. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10414. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10415. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10416. else
  10417. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10418. Taicpu(hp1).loadconst(0,0);
  10419. Taicpu(hp1).opcode:=carryadd_opcode;
  10420. RemoveCurrentP(p, hp1);
  10421. result:=true;
  10422. exit;
  10423. end
  10424. {
  10425. jcc @@1 setcc tmpreg
  10426. inc/dec/add/sub operand -> (movzx tmpreg)
  10427. @@1: add/sub tmpreg,operand
  10428. While this increases code size slightly, it makes the code much faster if the
  10429. jump is unpredictable
  10430. }
  10431. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10432. begin
  10433. { search for an available register which is volatile }
  10434. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10435. if increg <> NR_NO then
  10436. begin
  10437. { We don't need to check if tmpreg is in hp1 or not, because
  10438. it will be marked as in use at p (if not, this is
  10439. indictive of a compiler bug). }
  10440. TAsmLabel(symbol).decrefs;
  10441. Taicpu(p).clearop(0);
  10442. Taicpu(p).ops:=1;
  10443. Taicpu(p).is_jmp:=false;
  10444. Taicpu(p).opcode:=A_SETcc;
  10445. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10446. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10447. Taicpu(p).loadreg(0,increg);
  10448. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10449. begin
  10450. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10451. R_SUBW:
  10452. begin
  10453. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10454. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10455. end;
  10456. R_SUBD:
  10457. begin
  10458. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10459. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10460. end;
  10461. {$ifdef x86_64}
  10462. R_SUBQ:
  10463. begin
  10464. { MOVZX doesn't have a 64-bit variant, because
  10465. the 32-bit version implicitly zeroes the
  10466. upper 32-bits of the destination register }
  10467. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10468. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10469. setsubreg(tmpreg, R_SUBQ);
  10470. end;
  10471. {$endif x86_64}
  10472. else
  10473. Internalerror(2020030601);
  10474. end;
  10475. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10476. asml.InsertAfter(hp2,p);
  10477. end
  10478. else
  10479. tmpreg := increg;
  10480. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10481. begin
  10482. Taicpu(hp1).ops:=2;
  10483. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10484. end;
  10485. Taicpu(hp1).loadreg(0,tmpreg);
  10486. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10487. Result := True;
  10488. { p is no longer a Jcc instruction, so exit }
  10489. Exit;
  10490. end;
  10491. end;
  10492. end;
  10493. { Detect the following:
  10494. jmp<cond> @Lbl1
  10495. jmp @Lbl2
  10496. ...
  10497. @Lbl1:
  10498. ret
  10499. Change to:
  10500. jmp<inv_cond> @Lbl2
  10501. ret
  10502. }
  10503. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10504. begin
  10505. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10506. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10507. MatchInstruction(hp2,A_RET,[S_NO]) then
  10508. begin
  10509. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10510. { Change label address to that of the unconditional jump }
  10511. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10512. TAsmLabel(symbol).DecRefs;
  10513. taicpu(hp1).opcode := A_RET;
  10514. taicpu(hp1).is_jmp := false;
  10515. taicpu(hp1).ops := taicpu(hp2).ops;
  10516. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10517. case taicpu(hp2).ops of
  10518. 0:
  10519. taicpu(hp1).clearop(0);
  10520. 1:
  10521. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10522. else
  10523. internalerror(2016041302);
  10524. end;
  10525. end;
  10526. {$ifndef i8086}
  10527. end
  10528. {
  10529. convert
  10530. j<c> .L1
  10531. mov 1,reg
  10532. jmp .L2
  10533. .L1
  10534. mov 0,reg
  10535. .L2
  10536. into
  10537. mov 0,reg
  10538. set<not(c)> reg
  10539. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10540. would destroy the flag contents
  10541. }
  10542. else if MatchInstruction(hp1,A_MOV,[]) and
  10543. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10544. {$ifdef i386}
  10545. (
  10546. { Under i386, ESI, EDI, EBP and ESP
  10547. don't have an 8-bit representation }
  10548. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10549. ) and
  10550. {$endif i386}
  10551. (taicpu(hp1).oper[0]^.val=1) and
  10552. GetNextInstruction(hp1,hp2) and
  10553. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10554. GetNextInstruction(hp2,hp3) and
  10555. { skip align }
  10556. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10557. (hp3.typ=ait_label) and
  10558. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10559. (tai_label(hp3).labsym.getrefs=1) and
  10560. GetNextInstruction(hp3,hp4) and
  10561. MatchInstruction(hp4,A_MOV,[]) and
  10562. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10563. (taicpu(hp4).oper[0]^.val=0) and
  10564. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10565. GetNextInstruction(hp4,hp5) and
  10566. (hp5.typ=ait_label) and
  10567. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10568. (tai_label(hp5).labsym.getrefs=1) then
  10569. begin
  10570. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10571. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10572. { remove last label }
  10573. RemoveInstruction(hp5);
  10574. { remove second label }
  10575. RemoveInstruction(hp3);
  10576. { if align is present remove it }
  10577. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10578. RemoveInstruction(hp3);
  10579. { remove jmp }
  10580. RemoveInstruction(hp2);
  10581. if taicpu(hp1).opsize=S_B then
  10582. RemoveInstruction(hp1)
  10583. else
  10584. taicpu(hp1).loadconst(0,0);
  10585. taicpu(hp4).opcode:=A_SETcc;
  10586. taicpu(hp4).opsize:=S_B;
  10587. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10588. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10589. taicpu(hp4).opercnt:=1;
  10590. taicpu(hp4).ops:=1;
  10591. taicpu(hp4).freeop(1);
  10592. RemoveCurrentP(p);
  10593. Result:=true;
  10594. exit;
  10595. end
  10596. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  10597. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  10598. begin
  10599. { check for
  10600. jCC xxx
  10601. <several movs>
  10602. xxx:
  10603. Also spot:
  10604. Jcc xxx
  10605. <several movs>
  10606. jmp xxx
  10607. Change to:
  10608. <several cmovs with inverted condition>
  10609. jmp xxx (only for the 2nd case)
  10610. }
  10611. hp2 := p;
  10612. hp_lblxxx := hp1;
  10613. hp_flagalloc := nil;
  10614. hp_stop := nil;
  10615. FoundMatchingJump := False;
  10616. { Remember the first instruction in the first block of MOVs }
  10617. hpmov1 := hp1;
  10618. TransferUsedRegs(TmpUsedRegs);
  10619. while assigned(hp_lblxxx) and
  10620. { stop on labels }
  10621. (hp_lblxxx.typ <> ait_label) do
  10622. begin
  10623. { Keep track of all integer registers that are used }
  10624. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  10625. if hp_lblxxx.typ = ait_instruction then
  10626. begin
  10627. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  10628. IsJumpToLabel(taicpu(hp_lblxxx)) then
  10629. begin
  10630. hp_stop := hp_lblxxx;
  10631. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  10632. begin
  10633. { We found Jcc xxx; <several movs>; Jmp xxx }
  10634. FoundMatchingJump := True;
  10635. Break;
  10636. end;
  10637. { If it's not the jump we're looking for, it's
  10638. possibly the "if..else" variant }
  10639. end
  10640. { Check to see if we have a valid MOV instruction instead }
  10641. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  10642. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  10643. Break
  10644. else
  10645. { This will be a valid MOV }
  10646. hp_stop := hp_lblxxx;
  10647. end;
  10648. hp2 := hp_lblxxx;
  10649. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  10650. end;
  10651. { Just make sure the last MOV is included if there's no jump }
  10652. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  10653. hp_stop := hp_lblxxx;
  10654. { Note, the logic behind using hp_stop over hp_lblxxx in the
  10655. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  10656. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  10657. jmp yyy; xxx:; movs; yyy:" variation }
  10658. if assigned(hp_lblxxx) and
  10659. (
  10660. { If we found JMP xxx, we don't actually need a label
  10661. (hp_lblxxx is the JMP instruction instead) }
  10662. FoundMatchingJump or
  10663. { Make sure we actually have the right label }
  10664. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  10665. ) then
  10666. begin
  10667. { Use TmpUsedRegs to track registers that we reserve }
  10668. { When allocating temporary registers, try to look one
  10669. instruction back, as defining them before a CMP or TEST
  10670. instruction will be faster, and also avoid picking a
  10671. register that was only just deallocated }
  10672. if GetLastInstruction(p, hp_prev) and
  10673. 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
  10674. begin
  10675. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  10676. for l := 0 to 1 do
  10677. with taicpu(hp_prev).oper[l]^ do
  10678. case typ of
  10679. top_reg:
  10680. if getregtype(reg) = R_INTREGISTER then
  10681. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  10682. top_ref:
  10683. begin
  10684. if
  10685. {$ifdef x86_64}
  10686. (ref^.base <> NR_RIP) and
  10687. {$endif x86_64}
  10688. (ref^.base <> NR_NO) then
  10689. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  10690. if (ref^.index <> NR_NO) then
  10691. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  10692. end
  10693. else
  10694. ;
  10695. end;
  10696. { When inserting instructions before hp_prev, try to insert
  10697. them before the allocation of the FLAGS register }
  10698. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  10699. { If not found, set it equal to hp_prev so it's something sensible }
  10700. hp_flagalloc := hp_prev;
  10701. hp_prev2 := nil;
  10702. { When dealing with a comparison against zero, take
  10703. note of the instruction before it to see if we can
  10704. move instructions further back in order to benefit
  10705. PostPeepholeOptTestOr.
  10706. }
  10707. if (
  10708. (
  10709. (taicpu(hp_prev).opcode = A_CMP) and
  10710. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  10711. ) or
  10712. (
  10713. (taicpu(hp_prev).opcode = A_TEST) and
  10714. (
  10715. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  10716. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  10717. )
  10718. )
  10719. ) and
  10720. GetLastInstruction(hp_prev, hp_prev2) then
  10721. begin
  10722. if (hp_prev2.typ = ait_instruction) and
  10723. { These instructions set the zero flag if the result is zero }
  10724. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  10725. begin
  10726. { Also mark all the registers in this previous instruction
  10727. as 'in use', even if they've just been deallocated }
  10728. for l := 0 to 1 do
  10729. with taicpu(hp_prev2).oper[l]^ do
  10730. case typ of
  10731. top_reg:
  10732. if getregtype(reg) = R_INTREGISTER then
  10733. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  10734. top_ref:
  10735. begin
  10736. if
  10737. {$ifdef x86_64}
  10738. (ref^.base <> NR_RIP) and
  10739. {$endif x86_64}
  10740. (ref^.base <> NR_NO) then
  10741. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  10742. if (ref^.index <> NR_NO) then
  10743. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  10744. end
  10745. else
  10746. ;
  10747. end;
  10748. end
  10749. else
  10750. { Unsuitable instruction }
  10751. hp_prev2 := nil;
  10752. end;
  10753. end
  10754. else
  10755. begin
  10756. hp_prev := p;
  10757. { When inserting instructions before hp_prev, try to insert
  10758. them before the allocation of the FLAGS register }
  10759. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  10760. { If not found, set it equal to p so it's something sensible }
  10761. hp_flagalloc := p;
  10762. hp_prev2 := nil;
  10763. end;
  10764. l := 0;
  10765. c := 0;
  10766. { Initialise RegWrites, ConstRegs and ConstVals }
  10767. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  10768. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  10769. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  10770. while assigned(hp1) and
  10771. { Stop on the label we found }
  10772. (hp1 <> hp_lblxxx) do
  10773. begin
  10774. case hp1.typ of
  10775. ait_instruction:
  10776. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  10777. begin
  10778. if CanBeCMOV(hp1) then
  10779. Inc(l)
  10780. else if not (cs_opt_size in current_settings.optimizerswitches) and
  10781. { CMOV with constants grows the code size }
  10782. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  10783. begin
  10784. { Register was reserved by TryCMOVConst and
  10785. stored on ConstRegs[c] }
  10786. end
  10787. else
  10788. Break;
  10789. end
  10790. else
  10791. Break;
  10792. else
  10793. ;
  10794. end;
  10795. GetNextInstruction(hp1,hp1);
  10796. end;
  10797. if (hp1 = hp_lblxxx) then
  10798. begin
  10799. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  10800. begin
  10801. { Repurpose TmpUsedRegs to mark registers that we've defined }
  10802. TmpUsedRegs[R_INTREGISTER].Clear;
  10803. x := 0;
  10804. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  10805. condition := inverse_cond(taicpu(p).condition);
  10806. UpdateUsedRegs(tai(p.next));
  10807. hp1 := hpmov1;
  10808. repeat
  10809. if not Assigned(hp1) then
  10810. InternalError(2018062900);
  10811. if (hp1.typ = ait_instruction) then
  10812. begin
  10813. { Extra safeguard }
  10814. if (taicpu(hp1).opcode <> A_MOV) then
  10815. InternalError(2018062901);
  10816. if taicpu(hp1).oper[0]^.typ = top_const then
  10817. begin
  10818. if x >= MAX_CMOV_REGISTERS then
  10819. InternalError(2021100410);
  10820. { If it's in TmpUsedRegs, then this register
  10821. is being used more than once and hence has
  10822. already had its value defined (it gets
  10823. added to UsedRegs through AllocRegBetween
  10824. below) }
  10825. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  10826. begin
  10827. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  10828. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  10829. asml.InsertBefore(hp_new, hp_flagalloc);
  10830. if Assigned(hp_prev2) then
  10831. TrySwapMovOp(hp_prev2, hp_new);
  10832. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  10833. end
  10834. else
  10835. { We just need an instruction between hp_prev and hp1
  10836. where we know the register is marked as in use }
  10837. hp_new := hpmov1;
  10838. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  10839. taicpu(hp1).loadreg(0, ConstRegs[x]);
  10840. Inc(x);
  10841. end;
  10842. taicpu(hp1).opcode := A_CMOVcc;
  10843. taicpu(hp1).condition := condition;
  10844. end;
  10845. UpdateUsedRegs(tai(hp1.next));
  10846. GetNextInstruction(hp1, hp1);
  10847. until (hp1 = hp_lblxxx);
  10848. hp2 := hp_lblxxx;
  10849. repeat
  10850. if not Assigned(hp2) then
  10851. InternalError(2018062910);
  10852. case hp2.typ of
  10853. ait_label:
  10854. { What we expected - break out of the loop (it won't be a dead label at the top of
  10855. a cluster because that was optimised at an earlier stage) }
  10856. Break;
  10857. ait_align:
  10858. { Go to the next entry until a label is found (may be multiple aligns before it) }
  10859. begin
  10860. hp2 := tai(hp2.Next);
  10861. Continue;
  10862. end;
  10863. ait_instruction:
  10864. begin
  10865. if taicpu(hp2).opcode<>A_JMP then
  10866. InternalError(2018062912);
  10867. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  10868. Break;
  10869. end
  10870. else
  10871. begin
  10872. { Might be a comment or temporary allocation entry }
  10873. if not (hp2.typ in SkipInstr) then
  10874. InternalError(2018062911);
  10875. hp2 := tai(hp2.Next);
  10876. Continue;
  10877. end;
  10878. end;
  10879. until False;
  10880. { Now we can safely decrement the reference count }
  10881. tasmlabel(symbol).decrefs;
  10882. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  10883. { Remove the original jump }
  10884. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  10885. if hp2.typ=ait_instruction then
  10886. begin
  10887. p := hp2;
  10888. Result := True;
  10889. end
  10890. else
  10891. begin
  10892. UpdateUsedRegs(tai(hp2.next));
  10893. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  10894. { Remove the label if this is its final reference }
  10895. if (tasmlabel(symbol).getrefs=0) then
  10896. begin
  10897. { Make sure the aligns get stripped too }
  10898. hp1 := tai(hp_lblxxx.Previous);
  10899. while Assigned(hp1) and (hp1.typ = ait_align) do
  10900. begin
  10901. hp_lblxxx := hp1;
  10902. hp1 := tai(hp_lblxxx.Previous);
  10903. end;
  10904. StripLabelFast(hp_lblxxx);
  10905. end;
  10906. end;
  10907. Exit;
  10908. end;
  10909. end
  10910. else if assigned(hp_lblxxx) and
  10911. { check further for
  10912. jCC xxx
  10913. <several movs 1>
  10914. jmp yyy
  10915. xxx:
  10916. <several movs 2>
  10917. yyy:
  10918. }
  10919. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  10920. { hp1 should be pointing to jmp yyy }
  10921. MatchInstruction(hp1, A_JMP, []) and
  10922. { real label and jump, no further references to the
  10923. label are allowed }
  10924. (TAsmLabel(symbol).getrefs=1) and
  10925. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  10926. begin
  10927. hp_jump := hp1;
  10928. { Don't set c to zero }
  10929. l := 0;
  10930. w := 0;
  10931. GetNextInstruction(hp_lblxxx, hpmov2);
  10932. hp2 := hp_lblxxx;
  10933. hp_lblyyy := hpmov2;
  10934. while assigned(hp_lblyyy) and
  10935. { stop on labels }
  10936. (hp_lblyyy.typ <> ait_label) do
  10937. begin
  10938. { Keep track of all integer registers that are used }
  10939. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  10940. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  10941. Break;
  10942. hp2 := hp_lblyyy;
  10943. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  10944. end;
  10945. { Analyse the second batch of MOVs to see if the setup is valid }
  10946. hp1 := hpmov2;
  10947. while assigned(hp1) and
  10948. (hp1 <> hp_lblyyy) do
  10949. begin
  10950. case hp1.typ of
  10951. ait_instruction:
  10952. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  10953. begin
  10954. if CanBeCMOV(hp1) then
  10955. Inc(l)
  10956. else if not (cs_opt_size in current_settings.optimizerswitches)
  10957. { CMOV with constants grows the code size }
  10958. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  10959. begin
  10960. { Register was reserved by TryCMOVConst and
  10961. stored on ConstRegs[c] }
  10962. end
  10963. else
  10964. Break;
  10965. end
  10966. else
  10967. Break;
  10968. else
  10969. ;
  10970. end;
  10971. GetNextInstruction(hp1,hp1);
  10972. end;
  10973. { Repurpose TmpUsedRegs to mark registers that we've defined }
  10974. TmpUsedRegs[R_INTREGISTER].Clear;
  10975. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  10976. (hp1 = hp_lblyyy) and
  10977. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  10978. begin
  10979. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  10980. second_condition := taicpu(p).condition;
  10981. condition := inverse_cond(taicpu(p).condition);
  10982. UpdateUsedRegs(tai(p.next));
  10983. { Scan through the first set of MOVs to update UsedRegs,
  10984. but don't process them yet }
  10985. hp1 := hpmov1;
  10986. repeat
  10987. if not Assigned(hp1) then
  10988. InternalError(2018062901);
  10989. UpdateUsedRegs(tai(hp1.next));
  10990. GetNextInstruction(hp1, hp1);
  10991. until (hp1 = hp_lblxxx);
  10992. UpdateUsedRegs(tai(hp_lblxxx.next));
  10993. { Process the second set of MOVs first,
  10994. because if a destination register is
  10995. shared between the first and second MOV
  10996. sets, it is more efficient to turn the
  10997. first one into a MOV instruction and place
  10998. it before the CMP if possible, but we
  10999. won't know which registers are shared
  11000. until we've processed at least one list,
  11001. so we might as well make it the second
  11002. one since that won't be modified again. }
  11003. hp1 := hpmov2;
  11004. repeat
  11005. if not Assigned(hp1) then
  11006. InternalError(2018062902);
  11007. if (hp1.typ = ait_instruction) then
  11008. begin
  11009. { Extra safeguard }
  11010. if (taicpu(hp1).opcode <> A_MOV) then
  11011. InternalError(2018062903);
  11012. if taicpu(hp1).oper[0]^.typ = top_const then
  11013. begin
  11014. RegMatch := False;
  11015. for x := 0 to c - 1 do
  11016. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11017. begin
  11018. RegMatch := True;
  11019. { If it's in TmpUsedRegs, then this register
  11020. is being used more than once and hence has
  11021. already had its value defined (it gets
  11022. added to UsedRegs through AllocRegBetween
  11023. below) }
  11024. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11025. begin
  11026. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11027. asml.InsertBefore(hp_new, hp_flagalloc);
  11028. if Assigned(hp_prev2) then
  11029. TrySwapMovOp(hp_prev2, hp_new);
  11030. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11031. end
  11032. else
  11033. { We just need an instruction between hp_prev and hp1
  11034. where we know the register is marked as in use }
  11035. hp_new := hpmov2;
  11036. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11037. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11038. Break;
  11039. end;
  11040. if not RegMatch then
  11041. InternalError(2021100411);
  11042. end;
  11043. taicpu(hp1).opcode := A_CMOVcc;
  11044. taicpu(hp1).condition := second_condition;
  11045. { Store these writes to search for
  11046. duplicates later on }
  11047. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11048. Inc(w);
  11049. end;
  11050. UpdateUsedRegs(tai(hp1.next));
  11051. GetNextInstruction(hp1, hp1);
  11052. until (hp1 = hp_lblyyy);
  11053. { Now do the first set of MOVs }
  11054. hp1 := hpmov1;
  11055. repeat
  11056. if not Assigned(hp1) then
  11057. InternalError(2018062904);
  11058. if (hp1.typ = ait_instruction) then
  11059. begin
  11060. RegMatch := False;
  11061. { Extra safeguard }
  11062. if (taicpu(hp1).opcode <> A_MOV) then
  11063. InternalError(2018062905);
  11064. { Search through the RegWrites list to see
  11065. if there are any opposing CMOV pairs that
  11066. write to the same register }
  11067. for x := 0 to w - 1 do
  11068. if RegWrites[x] = taicpu(hp1).oper[1]^.reg then
  11069. begin
  11070. { We have a match. Move this instruction
  11071. right to the top }
  11072. hp2 := hp1;
  11073. { Move ahead in preparation }
  11074. GetNextInstruction(hp1, hp1);
  11075. asml.Remove(hp2);
  11076. asml.InsertAfter(hp2, hp_prev);
  11077. { Note we can't use the trick of inserting before hp_prev
  11078. and then calling TrySwapMovOp with hp_prev2, like with
  11079. the MOV imm,reg optimisations, because hp2 may share a
  11080. register with the comparison }
  11081. if (hp_prev <> p) then
  11082. TrySwapMovCmp(hp_prev, hp2);
  11083. RegMatch := True;
  11084. Break;
  11085. end;
  11086. if RegMatch then
  11087. Continue;
  11088. if taicpu(hp1).oper[0]^.typ = top_const then
  11089. begin
  11090. RegMatch := False;
  11091. for x := 0 to c - 1 do
  11092. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11093. begin
  11094. RegMatch := True;
  11095. { If it's in TmpUsedRegs, then this register
  11096. is being used more than once and hence has
  11097. already had its value defined (it gets
  11098. added to UsedRegs through AllocRegBetween
  11099. below) }
  11100. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11101. begin
  11102. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11103. asml.InsertBefore(hp_new, hp_flagalloc);
  11104. if Assigned(hp_prev2) then
  11105. TrySwapMovOp(hp_prev2, hp_new);
  11106. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11107. end
  11108. else
  11109. { We just need an instruction between hp_prev and hp1
  11110. where we know the register is marked as in use }
  11111. hp_new := hpmov1;
  11112. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11113. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11114. Break;
  11115. end;
  11116. if not RegMatch then
  11117. InternalError(2021100412);
  11118. end;
  11119. taicpu(hp1).opcode := A_CMOVcc;
  11120. taicpu(hp1).condition := condition;
  11121. end;
  11122. GetNextInstruction(hp1, hp1);
  11123. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11124. UpdateUsedRegs(tai(hp_jump.next));
  11125. UpdateUsedRegs(tai(hp_lblyyy.next));
  11126. { Get first instruction after label }
  11127. hp1 := p;
  11128. GetNextInstruction(hp_lblyyy, p);
  11129. { Don't dereference yet, as doing so will cause
  11130. GetNextInstruction to skip the label and
  11131. optional align marker. [Kit] }
  11132. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11133. { remove Jcc }
  11134. RemoveInstruction(hp1);
  11135. { Now we can safely decrement it }
  11136. tasmlabel(symbol).decrefs;
  11137. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11138. { Make sure the aligns get stripped too }
  11139. hp1 := tai(hp_lblxxx.Previous);
  11140. while Assigned(hp1) and (hp1.typ = ait_align) do
  11141. begin
  11142. hp_lblxxx := hp1;
  11143. hp1 := tai(hp_lblxxx.Previous);
  11144. end;
  11145. StripLabelFast(hp_lblxxx);
  11146. { remove jmp }
  11147. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11148. RemoveInstruction(hp_jump);
  11149. { As before, now we can safely decrement it }
  11150. TAsmLabel(symbol).decrefs;
  11151. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11152. if TAsmLabel(symbol).getrefs = 0 then
  11153. begin
  11154. { Make sure the aligns get stripped too }
  11155. hp1 := tai(hp_lblyyy.Previous);
  11156. while Assigned(hp1) and (hp1.typ = ait_align) do
  11157. begin
  11158. hp_lblyyy := hp1;
  11159. hp1 := tai(hp_lblyyy.Previous);
  11160. end;
  11161. StripLabelFast(hp_lblyyy);
  11162. end;
  11163. if Assigned(p) then
  11164. result := True;
  11165. exit;
  11166. end;
  11167. end;
  11168. end;
  11169. {$endif i8086}
  11170. end;
  11171. end;
  11172. end;
  11173. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11174. var
  11175. hp1,hp2,hp3: tai;
  11176. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11177. NewSize: TOpSize;
  11178. NewRegSize: TSubRegister;
  11179. Limit: TCgInt;
  11180. SwapOper: POper;
  11181. begin
  11182. result:=false;
  11183. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11184. GetNextInstruction(p,hp1) and
  11185. (hp1.typ = ait_instruction);
  11186. if reg_and_hp1_is_instr and
  11187. (
  11188. (taicpu(hp1).opcode <> A_LEA) or
  11189. { If the LEA instruction can be converted into an arithmetic instruction,
  11190. it may be possible to then fold it. }
  11191. (
  11192. { If the flags register is in use, don't change the instruction
  11193. to an ADD otherwise this will scramble the flags. [Kit] }
  11194. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11195. ConvertLEA(taicpu(hp1))
  11196. )
  11197. ) and
  11198. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11199. GetNextInstruction(hp1,hp2) and
  11200. MatchInstruction(hp2,A_MOV,[]) and
  11201. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11202. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11203. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11204. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11205. {$ifdef i386}
  11206. { not all registers have byte size sub registers on i386 }
  11207. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11208. {$endif i386}
  11209. (((taicpu(hp1).ops=2) and
  11210. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11211. ((taicpu(hp1).ops=1) and
  11212. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11213. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11214. begin
  11215. { change movsX/movzX reg/ref, reg2
  11216. add/sub/or/... reg3/$const, reg2
  11217. mov reg2 reg/ref
  11218. to add/sub/or/... reg3/$const, reg/ref }
  11219. { by example:
  11220. movswl %si,%eax movswl %si,%eax p
  11221. decl %eax addl %edx,%eax hp1
  11222. movw %ax,%si movw %ax,%si hp2
  11223. ->
  11224. movswl %si,%eax movswl %si,%eax p
  11225. decw %eax addw %edx,%eax hp1
  11226. movw %ax,%si movw %ax,%si hp2
  11227. }
  11228. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11229. {
  11230. ->
  11231. movswl %si,%eax movswl %si,%eax p
  11232. decw %si addw %dx,%si hp1
  11233. movw %ax,%si movw %ax,%si hp2
  11234. }
  11235. case taicpu(hp1).ops of
  11236. 1:
  11237. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11238. 2:
  11239. begin
  11240. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11241. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11242. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11243. end;
  11244. else
  11245. internalerror(2008042702);
  11246. end;
  11247. {
  11248. ->
  11249. decw %si addw %dx,%si p
  11250. }
  11251. DebugMsg(SPeepholeOptimization + 'var3',p);
  11252. RemoveCurrentP(p, hp1);
  11253. RemoveInstruction(hp2);
  11254. Result := True;
  11255. Exit;
  11256. end;
  11257. if reg_and_hp1_is_instr and
  11258. (taicpu(hp1).opcode = A_MOV) and
  11259. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11260. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11261. {$ifdef x86_64}
  11262. { check for implicit extension to 64 bit }
  11263. or
  11264. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11265. (taicpu(hp1).opsize=S_Q) and
  11266. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11267. )
  11268. {$endif x86_64}
  11269. )
  11270. then
  11271. begin
  11272. { change
  11273. movx %reg1,%reg2
  11274. mov %reg2,%reg3
  11275. dealloc %reg2
  11276. into
  11277. movx %reg,%reg3
  11278. }
  11279. TransferUsedRegs(TmpUsedRegs);
  11280. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11281. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11282. begin
  11283. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11284. {$ifdef x86_64}
  11285. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11286. (taicpu(hp1).opsize=S_Q) then
  11287. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11288. else
  11289. {$endif x86_64}
  11290. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11291. RemoveInstruction(hp1);
  11292. Result := True;
  11293. Exit;
  11294. end;
  11295. end;
  11296. if reg_and_hp1_is_instr and
  11297. ((taicpu(hp1).opcode=A_MOV) or
  11298. (taicpu(hp1).opcode=A_ADD) or
  11299. (taicpu(hp1).opcode=A_SUB) or
  11300. (taicpu(hp1).opcode=A_CMP) or
  11301. (taicpu(hp1).opcode=A_OR) or
  11302. (taicpu(hp1).opcode=A_XOR) or
  11303. (taicpu(hp1).opcode=A_AND)
  11304. ) and
  11305. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11306. begin
  11307. AndTest := (taicpu(hp1).opcode=A_AND) and
  11308. GetNextInstruction(hp1, hp2) and
  11309. (hp2.typ = ait_instruction) and
  11310. (
  11311. (
  11312. (taicpu(hp2).opcode=A_TEST) and
  11313. (
  11314. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11315. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11316. (
  11317. { If the AND and TEST instructions share a constant, this is also valid }
  11318. (taicpu(hp1).oper[0]^.typ = top_const) and
  11319. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11320. )
  11321. ) and
  11322. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11323. ) or
  11324. (
  11325. (taicpu(hp2).opcode=A_CMP) and
  11326. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11327. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11328. )
  11329. );
  11330. { change
  11331. movx (oper),%reg2
  11332. and $x,%reg2
  11333. test %reg2,%reg2
  11334. dealloc %reg2
  11335. into
  11336. op %reg1,%reg3
  11337. if the second op accesses only the bits stored in reg1
  11338. }
  11339. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11340. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11341. (taicpu(hp1).oper[0]^.typ = top_const) and
  11342. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11343. AndTest then
  11344. begin
  11345. { Check if the AND constant is in range }
  11346. case taicpu(p).opsize of
  11347. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11348. begin
  11349. NewSize := S_B;
  11350. Limit := $FF;
  11351. end;
  11352. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11353. begin
  11354. NewSize := S_W;
  11355. Limit := $FFFF;
  11356. end;
  11357. {$ifdef x86_64}
  11358. S_LQ:
  11359. begin
  11360. NewSize := S_L;
  11361. Limit := $FFFFFFFF;
  11362. end;
  11363. {$endif x86_64}
  11364. else
  11365. InternalError(2021120303);
  11366. end;
  11367. if (
  11368. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11369. { Check for negative operands }
  11370. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11371. ) and
  11372. GetNextInstruction(hp2,hp3) and
  11373. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11374. (taicpu(hp3).condition in [C_E,C_NE]) then
  11375. begin
  11376. TransferUsedRegs(TmpUsedRegs);
  11377. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11378. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11379. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11380. begin
  11381. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11382. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11383. taicpu(hp1).opcode := A_TEST;
  11384. taicpu(hp1).opsize := NewSize;
  11385. RemoveInstruction(hp2);
  11386. RemoveCurrentP(p, hp1);
  11387. Result:=true;
  11388. exit;
  11389. end;
  11390. end;
  11391. end;
  11392. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11393. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11394. (taicpu(hp1).opsize=S_B)) or
  11395. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11396. (taicpu(hp1).opsize=S_W))
  11397. {$ifdef x86_64}
  11398. or ((taicpu(p).opsize=S_LQ) and
  11399. (taicpu(hp1).opsize=S_L))
  11400. {$endif x86_64}
  11401. ) and
  11402. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11403. begin
  11404. { change
  11405. movx %reg1,%reg2
  11406. op %reg2,%reg3
  11407. dealloc %reg2
  11408. into
  11409. op %reg1,%reg3
  11410. if the second op accesses only the bits stored in reg1
  11411. }
  11412. TransferUsedRegs(TmpUsedRegs);
  11413. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11414. if AndTest then
  11415. begin
  11416. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11417. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11418. end
  11419. else
  11420. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11421. if not RegUsed then
  11422. begin
  11423. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11424. if taicpu(p).oper[0]^.typ=top_reg then
  11425. begin
  11426. case taicpu(hp1).opsize of
  11427. S_B:
  11428. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11429. S_W:
  11430. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11431. S_L:
  11432. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11433. else
  11434. Internalerror(2020102301);
  11435. end;
  11436. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11437. end
  11438. else
  11439. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11440. RemoveCurrentP(p);
  11441. if AndTest then
  11442. RemoveInstruction(hp2);
  11443. result:=true;
  11444. exit;
  11445. end;
  11446. end
  11447. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11448. (
  11449. { Bitwise operations only }
  11450. (taicpu(hp1).opcode=A_AND) or
  11451. (taicpu(hp1).opcode=A_TEST) or
  11452. (
  11453. (taicpu(hp1).oper[0]^.typ = top_const) and
  11454. (
  11455. (taicpu(hp1).opcode=A_OR) or
  11456. (taicpu(hp1).opcode=A_XOR)
  11457. )
  11458. )
  11459. ) and
  11460. (
  11461. (taicpu(hp1).oper[0]^.typ = top_const) or
  11462. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11463. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11464. ) then
  11465. begin
  11466. { change
  11467. movx %reg2,%reg2
  11468. op const,%reg2
  11469. into
  11470. op const,%reg2 (smaller version)
  11471. movx %reg2,%reg2
  11472. also change
  11473. movx %reg1,%reg2
  11474. and/test (oper),%reg2
  11475. dealloc %reg2
  11476. into
  11477. and/test (oper),%reg1
  11478. }
  11479. case taicpu(p).opsize of
  11480. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11481. begin
  11482. NewSize := S_B;
  11483. NewRegSize := R_SUBL;
  11484. Limit := $FF;
  11485. end;
  11486. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11487. begin
  11488. NewSize := S_W;
  11489. NewRegSize := R_SUBW;
  11490. Limit := $FFFF;
  11491. end;
  11492. {$ifdef x86_64}
  11493. S_LQ:
  11494. begin
  11495. NewSize := S_L;
  11496. NewRegSize := R_SUBD;
  11497. Limit := $FFFFFFFF;
  11498. end;
  11499. {$endif x86_64}
  11500. else
  11501. Internalerror(2021120302);
  11502. end;
  11503. TransferUsedRegs(TmpUsedRegs);
  11504. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11505. if AndTest then
  11506. begin
  11507. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11508. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11509. end
  11510. else
  11511. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11512. if
  11513. (
  11514. (taicpu(p).opcode = A_MOVZX) and
  11515. (
  11516. (taicpu(hp1).opcode=A_AND) or
  11517. (taicpu(hp1).opcode=A_TEST)
  11518. ) and
  11519. not (
  11520. { If both are references, then the final instruction will have
  11521. both operands as references, which is not allowed }
  11522. (taicpu(p).oper[0]^.typ = top_ref) and
  11523. (taicpu(hp1).oper[0]^.typ = top_ref)
  11524. ) and
  11525. not RegUsed
  11526. ) or
  11527. (
  11528. (
  11529. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  11530. not RegUsed
  11531. ) and
  11532. (taicpu(p).oper[0]^.typ = top_reg) and
  11533. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11534. (taicpu(hp1).oper[0]^.typ = top_const) and
  11535. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  11536. ) then
  11537. begin
  11538. {$if defined(i386) or defined(i8086)}
  11539. { If the target size is 8-bit, make sure we can actually encode it }
  11540. 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
  11541. Exit;
  11542. {$endif i386 or i8086}
  11543. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  11544. taicpu(hp1).opsize := NewSize;
  11545. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11546. if AndTest then
  11547. begin
  11548. RemoveInstruction(hp2);
  11549. if not RegUsed then
  11550. begin
  11551. taicpu(hp1).opcode := A_TEST;
  11552. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  11553. begin
  11554. { Make sure the reference is the second operand }
  11555. SwapOper := taicpu(hp1).oper[0];
  11556. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  11557. taicpu(hp1).oper[1] := SwapOper;
  11558. end;
  11559. end;
  11560. end;
  11561. case taicpu(hp1).oper[0]^.typ of
  11562. top_reg:
  11563. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  11564. top_const:
  11565. { For the AND/TEST case }
  11566. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  11567. else
  11568. ;
  11569. end;
  11570. if RegUsed then
  11571. begin
  11572. AsmL.Remove(p);
  11573. AsmL.InsertAfter(p, hp1);
  11574. p := hp1;
  11575. end
  11576. else
  11577. RemoveCurrentP(p, hp1);
  11578. result:=true;
  11579. exit;
  11580. end;
  11581. end;
  11582. end;
  11583. if reg_and_hp1_is_instr and
  11584. (taicpu(p).oper[0]^.typ = top_reg) and
  11585. (
  11586. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  11587. ) and
  11588. (taicpu(hp1).oper[0]^.typ = top_const) and
  11589. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11590. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11591. { Minimum shift value allowed is the bit difference between the sizes }
  11592. (taicpu(hp1).oper[0]^.val >=
  11593. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11594. 8 * (
  11595. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  11596. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11597. )
  11598. ) then
  11599. begin
  11600. { For:
  11601. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  11602. shl/sal ##, %reg1
  11603. Remove the movsx/movzx instruction if the shift overwrites the
  11604. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  11605. }
  11606. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  11607. RemoveCurrentP(p, hp1);
  11608. Result := True;
  11609. Exit;
  11610. end
  11611. else if reg_and_hp1_is_instr and
  11612. (taicpu(p).oper[0]^.typ = top_reg) and
  11613. (
  11614. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  11615. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  11616. ) and
  11617. (taicpu(hp1).oper[0]^.typ = top_const) and
  11618. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11619. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11620. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  11621. (taicpu(hp1).oper[0]^.val <
  11622. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11623. 8 * (
  11624. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11625. )
  11626. ) then
  11627. begin
  11628. { For:
  11629. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  11630. sar ##, %reg1 shr ##, %reg1
  11631. Move the shift to before the movx instruction if the shift value
  11632. is not too large.
  11633. }
  11634. asml.Remove(hp1);
  11635. asml.InsertBefore(hp1, p);
  11636. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11637. case taicpu(p).opsize of
  11638. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  11639. taicpu(hp1).opsize := S_B;
  11640. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  11641. taicpu(hp1).opsize := S_W;
  11642. {$ifdef x86_64}
  11643. S_LQ:
  11644. taicpu(hp1).opsize := S_L;
  11645. {$endif}
  11646. else
  11647. InternalError(2020112401);
  11648. end;
  11649. if (taicpu(hp1).opcode = A_SHR) then
  11650. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  11651. else
  11652. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  11653. Result := True;
  11654. end;
  11655. if reg_and_hp1_is_instr and
  11656. (taicpu(p).oper[0]^.typ = top_reg) and
  11657. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11658. (
  11659. (taicpu(hp1).opcode = taicpu(p).opcode)
  11660. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  11661. {$ifdef x86_64}
  11662. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  11663. {$endif x86_64}
  11664. ) then
  11665. begin
  11666. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  11667. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  11668. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11669. begin
  11670. {
  11671. For example:
  11672. movzbw %al,%ax
  11673. movzwl %ax,%eax
  11674. Compress into:
  11675. movzbl %al,%eax
  11676. }
  11677. RegUsed := False;
  11678. case taicpu(p).opsize of
  11679. S_BW:
  11680. case taicpu(hp1).opsize of
  11681. S_WL:
  11682. begin
  11683. taicpu(p).opsize := S_BL;
  11684. RegUsed := True;
  11685. end;
  11686. {$ifdef x86_64}
  11687. S_WQ:
  11688. begin
  11689. if taicpu(p).opcode = A_MOVZX then
  11690. begin
  11691. taicpu(p).opsize := S_BL;
  11692. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11693. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11694. end
  11695. else
  11696. taicpu(p).opsize := S_BQ;
  11697. RegUsed := True;
  11698. end;
  11699. {$endif x86_64}
  11700. else
  11701. ;
  11702. end;
  11703. {$ifdef x86_64}
  11704. S_BL:
  11705. case taicpu(hp1).opsize of
  11706. S_LQ:
  11707. begin
  11708. if taicpu(p).opcode = A_MOVZX then
  11709. begin
  11710. taicpu(p).opsize := S_BL;
  11711. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11712. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11713. end
  11714. else
  11715. taicpu(p).opsize := S_BQ;
  11716. RegUsed := True;
  11717. end;
  11718. else
  11719. ;
  11720. end;
  11721. S_WL:
  11722. case taicpu(hp1).opsize of
  11723. S_LQ:
  11724. begin
  11725. if taicpu(p).opcode = A_MOVZX then
  11726. begin
  11727. taicpu(p).opsize := S_WL;
  11728. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11729. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11730. end
  11731. else
  11732. taicpu(p).opsize := S_WQ;
  11733. RegUsed := True;
  11734. end;
  11735. else
  11736. ;
  11737. end;
  11738. {$endif x86_64}
  11739. else
  11740. ;
  11741. end;
  11742. if RegUsed then
  11743. begin
  11744. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  11745. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  11746. RemoveInstruction(hp1);
  11747. Result := True;
  11748. Exit;
  11749. end;
  11750. end;
  11751. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  11752. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  11753. GetNextInstruction(hp1, hp2) and
  11754. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  11755. (
  11756. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  11757. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  11758. {$ifdef x86_64}
  11759. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  11760. {$endif x86_64}
  11761. ) and
  11762. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11763. (
  11764. (
  11765. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11766. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11767. ) or
  11768. (
  11769. { Only allow the operands in reverse order for TEST instructions }
  11770. (taicpu(hp2).opcode = A_TEST) and
  11771. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11772. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  11773. )
  11774. ) then
  11775. begin
  11776. {
  11777. For example:
  11778. movzbl %al,%eax
  11779. movzbl (ref),%edx
  11780. andl %edx,%eax
  11781. (%edx deallocated)
  11782. Change to:
  11783. andb (ref),%al
  11784. movzbl %al,%eax
  11785. Rules are:
  11786. - First two instructions have the same opcode and opsize
  11787. - First instruction's operands are the same super-register
  11788. - Second instruction operates on a different register
  11789. - Third instruction is AND, OR, XOR or TEST
  11790. - Third instruction's operands are the destination registers of the first two instructions
  11791. - Third instruction writes to the destination register of the first instruction (except with TEST)
  11792. - Second instruction's destination register is deallocated afterwards
  11793. }
  11794. TransferUsedRegs(TmpUsedRegs);
  11795. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11796. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11797. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  11798. begin
  11799. case taicpu(p).opsize of
  11800. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11801. NewSize := S_B;
  11802. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11803. NewSize := S_W;
  11804. {$ifdef x86_64}
  11805. S_LQ:
  11806. NewSize := S_L;
  11807. {$endif x86_64}
  11808. else
  11809. InternalError(2021120301);
  11810. end;
  11811. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  11812. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  11813. taicpu(hp2).opsize := NewSize;
  11814. RemoveInstruction(hp1);
  11815. { With TEST, it's best to keep the MOVX instruction at the top }
  11816. if (taicpu(hp2).opcode <> A_TEST) then
  11817. begin
  11818. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  11819. asml.Remove(p);
  11820. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  11821. asml.InsertAfter(p, hp2);
  11822. p := hp2;
  11823. end
  11824. else
  11825. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  11826. Result := True;
  11827. Exit;
  11828. end;
  11829. end;
  11830. end;
  11831. if taicpu(p).opcode=A_MOVZX then
  11832. begin
  11833. { removes superfluous And's after movzx's }
  11834. if reg_and_hp1_is_instr and
  11835. (taicpu(hp1).opcode = A_AND) and
  11836. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11837. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11838. {$ifdef x86_64}
  11839. { check for implicit extension to 64 bit }
  11840. or
  11841. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11842. (taicpu(hp1).opsize=S_Q) and
  11843. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  11844. )
  11845. {$endif x86_64}
  11846. )
  11847. then
  11848. begin
  11849. case taicpu(p).opsize Of
  11850. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11851. if (taicpu(hp1).oper[0]^.val = $ff) then
  11852. begin
  11853. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  11854. RemoveInstruction(hp1);
  11855. Result:=true;
  11856. exit;
  11857. end;
  11858. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11859. if (taicpu(hp1).oper[0]^.val = $ffff) then
  11860. begin
  11861. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  11862. RemoveInstruction(hp1);
  11863. Result:=true;
  11864. exit;
  11865. end;
  11866. {$ifdef x86_64}
  11867. S_LQ:
  11868. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  11869. begin
  11870. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  11871. RemoveInstruction(hp1);
  11872. Result:=true;
  11873. exit;
  11874. end;
  11875. {$endif x86_64}
  11876. else
  11877. ;
  11878. end;
  11879. { we cannot get rid of the and, but can we get rid of the movz ?}
  11880. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  11881. begin
  11882. case taicpu(p).opsize Of
  11883. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11884. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  11885. begin
  11886. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  11887. RemoveCurrentP(p,hp1);
  11888. Result:=true;
  11889. exit;
  11890. end;
  11891. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11892. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  11893. begin
  11894. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  11895. RemoveCurrentP(p,hp1);
  11896. Result:=true;
  11897. exit;
  11898. end;
  11899. {$ifdef x86_64}
  11900. S_LQ:
  11901. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  11902. begin
  11903. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  11904. RemoveCurrentP(p,hp1);
  11905. Result:=true;
  11906. exit;
  11907. end;
  11908. {$endif x86_64}
  11909. else
  11910. ;
  11911. end;
  11912. end;
  11913. end;
  11914. { changes some movzx constructs to faster synonyms (all examples
  11915. are given with eax/ax, but are also valid for other registers)}
  11916. if MatchOpType(taicpu(p),top_reg,top_reg) then
  11917. begin
  11918. case taicpu(p).opsize of
  11919. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  11920. (the machine code is equivalent to movzbl %al,%eax), but the
  11921. code generator still generates that assembler instruction and
  11922. it is silently converted. This should probably be checked.
  11923. [Kit] }
  11924. S_BW:
  11925. begin
  11926. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  11927. (
  11928. not IsMOVZXAcceptable
  11929. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  11930. or (
  11931. (cs_opt_size in current_settings.optimizerswitches) and
  11932. (taicpu(p).oper[1]^.reg = NR_AX)
  11933. )
  11934. ) then
  11935. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  11936. begin
  11937. DebugMsg(SPeepholeOptimization + 'var7',p);
  11938. taicpu(p).opcode := A_AND;
  11939. taicpu(p).changeopsize(S_W);
  11940. taicpu(p).loadConst(0,$ff);
  11941. Result := True;
  11942. end
  11943. else if not IsMOVZXAcceptable and
  11944. GetNextInstruction(p, hp1) and
  11945. (tai(hp1).typ = ait_instruction) and
  11946. (taicpu(hp1).opcode = A_AND) and
  11947. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11948. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11949. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  11950. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  11951. begin
  11952. DebugMsg(SPeepholeOptimization + 'var8',p);
  11953. taicpu(p).opcode := A_MOV;
  11954. taicpu(p).changeopsize(S_W);
  11955. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  11956. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11957. Result := True;
  11958. end;
  11959. end;
  11960. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  11961. S_BL:
  11962. if not IsMOVZXAcceptable then
  11963. begin
  11964. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  11965. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  11966. begin
  11967. DebugMsg(SPeepholeOptimization + 'var9',p);
  11968. taicpu(p).opcode := A_AND;
  11969. taicpu(p).changeopsize(S_L);
  11970. taicpu(p).loadConst(0,$ff);
  11971. Result := True;
  11972. end
  11973. else if GetNextInstruction(p, hp1) and
  11974. (tai(hp1).typ = ait_instruction) and
  11975. (taicpu(hp1).opcode = A_AND) and
  11976. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11977. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11978. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  11979. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  11980. begin
  11981. DebugMsg(SPeepholeOptimization + 'var10',p);
  11982. taicpu(p).opcode := A_MOV;
  11983. taicpu(p).changeopsize(S_L);
  11984. { do not use R_SUBWHOLE
  11985. as movl %rdx,%eax
  11986. is invalid in assembler PM }
  11987. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11988. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11989. Result := True;
  11990. end;
  11991. end;
  11992. {$endif i8086}
  11993. S_WL:
  11994. if not IsMOVZXAcceptable then
  11995. begin
  11996. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  11997. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  11998. begin
  11999. DebugMsg(SPeepholeOptimization + 'var11',p);
  12000. taicpu(p).opcode := A_AND;
  12001. taicpu(p).changeopsize(S_L);
  12002. taicpu(p).loadConst(0,$ffff);
  12003. Result := True;
  12004. end
  12005. else if GetNextInstruction(p, hp1) and
  12006. (tai(hp1).typ = ait_instruction) and
  12007. (taicpu(hp1).opcode = A_AND) and
  12008. (taicpu(hp1).oper[0]^.typ = top_const) and
  12009. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12010. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12011. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12012. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12013. begin
  12014. DebugMsg(SPeepholeOptimization + 'var12',p);
  12015. taicpu(p).opcode := A_MOV;
  12016. taicpu(p).changeopsize(S_L);
  12017. { do not use R_SUBWHOLE
  12018. as movl %rdx,%eax
  12019. is invalid in assembler PM }
  12020. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12021. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12022. Result := True;
  12023. end;
  12024. end;
  12025. else
  12026. InternalError(2017050705);
  12027. end;
  12028. end
  12029. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12030. begin
  12031. if GetNextInstruction(p, hp1) and
  12032. (tai(hp1).typ = ait_instruction) and
  12033. (taicpu(hp1).opcode = A_AND) and
  12034. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12035. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12036. begin
  12037. //taicpu(p).opcode := A_MOV;
  12038. case taicpu(p).opsize Of
  12039. S_BL:
  12040. begin
  12041. DebugMsg(SPeepholeOptimization + 'var13',p);
  12042. taicpu(hp1).changeopsize(S_L);
  12043. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12044. end;
  12045. S_WL:
  12046. begin
  12047. DebugMsg(SPeepholeOptimization + 'var14',p);
  12048. taicpu(hp1).changeopsize(S_L);
  12049. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12050. end;
  12051. S_BW:
  12052. begin
  12053. DebugMsg(SPeepholeOptimization + 'var15',p);
  12054. taicpu(hp1).changeopsize(S_W);
  12055. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12056. end;
  12057. else
  12058. Internalerror(2017050704)
  12059. end;
  12060. Result := True;
  12061. end;
  12062. end;
  12063. end;
  12064. end;
  12065. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12066. var
  12067. hp1, hp2 : tai;
  12068. MaskLength : Cardinal;
  12069. MaskedBits : TCgInt;
  12070. ActiveReg : TRegister;
  12071. begin
  12072. Result:=false;
  12073. { There are no optimisations for reference targets }
  12074. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12075. Exit;
  12076. while GetNextInstruction(p, hp1) and
  12077. (hp1.typ = ait_instruction) do
  12078. begin
  12079. if (taicpu(p).oper[0]^.typ = top_const) then
  12080. begin
  12081. case taicpu(hp1).opcode of
  12082. A_AND:
  12083. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12084. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12085. { the second register must contain the first one, so compare their subreg types }
  12086. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12087. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12088. { change
  12089. and const1, reg
  12090. and const2, reg
  12091. to
  12092. and (const1 and const2), reg
  12093. }
  12094. begin
  12095. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12096. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12097. RemoveCurrentP(p, hp1);
  12098. Result:=true;
  12099. exit;
  12100. end;
  12101. A_CMP:
  12102. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12103. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12104. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12105. { Just check that the condition on the next instruction is compatible }
  12106. GetNextInstruction(hp1, hp2) and
  12107. (hp2.typ = ait_instruction) and
  12108. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12109. then
  12110. { change
  12111. and 2^n, reg
  12112. cmp 2^n, reg
  12113. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12114. to
  12115. and 2^n, reg
  12116. test reg, reg
  12117. j(~c) / set(~c) / cmov(~c)
  12118. }
  12119. begin
  12120. { Keep TEST instruction in, rather than remove it, because
  12121. it may trigger other optimisations such as MovAndTest2Test }
  12122. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12123. taicpu(hp1).opcode := A_TEST;
  12124. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12125. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12126. Result := True;
  12127. Exit;
  12128. end;
  12129. A_MOVZX:
  12130. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12131. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12132. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12133. (
  12134. (
  12135. (taicpu(p).opsize=S_W) and
  12136. (taicpu(hp1).opsize=S_BW)
  12137. ) or
  12138. (
  12139. (taicpu(p).opsize=S_L) and
  12140. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12141. )
  12142. {$ifdef x86_64}
  12143. or
  12144. (
  12145. (taicpu(p).opsize=S_Q) and
  12146. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12147. )
  12148. {$endif x86_64}
  12149. ) then
  12150. begin
  12151. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12152. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12153. ) or
  12154. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12155. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12156. then
  12157. begin
  12158. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12159. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12160. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12161. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12162. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12163. }
  12164. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12165. RemoveInstruction(hp1);
  12166. { See if there are other optimisations possible }
  12167. Continue;
  12168. end;
  12169. end;
  12170. A_SHL:
  12171. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12172. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12173. begin
  12174. {$ifopt R+}
  12175. {$define RANGE_WAS_ON}
  12176. {$R-}
  12177. {$endif}
  12178. { get length of potential and mask }
  12179. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12180. { really a mask? }
  12181. {$ifdef RANGE_WAS_ON}
  12182. {$R+}
  12183. {$endif}
  12184. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12185. { unmasked part shifted out? }
  12186. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12187. begin
  12188. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12189. RemoveCurrentP(p, hp1);
  12190. Result:=true;
  12191. exit;
  12192. end;
  12193. end;
  12194. A_SHR:
  12195. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12196. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12197. (taicpu(hp1).oper[0]^.val <= 63) then
  12198. begin
  12199. { Does SHR combined with the AND cover all the bits?
  12200. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12201. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12202. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12203. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12204. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12205. begin
  12206. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12207. RemoveCurrentP(p, hp1);
  12208. Result := True;
  12209. Exit;
  12210. end;
  12211. end;
  12212. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12213. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12214. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12215. begin
  12216. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12217. (
  12218. (
  12219. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12220. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12221. ) or (
  12222. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12223. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12224. {$ifdef x86_64}
  12225. ) or (
  12226. (taicpu(hp1).opsize = S_LQ) and
  12227. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12228. {$endif x86_64}
  12229. )
  12230. ) then
  12231. begin
  12232. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12233. begin
  12234. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12235. RemoveInstruction(hp1);
  12236. { See if there are other optimisations possible }
  12237. Continue;
  12238. end;
  12239. { The super-registers are the same though.
  12240. Note that this change by itself doesn't improve
  12241. code speed, but it opens up other optimisations. }
  12242. {$ifdef x86_64}
  12243. { Convert 64-bit register to 32-bit }
  12244. case taicpu(hp1).opsize of
  12245. S_BQ:
  12246. begin
  12247. taicpu(hp1).opsize := S_BL;
  12248. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12249. end;
  12250. S_WQ:
  12251. begin
  12252. taicpu(hp1).opsize := S_WL;
  12253. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12254. end
  12255. else
  12256. ;
  12257. end;
  12258. {$endif x86_64}
  12259. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12260. taicpu(hp1).opcode := A_MOVZX;
  12261. { See if there are other optimisations possible }
  12262. Continue;
  12263. end;
  12264. end;
  12265. else
  12266. ;
  12267. end;
  12268. end
  12269. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12270. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12271. begin
  12272. {$ifdef x86_64}
  12273. if (taicpu(p).opsize = S_Q) then
  12274. begin
  12275. { Never necessary }
  12276. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12277. RemoveCurrentP(p, hp1);
  12278. Result := True;
  12279. Exit;
  12280. end;
  12281. {$endif x86_64}
  12282. { Forward check to determine necessity of and %reg,%reg }
  12283. TransferUsedRegs(TmpUsedRegs);
  12284. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12285. { Saves on a bunch of dereferences }
  12286. ActiveReg := taicpu(p).oper[1]^.reg;
  12287. case taicpu(hp1).opcode of
  12288. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12289. if (
  12290. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12291. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12292. ) and
  12293. (
  12294. (taicpu(hp1).opcode <> A_MOV) or
  12295. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12296. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12297. ) and
  12298. not (
  12299. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12300. (taicpu(hp1).opcode = A_MOV) and
  12301. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12302. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12303. ) and
  12304. (
  12305. (
  12306. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12307. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12308. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12309. ) or
  12310. (
  12311. {$ifdef x86_64}
  12312. (
  12313. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12314. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12315. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12316. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12317. ) and
  12318. {$endif x86_64}
  12319. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12320. )
  12321. ) then
  12322. begin
  12323. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12324. RemoveCurrentP(p, hp1);
  12325. Result := True;
  12326. Exit;
  12327. end;
  12328. A_ADD,
  12329. A_AND,
  12330. A_BSF,
  12331. A_BSR,
  12332. A_BTC,
  12333. A_BTR,
  12334. A_BTS,
  12335. A_OR,
  12336. A_SUB,
  12337. A_XOR:
  12338. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12339. if (
  12340. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12341. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12342. ) and
  12343. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12344. begin
  12345. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12346. RemoveCurrentP(p, hp1);
  12347. Result := True;
  12348. Exit;
  12349. end;
  12350. A_CMP,
  12351. A_TEST:
  12352. if (
  12353. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12354. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12355. ) and
  12356. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12357. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12358. begin
  12359. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12360. RemoveCurrentP(p, hp1);
  12361. Result := True;
  12362. Exit;
  12363. end;
  12364. A_BSWAP,
  12365. A_NEG,
  12366. A_NOT:
  12367. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12368. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12369. begin
  12370. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12371. RemoveCurrentP(p, hp1);
  12372. Result := True;
  12373. Exit;
  12374. end;
  12375. else
  12376. ;
  12377. end;
  12378. end;
  12379. if (taicpu(hp1).is_jmp) and
  12380. (taicpu(hp1).opcode<>A_JMP) and
  12381. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12382. begin
  12383. { change
  12384. and x, reg
  12385. jxx
  12386. to
  12387. test x, reg
  12388. jxx
  12389. if reg is deallocated before the
  12390. jump, but only if it's a conditional jump (PFV)
  12391. }
  12392. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12393. taicpu(p).opcode := A_TEST;
  12394. Exit;
  12395. end;
  12396. Break;
  12397. end;
  12398. { Lone AND tests }
  12399. if (taicpu(p).oper[0]^.typ = top_const) then
  12400. begin
  12401. {
  12402. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12403. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12404. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12405. }
  12406. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12407. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12408. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12409. begin
  12410. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12411. if taicpu(p).opsize = S_L then
  12412. begin
  12413. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12414. Result := True;
  12415. end;
  12416. end;
  12417. end;
  12418. { Backward check to determine necessity of and %reg,%reg }
  12419. if (taicpu(p).oper[0]^.typ = top_reg) and
  12420. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12421. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12422. GetLastInstruction(p, hp2) and
  12423. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12424. { Check size of adjacent instruction to determine if the AND is
  12425. effectively a null operation }
  12426. (
  12427. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12428. { Note: Don't include S_Q }
  12429. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12430. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12431. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  12432. ) then
  12433. begin
  12434. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  12435. { If GetNextInstruction returned False, hp1 will be nil }
  12436. RemoveCurrentP(p, hp1);
  12437. Result := True;
  12438. Exit;
  12439. end;
  12440. end;
  12441. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  12442. var
  12443. hp1, hp2: tai;
  12444. NewRef: TReference;
  12445. Distance: Cardinal;
  12446. TempTracking: TAllUsedRegs;
  12447. { This entire nested function is used in an if-statement below, but we
  12448. want to avoid all the used reg transfers and GetNextInstruction calls
  12449. until we really have to check }
  12450. function MemRegisterNotUsedLater: Boolean; inline;
  12451. var
  12452. hp2: tai;
  12453. begin
  12454. TransferUsedRegs(TmpUsedRegs);
  12455. hp2 := p;
  12456. repeat
  12457. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12458. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12459. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  12460. end;
  12461. begin
  12462. Result := False;
  12463. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12464. (taicpu(p).oper[1]^.typ = top_reg) then
  12465. begin
  12466. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12467. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12468. (hp1.typ <> ait_instruction) or
  12469. not
  12470. (
  12471. (cs_opt_level3 in current_settings.optimizerswitches) or
  12472. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12473. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12474. ) then
  12475. Exit;
  12476. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12477. addq $x, %rax
  12478. movq %rax, %rdx
  12479. sarq $63, %rdx
  12480. (%rax still in use)
  12481. ...letting OptPass2ADD run its course (and without -Os) will produce:
  12482. leaq $x(%rax),%rdx
  12483. addq $x, %rax
  12484. sarq $63, %rdx
  12485. ...which is okay since it breaks the dependency chain between
  12486. addq and movq, but if OptPass2MOV is called first:
  12487. addq $x, %rax
  12488. cqto
  12489. ...which is better in all ways, taking only 2 cycles to execute
  12490. and much smaller in code size.
  12491. }
  12492. { The extra register tracking is quite strenuous }
  12493. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12494. MatchInstruction(hp1, A_MOV, []) then
  12495. begin
  12496. { Update the register tracking to the MOV instruction }
  12497. CopyUsedRegs(TempTracking);
  12498. hp2 := p;
  12499. repeat
  12500. UpdateUsedRegs(tai(hp2.Next));
  12501. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12502. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12503. OptPass2ADD get called again }
  12504. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12505. begin
  12506. { Reset the tracking to the current instruction }
  12507. RestoreUsedRegs(TempTracking);
  12508. ReleaseUsedRegs(TempTracking);
  12509. Result := True;
  12510. Exit;
  12511. end;
  12512. { Reset the tracking to the current instruction }
  12513. RestoreUsedRegs(TempTracking);
  12514. ReleaseUsedRegs(TempTracking);
  12515. { If OptPass2MOV returned True, we don't need to set Result to
  12516. True if hp1 didn't change because the ADD instruction didn't
  12517. get modified and we'll be evaluating hp1 again when the
  12518. peephole optimizer reaches it }
  12519. end;
  12520. { Change:
  12521. add %reg2,%reg1
  12522. (%reg2 not modified in between)
  12523. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  12524. To:
  12525. mov/s/z #(%reg1,%reg2),%reg1
  12526. }
  12527. if (taicpu(p).oper[0]^.typ = top_reg) and
  12528. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  12529. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  12530. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  12531. (
  12532. (
  12533. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  12534. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  12535. { r/esp cannot be an index }
  12536. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  12537. ) or (
  12538. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  12539. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  12540. )
  12541. ) and (
  12542. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  12543. (
  12544. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  12545. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12546. MemRegisterNotUsedLater
  12547. )
  12548. ) then
  12549. begin
  12550. if (
  12551. { Instructions are guaranteed to be adjacent on -O2 and under }
  12552. (cs_opt_level3 in current_settings.optimizerswitches) and
  12553. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  12554. ) then
  12555. begin
  12556. { If the other register is used in between, move the MOV
  12557. instruction to right after the ADD instruction so a
  12558. saving can still be made }
  12559. Asml.Remove(hp1);
  12560. Asml.InsertAfter(hp1, p);
  12561. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12562. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12563. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  12564. RemoveCurrentp(p, hp1);
  12565. end
  12566. else
  12567. begin
  12568. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  12569. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12570. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12571. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  12572. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12573. { hp1 may not be the immediate next instruction under -O3 }
  12574. RemoveCurrentp(p)
  12575. else
  12576. RemoveCurrentp(p, hp1);
  12577. end;
  12578. Result := True;
  12579. Exit;
  12580. end;
  12581. { Change:
  12582. addl/q $x,%reg1
  12583. movl/q %reg1,%reg2
  12584. To:
  12585. leal/q $x(%reg1),%reg2
  12586. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12587. Breaks the dependency chain.
  12588. }
  12589. if (taicpu(p).oper[0]^.typ = top_const) and
  12590. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12591. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12592. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12593. (
  12594. { Instructions are guaranteed to be adjacent on -O2 and under }
  12595. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12596. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12597. ) then
  12598. begin
  12599. TransferUsedRegs(TmpUsedRegs);
  12600. hp2 := p;
  12601. repeat
  12602. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12603. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12604. if (
  12605. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  12606. not (cs_opt_size in current_settings.optimizerswitches) or
  12607. (
  12608. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12609. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12610. )
  12611. ) then
  12612. begin
  12613. { Change the MOV instruction to a LEA instruction, and update the
  12614. first operand }
  12615. reference_reset(NewRef, 1, []);
  12616. NewRef.base := taicpu(p).oper[1]^.reg;
  12617. NewRef.scalefactor := 1;
  12618. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  12619. taicpu(hp1).opcode := A_LEA;
  12620. taicpu(hp1).loadref(0, NewRef);
  12621. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12622. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12623. begin
  12624. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12625. { Move what is now the LEA instruction to before the ADD instruction }
  12626. Asml.Remove(hp1);
  12627. Asml.InsertBefore(hp1, p);
  12628. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12629. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  12630. p := hp1;
  12631. end
  12632. else
  12633. begin
  12634. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12635. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  12636. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12637. { hp1 may not be the immediate next instruction under -O3 }
  12638. RemoveCurrentp(p)
  12639. else
  12640. RemoveCurrentp(p, hp1);
  12641. end;
  12642. Result := True;
  12643. end;
  12644. end;
  12645. end;
  12646. end;
  12647. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  12648. var
  12649. SubReg: TSubRegister;
  12650. begin
  12651. Result:=false;
  12652. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  12653. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12654. with taicpu(p).oper[0]^.ref^ do
  12655. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  12656. begin
  12657. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  12658. begin
  12659. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  12660. taicpu(p).opcode := A_ADD;
  12661. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  12662. Result := True;
  12663. end
  12664. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  12665. begin
  12666. if (base <> NR_NO) then
  12667. begin
  12668. if (scalefactor <= 1) then
  12669. begin
  12670. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  12671. taicpu(p).opcode := A_ADD;
  12672. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  12673. Result := True;
  12674. end;
  12675. end
  12676. else
  12677. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  12678. if (scalefactor in [2, 4, 8]) then
  12679. begin
  12680. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  12681. taicpu(p).loadconst(0, BsrByte(scalefactor));
  12682. taicpu(p).opcode := A_SHL;
  12683. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  12684. Result := True;
  12685. end;
  12686. end;
  12687. end;
  12688. end;
  12689. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  12690. var
  12691. hp1, hp2: tai;
  12692. NewRef: TReference;
  12693. Distance: Cardinal;
  12694. TempTracking: TAllUsedRegs;
  12695. begin
  12696. Result := False;
  12697. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12698. MatchOpType(taicpu(p),top_const,top_reg) then
  12699. begin
  12700. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12701. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12702. (hp1.typ <> ait_instruction) or
  12703. not
  12704. (
  12705. (cs_opt_level3 in current_settings.optimizerswitches) or
  12706. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12707. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12708. ) then
  12709. Exit;
  12710. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12711. subq $x, %rax
  12712. movq %rax, %rdx
  12713. sarq $63, %rdx
  12714. (%rax still in use)
  12715. ...letting OptPass2SUB run its course (and without -Os) will produce:
  12716. leaq $-x(%rax),%rdx
  12717. movq $x, %rax
  12718. sarq $63, %rdx
  12719. ...which is okay since it breaks the dependency chain between
  12720. subq and movq, but if OptPass2MOV is called first:
  12721. subq $x, %rax
  12722. cqto
  12723. ...which is better in all ways, taking only 2 cycles to execute
  12724. and much smaller in code size.
  12725. }
  12726. { The extra register tracking is quite strenuous }
  12727. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12728. MatchInstruction(hp1, A_MOV, []) then
  12729. begin
  12730. { Update the register tracking to the MOV instruction }
  12731. CopyUsedRegs(TempTracking);
  12732. hp2 := p;
  12733. repeat
  12734. UpdateUsedRegs(tai(hp2.Next));
  12735. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12736. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12737. OptPass2SUB get called again }
  12738. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12739. begin
  12740. { Reset the tracking to the current instruction }
  12741. RestoreUsedRegs(TempTracking);
  12742. ReleaseUsedRegs(TempTracking);
  12743. Result := True;
  12744. Exit;
  12745. end;
  12746. { Reset the tracking to the current instruction }
  12747. RestoreUsedRegs(TempTracking);
  12748. ReleaseUsedRegs(TempTracking);
  12749. { If OptPass2MOV returned True, we don't need to set Result to
  12750. True if hp1 didn't change because the SUB instruction didn't
  12751. get modified and we'll be evaluating hp1 again when the
  12752. peephole optimizer reaches it }
  12753. end;
  12754. { Change:
  12755. subl/q $x,%reg1
  12756. movl/q %reg1,%reg2
  12757. To:
  12758. leal/q $-x(%reg1),%reg2
  12759. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12760. Breaks the dependency chain and potentially permits the removal of
  12761. a CMP instruction if one follows.
  12762. }
  12763. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12764. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12765. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12766. (
  12767. { Instructions are guaranteed to be adjacent on -O2 and under }
  12768. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12769. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12770. ) then
  12771. begin
  12772. TransferUsedRegs(TmpUsedRegs);
  12773. hp2 := p;
  12774. repeat
  12775. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12776. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12777. if (
  12778. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  12779. not (cs_opt_size in current_settings.optimizerswitches) or
  12780. (
  12781. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12782. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12783. )
  12784. ) then
  12785. begin
  12786. { Change the MOV instruction to a LEA instruction, and update the
  12787. first operand }
  12788. reference_reset(NewRef, 1, []);
  12789. NewRef.base := taicpu(p).oper[1]^.reg;
  12790. NewRef.scalefactor := 1;
  12791. NewRef.offset := -taicpu(p).oper[0]^.val;
  12792. taicpu(hp1).opcode := A_LEA;
  12793. taicpu(hp1).loadref(0, NewRef);
  12794. TransferUsedRegs(TmpUsedRegs);
  12795. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12796. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12797. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12798. begin
  12799. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12800. { Move what is now the LEA instruction to before the SUB instruction }
  12801. Asml.Remove(hp1);
  12802. Asml.InsertBefore(hp1, p);
  12803. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12804. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  12805. p := hp1;
  12806. end
  12807. else
  12808. begin
  12809. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12810. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  12811. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12812. { hp1 may not be the immediate next instruction under -O3 }
  12813. RemoveCurrentp(p)
  12814. else
  12815. RemoveCurrentp(p, hp1);
  12816. end;
  12817. Result := True;
  12818. end;
  12819. end;
  12820. end;
  12821. end;
  12822. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  12823. begin
  12824. { we can skip all instructions not messing with the stack pointer }
  12825. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  12826. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  12827. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  12828. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  12829. ({(taicpu(hp1).ops=0) or }
  12830. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  12831. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  12832. ) and }
  12833. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  12834. )
  12835. ) do
  12836. GetNextInstruction(hp1,hp1);
  12837. Result:=assigned(hp1);
  12838. end;
  12839. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  12840. var
  12841. hp1, hp2, hp3, hp4, hp5: tai;
  12842. begin
  12843. Result:=false;
  12844. hp5:=nil;
  12845. { replace
  12846. leal(q) x(<stackpointer>),<stackpointer>
  12847. call procname
  12848. leal(q) -x(<stackpointer>),<stackpointer>
  12849. ret
  12850. by
  12851. jmp procname
  12852. but do it only on level 4 because it destroys stack back traces
  12853. }
  12854. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12855. MatchOpType(taicpu(p),top_ref,top_reg) and
  12856. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  12857. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  12858. { the -8 or -24 are not required, but bail out early if possible,
  12859. higher values are unlikely }
  12860. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  12861. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  12862. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  12863. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  12864. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  12865. GetNextInstruction(p, hp1) and
  12866. { Take a copy of hp1 }
  12867. SetAndTest(hp1, hp4) and
  12868. { trick to skip label }
  12869. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  12870. SkipSimpleInstructions(hp1) and
  12871. MatchInstruction(hp1,A_CALL,[S_NO]) and
  12872. GetNextInstruction(hp1, hp2) and
  12873. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  12874. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  12875. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  12876. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  12877. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  12878. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  12879. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  12880. { Segment register will be NR_NO }
  12881. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  12882. GetNextInstruction(hp2, hp3) and
  12883. { trick to skip label }
  12884. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  12885. (MatchInstruction(hp3,A_RET,[S_NO]) or
  12886. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  12887. SetAndTest(hp3,hp5) and
  12888. GetNextInstruction(hp3,hp3) and
  12889. MatchInstruction(hp3,A_RET,[S_NO])
  12890. )
  12891. ) and
  12892. (taicpu(hp3).ops=0) then
  12893. begin
  12894. taicpu(hp1).opcode := A_JMP;
  12895. taicpu(hp1).is_jmp := true;
  12896. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  12897. RemoveCurrentP(p, hp4);
  12898. RemoveInstruction(hp2);
  12899. RemoveInstruction(hp3);
  12900. if Assigned(hp5) then
  12901. begin
  12902. AsmL.Remove(hp5);
  12903. ASmL.InsertBefore(hp5,hp1)
  12904. end;
  12905. Result:=true;
  12906. end;
  12907. end;
  12908. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  12909. {$ifdef x86_64}
  12910. var
  12911. hp1, hp2, hp3, hp4, hp5: tai;
  12912. {$endif x86_64}
  12913. begin
  12914. Result:=false;
  12915. {$ifdef x86_64}
  12916. hp5:=nil;
  12917. { replace
  12918. push %rax
  12919. call procname
  12920. pop %rcx
  12921. ret
  12922. by
  12923. jmp procname
  12924. but do it only on level 4 because it destroys stack back traces
  12925. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  12926. for all supported calling conventions
  12927. }
  12928. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12929. MatchOpType(taicpu(p),top_reg) and
  12930. (taicpu(p).oper[0]^.reg=NR_RAX) and
  12931. GetNextInstruction(p, hp1) and
  12932. { Take a copy of hp1 }
  12933. SetAndTest(hp1, hp4) and
  12934. { trick to skip label }
  12935. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  12936. SkipSimpleInstructions(hp1) and
  12937. MatchInstruction(hp1,A_CALL,[S_NO]) and
  12938. GetNextInstruction(hp1, hp2) and
  12939. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  12940. MatchOpType(taicpu(hp2),top_reg) and
  12941. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  12942. GetNextInstruction(hp2, hp3) and
  12943. { trick to skip label }
  12944. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  12945. (MatchInstruction(hp3,A_RET,[S_NO]) or
  12946. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  12947. SetAndTest(hp3,hp5) and
  12948. GetNextInstruction(hp3,hp3) and
  12949. MatchInstruction(hp3,A_RET,[S_NO])
  12950. )
  12951. ) and
  12952. (taicpu(hp3).ops=0) then
  12953. begin
  12954. taicpu(hp1).opcode := A_JMP;
  12955. taicpu(hp1).is_jmp := true;
  12956. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  12957. RemoveCurrentP(p, hp4);
  12958. RemoveInstruction(hp2);
  12959. RemoveInstruction(hp3);
  12960. if Assigned(hp5) then
  12961. begin
  12962. AsmL.Remove(hp5);
  12963. ASmL.InsertBefore(hp5,hp1)
  12964. end;
  12965. Result:=true;
  12966. end;
  12967. {$endif x86_64}
  12968. end;
  12969. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  12970. var
  12971. Value, RegName: string;
  12972. begin
  12973. Result:=false;
  12974. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  12975. begin
  12976. case taicpu(p).oper[0]^.val of
  12977. 0:
  12978. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  12979. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12980. begin
  12981. { change "mov $0,%reg" into "xor %reg,%reg" }
  12982. taicpu(p).opcode := A_XOR;
  12983. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  12984. Result := True;
  12985. {$ifdef x86_64}
  12986. end
  12987. else if (taicpu(p).opsize = S_Q) then
  12988. begin
  12989. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  12990. { The actual optimization }
  12991. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12992. taicpu(p).changeopsize(S_L);
  12993. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  12994. Result := True;
  12995. end;
  12996. $1..$FFFFFFFF:
  12997. begin
  12998. { Code size reduction by J. Gareth "Kit" Moreton }
  12999. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13000. case taicpu(p).opsize of
  13001. S_Q:
  13002. begin
  13003. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13004. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13005. { The actual optimization }
  13006. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13007. taicpu(p).changeopsize(S_L);
  13008. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13009. Result := True;
  13010. end;
  13011. else
  13012. { Do nothing };
  13013. end;
  13014. {$endif x86_64}
  13015. end;
  13016. -1:
  13017. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13018. if (cs_opt_size in current_settings.optimizerswitches) and
  13019. (taicpu(p).opsize <> S_B) and
  13020. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13021. begin
  13022. { change "mov $-1,%reg" into "or $-1,%reg" }
  13023. { NOTES:
  13024. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13025. - This operation creates a false dependency on the register, so only do it when optimising for size
  13026. - 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
  13027. }
  13028. taicpu(p).opcode := A_OR;
  13029. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13030. Result := True;
  13031. end;
  13032. else
  13033. { Do nothing };
  13034. end;
  13035. end;
  13036. end;
  13037. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13038. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13039. begin
  13040. Result := False;
  13041. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13042. Exit;
  13043. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13044. so don't bother optimising }
  13045. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13046. Exit;
  13047. if (taicpu(p).oper[0]^.typ <> top_const) or
  13048. { If the value can fit into an 8-bit signed integer, a smaller
  13049. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13050. falls within this range }
  13051. (
  13052. (taicpu(p).oper[0]^.val > -128) and
  13053. (taicpu(p).oper[0]^.val <= 127)
  13054. ) then
  13055. Exit;
  13056. { If we're optimising for size, this is acceptable }
  13057. if (cs_opt_size in current_settings.optimizerswitches) then
  13058. Exit(True);
  13059. if (taicpu(p).oper[1]^.typ = top_reg) and
  13060. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13061. Exit(True);
  13062. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13063. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13064. Exit(True);
  13065. end;
  13066. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13067. var
  13068. hp1: tai;
  13069. Value: TCGInt;
  13070. begin
  13071. Result := False;
  13072. if MatchOpType(taicpu(p), top_const, top_reg) then
  13073. begin
  13074. { Detect:
  13075. andw x, %ax (0 <= x < $8000)
  13076. ...
  13077. movzwl %ax,%eax
  13078. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13079. }
  13080. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13081. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13082. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13083. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13084. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13085. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13086. begin
  13087. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13088. taicpu(hp1).opcode := A_CWDE;
  13089. taicpu(hp1).clearop(0);
  13090. taicpu(hp1).clearop(1);
  13091. taicpu(hp1).ops := 0;
  13092. { A change was made, but not with p, so move forward 1 }
  13093. p := tai(p.Next);
  13094. Result := True;
  13095. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13096. end;
  13097. end;
  13098. { If "not x" is a power of 2 (popcnt = 1), change:
  13099. and $x, %reg/ref
  13100. To:
  13101. btr lb(x), %reg/ref
  13102. }
  13103. if IsBTXAcceptable(p) and
  13104. (
  13105. { Make sure a TEST doesn't follow that plays with the register }
  13106. not GetNextInstruction(p, hp1) or
  13107. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13108. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13109. ) then
  13110. begin
  13111. {$push}{$R-}{$Q-}
  13112. { Value is a sign-extended 32-bit integer - just correct it
  13113. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13114. checks to see if this operand is an immediate. }
  13115. Value := not taicpu(p).oper[0]^.val;
  13116. {$pop}
  13117. {$ifdef x86_64}
  13118. if taicpu(p).opsize = S_L then
  13119. {$endif x86_64}
  13120. Value := Value and $FFFFFFFF;
  13121. if (PopCnt(QWord(Value)) = 1) then
  13122. begin
  13123. DebugMsg(SPeepholeOptimization + 'Changed AND (not $0x' + hexstr(taicpu(p).oper[0]^.val, 2) + ') to BTR ' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13124. taicpu(p).opcode := A_BTR;
  13125. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13126. Result := True;
  13127. Exit;
  13128. end;
  13129. end;
  13130. end;
  13131. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13132. begin
  13133. Result := False;
  13134. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13135. Exit;
  13136. { Convert:
  13137. movswl %ax,%eax -> cwtl
  13138. movslq %eax,%rax -> cdqe
  13139. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13140. refer to the same opcode and depends only on the assembler's
  13141. current operand-size attribute. [Kit]
  13142. }
  13143. with taicpu(p) do
  13144. case opsize of
  13145. S_WL:
  13146. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13147. begin
  13148. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13149. opcode := A_CWDE;
  13150. clearop(0);
  13151. clearop(1);
  13152. ops := 0;
  13153. Result := True;
  13154. end;
  13155. {$ifdef x86_64}
  13156. S_LQ:
  13157. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13158. begin
  13159. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13160. opcode := A_CDQE;
  13161. clearop(0);
  13162. clearop(1);
  13163. ops := 0;
  13164. Result := True;
  13165. end;
  13166. {$endif x86_64}
  13167. else
  13168. ;
  13169. end;
  13170. end;
  13171. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13172. var
  13173. hp1, hp2: tai;
  13174. IdentityMask, Shift: TCGInt;
  13175. LimitSize: Topsize;
  13176. DoNotMerge: Boolean;
  13177. begin
  13178. Result := False;
  13179. { All these optimisations work on "shr const,%reg" }
  13180. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13181. Exit;
  13182. DoNotMerge := False;
  13183. Shift := taicpu(p).oper[0]^.val;
  13184. LimitSize := taicpu(p).opsize;
  13185. hp1 := p;
  13186. repeat
  13187. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13188. Break;
  13189. { Detect:
  13190. shr x, %reg
  13191. and y, %reg
  13192. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13193. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13194. }
  13195. case taicpu(hp1).opcode of
  13196. A_AND:
  13197. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13198. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13199. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13200. begin
  13201. { Make sure the FLAGS register isn't in use }
  13202. TransferUsedRegs(TmpUsedRegs);
  13203. hp2 := p;
  13204. repeat
  13205. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13206. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13207. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13208. begin
  13209. { Generate the identity mask }
  13210. case taicpu(p).opsize of
  13211. S_B:
  13212. IdentityMask := $FF shr Shift;
  13213. S_W:
  13214. IdentityMask := $FFFF shr Shift;
  13215. S_L:
  13216. IdentityMask := $FFFFFFFF shr Shift;
  13217. {$ifdef x86_64}
  13218. S_Q:
  13219. { We need to force the operands to be unsigned 64-bit
  13220. integers otherwise the wrong value is generated }
  13221. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13222. {$endif x86_64}
  13223. else
  13224. InternalError(2022081501);
  13225. end;
  13226. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13227. begin
  13228. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13229. { All the possible 1 bits are covered, so we can remove the AND }
  13230. hp2 := tai(hp1.Previous);
  13231. RemoveInstruction(hp1);
  13232. { p wasn't actually changed, so don't set Result to True,
  13233. but a change was nonetheless made elsewhere }
  13234. Include(OptsToCheck, aoc_ForceNewIteration);
  13235. { Do another pass in case other AND or MOVZX instructions
  13236. follow }
  13237. hp1 := hp2;
  13238. Continue;
  13239. end;
  13240. end;
  13241. end;
  13242. A_TEST, A_CMP, A_Jcc:
  13243. { Skip over conditional jumps and relevant comparisons }
  13244. Continue;
  13245. A_MOVZX:
  13246. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13247. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13248. begin
  13249. { Since the original register is being read as is, subsequent
  13250. SHRs must not be merged at this point }
  13251. DoNotMerge := True;
  13252. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13253. begin
  13254. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13255. begin
  13256. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13257. { All the possible 1 bits are covered, so we can remove the AND }
  13258. hp2 := tai(hp1.Previous);
  13259. RemoveInstruction(hp1);
  13260. hp1 := hp2;
  13261. end
  13262. else { Different register target }
  13263. begin
  13264. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13265. taicpu(hp1).opcode := A_MOV;
  13266. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13267. case taicpu(hp1).opsize of
  13268. S_BW:
  13269. taicpu(hp1).opsize := S_W;
  13270. S_BL, S_WL:
  13271. taicpu(hp1).opsize := S_L;
  13272. else
  13273. InternalError(2022081503);
  13274. end;
  13275. end;
  13276. end
  13277. else if (Shift > 0) and
  13278. (taicpu(p).opsize = S_W) and
  13279. (taicpu(hp1).opsize = S_WL) and
  13280. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13281. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13282. begin
  13283. { Detect:
  13284. shr x, %ax (x > 0)
  13285. ...
  13286. movzwl %ax,%eax
  13287. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13288. }
  13289. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13290. taicpu(hp1).opcode := A_CWDE;
  13291. taicpu(hp1).clearop(0);
  13292. taicpu(hp1).clearop(1);
  13293. taicpu(hp1).ops := 0;
  13294. end;
  13295. { Move onto the next instruction }
  13296. Continue;
  13297. end;
  13298. A_SHL, A_SAL, A_SHR:
  13299. if (taicpu(hp1).opsize <= LimitSize) and
  13300. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13301. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13302. begin
  13303. { Make sure the sizes don't exceed the register size limit
  13304. (measured by the shift value falling below the limit) }
  13305. if taicpu(hp1).opsize < LimitSize then
  13306. LimitSize := taicpu(hp1).opsize;
  13307. if taicpu(hp1).opcode = A_SHR then
  13308. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13309. else
  13310. begin
  13311. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13312. DoNotMerge := True;
  13313. end;
  13314. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13315. Break;
  13316. { Since we've established that the combined shift is within
  13317. limits, we can actually combine the adjacent SHR
  13318. instructions even if they're different sizes }
  13319. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13320. begin
  13321. hp2 := tai(hp1.Previous);
  13322. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13323. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13324. RemoveInstruction(hp1);
  13325. hp1 := hp2;
  13326. end;
  13327. { Move onto the next instruction }
  13328. Continue;
  13329. end;
  13330. else
  13331. ;
  13332. end;
  13333. Break;
  13334. until False;
  13335. { Detect the following (looking backwards):
  13336. shr %cl,%reg
  13337. shr x, %reg
  13338. Swap the two SHR instructions to minimise a pipeline stall.
  13339. }
  13340. if GetLastInstruction(p, hp1) and
  13341. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13342. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13343. { First operand will be %cl }
  13344. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13345. { Just to be sure }
  13346. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13347. begin
  13348. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13349. { Moving the entries this way ensures the register tracking remains correct }
  13350. Asml.Remove(p);
  13351. Asml.InsertBefore(p, hp1);
  13352. p := hp1;
  13353. { Don't set Result to True because the current instruction is now
  13354. "shr %cl,%reg" and there's nothing more we can do with it }
  13355. end;
  13356. end;
  13357. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13358. var
  13359. hp1, hp2: tai;
  13360. Opposite, SecondOpposite: TAsmOp;
  13361. NewCond: TAsmCond;
  13362. begin
  13363. Result := False;
  13364. { Change:
  13365. add/sub 128,(dest)
  13366. To:
  13367. sub/add -128,(dest)
  13368. This generaally takes fewer bytes to encode because -128 can be stored
  13369. in a signed byte, whereas +128 cannot.
  13370. }
  13371. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13372. begin
  13373. if taicpu(p).opcode = A_ADD then
  13374. Opposite := A_SUB
  13375. else
  13376. Opposite := A_ADD;
  13377. { Be careful if the flags are in use, because the CF flag inverts
  13378. when changing from ADD to SUB and vice versa }
  13379. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13380. GetNextInstruction(p, hp1) then
  13381. begin
  13382. TransferUsedRegs(TmpUsedRegs);
  13383. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13384. hp2 := hp1;
  13385. { Scan ahead to check if everything's safe }
  13386. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13387. begin
  13388. if (hp1.typ <> ait_instruction) then
  13389. { Probably unsafe since the flags are still in use }
  13390. Exit;
  13391. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13392. { Stop searching at an unconditional jump }
  13393. Break;
  13394. if not
  13395. (
  13396. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13397. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13398. ) and
  13399. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13400. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13401. Exit;
  13402. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13403. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13404. { Move to the next instruction }
  13405. GetNextInstruction(hp1, hp1);
  13406. end;
  13407. while Assigned(hp2) and (hp2 <> hp1) do
  13408. begin
  13409. NewCond := C_None;
  13410. case taicpu(hp2).condition of
  13411. C_A, C_NBE:
  13412. NewCond := C_BE;
  13413. C_B, C_C, C_NAE:
  13414. NewCond := C_AE;
  13415. C_AE, C_NB, C_NC:
  13416. NewCond := C_B;
  13417. C_BE, C_NA:
  13418. NewCond := C_A;
  13419. else
  13420. { No change needed };
  13421. end;
  13422. if NewCond <> C_None then
  13423. begin
  13424. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13425. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13426. taicpu(hp2).condition := NewCond;
  13427. end
  13428. else
  13429. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13430. begin
  13431. { Because of the flipping of the carry bit, to ensure
  13432. the operation remains equivalent, ADC becomes SBB
  13433. and vice versa, and the constant is not-inverted.
  13434. If multiple ADCs or SBBs appear in a row, each one
  13435. changed causes the carry bit to invert, so they all
  13436. need to be flipped }
  13437. if taicpu(hp2).opcode = A_ADC then
  13438. SecondOpposite := A_SBB
  13439. else
  13440. SecondOpposite := A_ADC;
  13441. if taicpu(hp2).oper[0]^.typ <> top_const then
  13442. { Should have broken out of this optimisation already }
  13443. InternalError(2021112901);
  13444. 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]^) + ' -> ' +
  13445. 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);
  13446. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  13447. taicpu(hp2).opcode := SecondOpposite;
  13448. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  13449. end;
  13450. { Move to the next instruction }
  13451. GetNextInstruction(hp2, hp2);
  13452. end;
  13453. if (hp2 <> hp1) then
  13454. InternalError(2021111501);
  13455. end;
  13456. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  13457. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  13458. taicpu(p).opcode := Opposite;
  13459. taicpu(p).oper[0]^.val := -128;
  13460. { No further optimisations can be made on this instruction, so move
  13461. onto the next one to save time }
  13462. p := tai(p.Next);
  13463. UpdateUsedRegs(p);
  13464. Result := True;
  13465. Exit;
  13466. end;
  13467. { Detect:
  13468. add/sub %reg2,(dest)
  13469. add/sub x, (dest)
  13470. (dest can be a register or a reference)
  13471. Swap the instructions to minimise a pipeline stall. This reverses the
  13472. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  13473. optimisations could be made.
  13474. }
  13475. if (taicpu(p).oper[0]^.typ = top_reg) and
  13476. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  13477. (
  13478. (
  13479. (taicpu(p).oper[1]^.typ = top_reg) and
  13480. { We can try searching further ahead if we're writing to a register }
  13481. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  13482. ) or
  13483. (
  13484. (taicpu(p).oper[1]^.typ = top_ref) and
  13485. GetNextInstruction(p, hp1)
  13486. )
  13487. ) and
  13488. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  13489. (taicpu(hp1).oper[0]^.typ = top_const) and
  13490. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  13491. begin
  13492. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  13493. TransferUsedRegs(TmpUsedRegs);
  13494. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13495. hp2 := p;
  13496. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  13497. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  13498. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  13499. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13500. begin
  13501. asml.remove(hp1);
  13502. asml.InsertBefore(hp1, p);
  13503. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  13504. Result := True;
  13505. end;
  13506. end;
  13507. end;
  13508. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  13509. begin
  13510. Result:=false;
  13511. { change "cmp $0, %reg" to "test %reg, %reg" }
  13512. if MatchOpType(taicpu(p),top_const,top_reg) and
  13513. (taicpu(p).oper[0]^.val = 0) then
  13514. begin
  13515. taicpu(p).opcode := A_TEST;
  13516. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  13517. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  13518. Result:=true;
  13519. end;
  13520. end;
  13521. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  13522. var
  13523. IsTestConstX, IsValid : Boolean;
  13524. hp1,hp2 : tai;
  13525. begin
  13526. Result:=false;
  13527. { If x is a power of 2 (popcnt = 1), change:
  13528. or $x, %reg/ref
  13529. To:
  13530. bts lb(x), %reg/ref
  13531. }
  13532. if (taicpu(p).opcode = A_OR) and
  13533. IsBTXAcceptable(p) and
  13534. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  13535. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13536. (
  13537. { Don't optimise if a test instruction follows }
  13538. not GetNextInstruction(p, hp1) or
  13539. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  13540. ) then
  13541. begin
  13542. DebugMsg(SPeepholeOptimization + 'Changed OR $0x' + hexstr(taicpu(p).oper[0]^.val, 2) + ' to BTS ' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Or2Bts)', p);
  13543. taicpu(p).opcode := A_BTS;
  13544. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13545. Result := True;
  13546. Exit;
  13547. end;
  13548. { If x is a power of 2 (popcnt = 1), change:
  13549. test $x, %reg/ref
  13550. je / sete / cmove (or jne / setne)
  13551. To:
  13552. bt lb(x), %reg/ref
  13553. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  13554. }
  13555. if (taicpu(p).opcode = A_TEST) and
  13556. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  13557. (taicpu(p).oper[0]^.typ = top_const) and
  13558. (
  13559. (cs_opt_size in current_settings.optimizerswitches) or
  13560. (
  13561. (taicpu(p).oper[1]^.typ = top_reg) and
  13562. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13563. ) or
  13564. (
  13565. (taicpu(p).oper[1]^.typ <> top_reg) and
  13566. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13567. )
  13568. ) and
  13569. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13570. { For sizes less than S_L, the byte size is equal or larger with BT,
  13571. so don't bother optimising }
  13572. (taicpu(p).opsize >= S_L) then
  13573. begin
  13574. IsValid := True;
  13575. { Check the next set of instructions, watching the FLAGS register
  13576. and the conditions used }
  13577. TransferUsedRegs(TmpUsedRegs);
  13578. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13579. hp1 := p;
  13580. hp2 := nil;
  13581. while GetNextInstruction(hp1, hp1) do
  13582. begin
  13583. if not Assigned(hp2) then
  13584. { The first instruction after TEST }
  13585. hp2 := hp1;
  13586. if (hp1.typ <> ait_instruction) then
  13587. begin
  13588. { If the flags are no longer in use, everything is fine }
  13589. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13590. IsValid := False;
  13591. Break;
  13592. end;
  13593. case taicpu(hp1).condition of
  13594. C_None:
  13595. begin
  13596. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13597. { Something is not quite normal, so play safe and don't change }
  13598. IsValid := False;
  13599. Break;
  13600. end;
  13601. C_E, C_Z, C_NE, C_NZ:
  13602. { This is fine };
  13603. else
  13604. begin
  13605. { Unsupported condition }
  13606. IsValid := False;
  13607. Break;
  13608. end;
  13609. end;
  13610. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13611. end;
  13612. if IsValid then
  13613. begin
  13614. while hp2 <> hp1 do
  13615. begin
  13616. case taicpu(hp2).condition of
  13617. C_Z, C_E:
  13618. taicpu(hp2).condition := C_NC;
  13619. C_NZ, C_NE:
  13620. taicpu(hp2).condition := C_C;
  13621. else
  13622. { Should not get this by this point }
  13623. InternalError(2022110701);
  13624. end;
  13625. GetNextInstruction(hp2, hp2);
  13626. end;
  13627. DebugMsg(SPeepholeOptimization + 'Changed TEST $0x' + hexstr(taicpu(p).oper[0]^.val, 2) + ' to BT ' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Test2Bt)', p);
  13628. taicpu(p).opcode := A_BT;
  13629. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13630. Result := True;
  13631. Exit;
  13632. end;
  13633. end;
  13634. { removes the line marked with (x) from the sequence
  13635. and/or/xor/add/sub/... $x, %y
  13636. test/or %y, %y | test $-1, %y (x)
  13637. j(n)z _Label
  13638. as the first instruction already adjusts the ZF
  13639. %y operand may also be a reference }
  13640. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  13641. MatchOperand(taicpu(p).oper[0]^,-1);
  13642. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  13643. GetLastInstruction(p, hp1) and
  13644. (tai(hp1).typ = ait_instruction) and
  13645. GetNextInstruction(p,hp2) and
  13646. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  13647. case taicpu(hp1).opcode Of
  13648. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  13649. { These two instructions set the zero flag if the result is zero }
  13650. A_POPCNT, A_LZCNT:
  13651. begin
  13652. if (
  13653. { With POPCNT, an input of zero will set the zero flag
  13654. because the population count of zero is zero }
  13655. (taicpu(hp1).opcode = A_POPCNT) and
  13656. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  13657. (
  13658. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  13659. { Faster than going through the second half of the 'or'
  13660. condition below }
  13661. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  13662. )
  13663. ) or (
  13664. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  13665. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13666. { and in case of carry for A(E)/B(E)/C/NC }
  13667. (
  13668. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  13669. (
  13670. (taicpu(hp1).opcode <> A_ADD) and
  13671. (taicpu(hp1).opcode <> A_SUB) and
  13672. (taicpu(hp1).opcode <> A_LZCNT)
  13673. )
  13674. )
  13675. ) then
  13676. begin
  13677. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  13678. RemoveCurrentP(p, hp2);
  13679. Result:=true;
  13680. Exit;
  13681. end;
  13682. end;
  13683. A_SHL, A_SAL, A_SHR, A_SAR:
  13684. begin
  13685. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  13686. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  13687. { therefore, it's only safe to do this optimization for }
  13688. { shifts by a (nonzero) constant }
  13689. (taicpu(hp1).oper[0]^.typ = top_const) and
  13690. (taicpu(hp1).oper[0]^.val <> 0) and
  13691. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13692. { and in case of carry for A(E)/B(E)/C/NC }
  13693. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13694. begin
  13695. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  13696. RemoveCurrentP(p, hp2);
  13697. Result:=true;
  13698. Exit;
  13699. end;
  13700. end;
  13701. A_DEC, A_INC, A_NEG:
  13702. begin
  13703. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  13704. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13705. { and in case of carry for A(E)/B(E)/C/NC }
  13706. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13707. begin
  13708. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  13709. RemoveCurrentP(p, hp2);
  13710. Result:=true;
  13711. Exit;
  13712. end;
  13713. end;
  13714. A_ANDN, A_BZHI:
  13715. begin
  13716. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  13717. { Only the zero and sign flags are consistent with what the result is }
  13718. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  13719. begin
  13720. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  13721. RemoveCurrentP(p, hp2);
  13722. Result:=true;
  13723. Exit;
  13724. end;
  13725. end;
  13726. A_BEXTR:
  13727. begin
  13728. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  13729. { Only the zero flag is set }
  13730. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13731. begin
  13732. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  13733. RemoveCurrentP(p, hp2);
  13734. Result:=true;
  13735. Exit;
  13736. end;
  13737. end;
  13738. else
  13739. ;
  13740. end; { case }
  13741. { change "test $-1,%reg" into "test %reg,%reg" }
  13742. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  13743. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  13744. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  13745. if MatchInstruction(p, A_OR, []) and
  13746. { Can only match if they're both registers }
  13747. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  13748. begin
  13749. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  13750. taicpu(p).opcode := A_TEST;
  13751. { No need to set Result to True, as we've done all the optimisations we can }
  13752. end;
  13753. end;
  13754. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  13755. var
  13756. hp1,hp3 : tai;
  13757. {$ifndef x86_64}
  13758. hp2 : taicpu;
  13759. {$endif x86_64}
  13760. begin
  13761. Result:=false;
  13762. hp3:=nil;
  13763. {$ifndef x86_64}
  13764. { don't do this on modern CPUs, this really hurts them due to
  13765. broken call/ret pairing }
  13766. if (current_settings.optimizecputype < cpu_Pentium2) and
  13767. not(cs_create_pic in current_settings.moduleswitches) and
  13768. GetNextInstruction(p, hp1) and
  13769. MatchInstruction(hp1,A_JMP,[S_NO]) and
  13770. MatchOpType(taicpu(hp1),top_ref) and
  13771. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  13772. begin
  13773. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  13774. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  13775. InsertLLItem(p.previous, p, hp2);
  13776. taicpu(p).opcode := A_JMP;
  13777. taicpu(p).is_jmp := true;
  13778. RemoveInstruction(hp1);
  13779. Result:=true;
  13780. end
  13781. else
  13782. {$endif x86_64}
  13783. { replace
  13784. call procname
  13785. ret
  13786. by
  13787. jmp procname
  13788. but do it only on level 4 because it destroys stack back traces
  13789. else if the subroutine is marked as no return, remove the ret
  13790. }
  13791. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  13792. (po_noreturn in current_procinfo.procdef.procoptions)) and
  13793. GetNextInstruction(p, hp1) and
  13794. (MatchInstruction(hp1,A_RET,[S_NO]) or
  13795. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  13796. SetAndTest(hp1,hp3) and
  13797. GetNextInstruction(hp1,hp1) and
  13798. MatchInstruction(hp1,A_RET,[S_NO])
  13799. )
  13800. ) and
  13801. (taicpu(hp1).ops=0) then
  13802. begin
  13803. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13804. { we might destroy stack alignment here if we do not do a call }
  13805. (target_info.stackalign<=sizeof(SizeUInt)) then
  13806. begin
  13807. taicpu(p).opcode := A_JMP;
  13808. taicpu(p).is_jmp := true;
  13809. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  13810. end
  13811. else
  13812. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  13813. RemoveInstruction(hp1);
  13814. if Assigned(hp3) then
  13815. begin
  13816. AsmL.Remove(hp3);
  13817. AsmL.InsertBefore(hp3,p)
  13818. end;
  13819. Result:=true;
  13820. end;
  13821. end;
  13822. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  13823. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  13824. begin
  13825. case OpSize of
  13826. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13827. Result := (Val <= $FF) and (Val >= -128);
  13828. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13829. Result := (Val <= $FFFF) and (Val >= -32768);
  13830. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  13831. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  13832. else
  13833. Result := True;
  13834. end;
  13835. end;
  13836. var
  13837. hp1, hp2 : tai;
  13838. SizeChange: Boolean;
  13839. PreMessage: string;
  13840. begin
  13841. Result := False;
  13842. if (taicpu(p).oper[0]^.typ = top_reg) and
  13843. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13844. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  13845. begin
  13846. { Change (using movzbl %al,%eax as an example):
  13847. movzbl %al, %eax movzbl %al, %eax
  13848. cmpl x, %eax testl %eax,%eax
  13849. To:
  13850. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  13851. movzbl %al, %eax movzbl %al, %eax
  13852. Smaller instruction and minimises pipeline stall as the CPU
  13853. doesn't have to wait for the register to get zero-extended. [Kit]
  13854. Also allow if the smaller of the two registers is being checked,
  13855. as this still removes the false dependency.
  13856. }
  13857. if
  13858. (
  13859. (
  13860. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  13861. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  13862. ) or (
  13863. { If MatchOperand returns True, they must both be registers }
  13864. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  13865. )
  13866. ) and
  13867. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  13868. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  13869. begin
  13870. 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);
  13871. asml.Remove(hp1);
  13872. asml.InsertBefore(hp1, p);
  13873. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  13874. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  13875. begin
  13876. taicpu(hp1).opcode := A_TEST;
  13877. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  13878. end;
  13879. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13880. case taicpu(p).opsize of
  13881. S_BW, S_BL:
  13882. begin
  13883. SizeChange := taicpu(hp1).opsize <> S_B;
  13884. taicpu(hp1).changeopsize(S_B);
  13885. end;
  13886. S_WL:
  13887. begin
  13888. SizeChange := taicpu(hp1).opsize <> S_W;
  13889. taicpu(hp1).changeopsize(S_W);
  13890. end
  13891. else
  13892. InternalError(2020112701);
  13893. end;
  13894. UpdateUsedRegs(tai(p.Next));
  13895. { Check if the register is used aferwards - if not, we can
  13896. remove the movzx instruction completely }
  13897. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  13898. begin
  13899. { Hp1 is a better position than p for debugging purposes }
  13900. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  13901. RemoveCurrentp(p, hp1);
  13902. Result := True;
  13903. end;
  13904. if SizeChange then
  13905. DebugMsg(SPeepholeOptimization + PreMessage +
  13906. 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)
  13907. else
  13908. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  13909. Exit;
  13910. end;
  13911. { Change (using movzwl %ax,%eax as an example):
  13912. movzwl %ax, %eax
  13913. movb %al, (dest) (Register is smaller than read register in movz)
  13914. To:
  13915. movb %al, (dest) (Move one back to avoid a false dependency)
  13916. movzwl %ax, %eax
  13917. }
  13918. if (taicpu(hp1).opcode = A_MOV) and
  13919. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13920. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  13921. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  13922. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  13923. begin
  13924. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  13925. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  13926. asml.Remove(hp1);
  13927. asml.InsertBefore(hp1, p);
  13928. if taicpu(hp1).oper[1]^.typ = top_reg then
  13929. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13930. { Check if the register is used aferwards - if not, we can
  13931. remove the movzx instruction completely }
  13932. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  13933. begin
  13934. { Hp1 is a better position than p for debugging purposes }
  13935. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  13936. RemoveCurrentp(p, hp1);
  13937. Result := True;
  13938. end;
  13939. Exit;
  13940. end;
  13941. end;
  13942. end;
  13943. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  13944. var
  13945. hp1: tai;
  13946. {$ifdef x86_64}
  13947. PreMessage, RegName: string;
  13948. {$endif x86_64}
  13949. begin
  13950. Result := False;
  13951. { If x is a power of 2 (popcnt = 1), change:
  13952. xor $x, %reg/ref
  13953. To:
  13954. btc lb(x), %reg/ref
  13955. }
  13956. if IsBTXAcceptable(p) and
  13957. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  13958. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13959. (
  13960. { Don't optimise if a test instruction follows }
  13961. not GetNextInstruction(p, hp1) or
  13962. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  13963. ) then
  13964. begin
  13965. DebugMsg(SPeepholeOptimization + 'Changed XOR $0x' + hexstr(taicpu(p).oper[0]^.val, 2) + ' to BTC ' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Xor2Btc)', p);
  13966. taicpu(p).opcode := A_BTC;
  13967. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13968. Result := True;
  13969. Exit;
  13970. end;
  13971. {$ifdef x86_64}
  13972. { Code size reduction by J. Gareth "Kit" Moreton }
  13973. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  13974. as this removes the REX prefix }
  13975. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  13976. Exit;
  13977. if taicpu(p).oper[0]^.typ <> top_reg then
  13978. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  13979. InternalError(2018011500);
  13980. case taicpu(p).opsize of
  13981. S_Q:
  13982. begin
  13983. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  13984. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  13985. { The actual optimization }
  13986. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13987. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13988. taicpu(p).changeopsize(S_L);
  13989. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  13990. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  13991. end;
  13992. else
  13993. ;
  13994. end;
  13995. {$endif x86_64}
  13996. end;
  13997. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  13998. var
  13999. XReg: TRegister;
  14000. begin
  14001. Result := False;
  14002. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14003. Smaller encoding and slightly faster on some platforms (also works for
  14004. ZMM-sized registers) }
  14005. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14006. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14007. begin
  14008. XReg := taicpu(p).oper[0]^.reg;
  14009. if (taicpu(p).oper[1]^.reg = XReg) then
  14010. begin
  14011. taicpu(p).changeopsize(S_XMM);
  14012. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14013. if (cs_opt_size in current_settings.optimizerswitches) then
  14014. begin
  14015. { Change input registers to %xmm0 to reduce size. Note that
  14016. there's a risk of a false dependency doing this, so only
  14017. optimise for size here }
  14018. XReg := NR_XMM0;
  14019. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14020. end
  14021. else
  14022. begin
  14023. setsubreg(XReg, R_SUBMMX);
  14024. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14025. end;
  14026. taicpu(p).oper[0]^.reg := XReg;
  14027. taicpu(p).oper[1]^.reg := XReg;
  14028. Result := True;
  14029. end;
  14030. end;
  14031. end;
  14032. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14033. var
  14034. OperIdx: Integer;
  14035. begin
  14036. for OperIdx := 0 to p.ops - 1 do
  14037. if p.oper[OperIdx]^.typ = top_ref then
  14038. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14039. end;
  14040. end.