aoptx86.pas 753 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600
  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. aoc_DoPass2JccOpts
  35. );
  36. TX86AsmOptimizer = class(TAsmOptimizer)
  37. { some optimizations are very expensive to check, so the
  38. pre opt pass can be used to set some flags, depending on the found
  39. instructions if it is worth to check a certain optimization }
  40. OptsToCheck : set of TOptsToCheck;
  41. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  42. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  43. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  44. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  45. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  46. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  47. how many instructions away that Next is from Current is.
  48. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  49. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  50. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  51. potentially allowing further optimisation (although it might need to know if
  52. it crossed a conditional jump. }
  53. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  54. {
  55. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  56. the use of a register by allocs/dealloc, so it can ignore calls.
  57. In the following example, GetNextInstructionUsingReg will return the second movq,
  58. GetNextInstructionUsingRegTrackingUse won't.
  59. movq %rdi,%rax
  60. # Register rdi released
  61. # Register rdi allocated
  62. movq %rax,%rdi
  63. While in this example:
  64. movq %rdi,%rax
  65. call proc
  66. movq %rdi,%rax
  67. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  68. won't.
  69. }
  70. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  71. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  72. { returns true if any of the registers in ref are modified by any
  73. instruction between p1 and p2, or if those instructions write to the
  74. reference }
  75. function RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  76. private
  77. function SkipSimpleInstructions(var hp1: tai): Boolean;
  78. protected
  79. class function IsMOVZXAcceptable: Boolean; static; inline;
  80. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  81. { Attempts to allocate a volatile integer register for use between p and hp,
  82. using AUsedRegs for the current register usage information. Returns NR_NO
  83. if no free register could be found }
  84. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { Attempts to allocate a volatile MM register for use between p and hp,
  86. using AUsedRegs for the current register usage information. Returns NR_NO
  87. if no free register could be found }
  88. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  89. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  90. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  91. { checks whether reading the value in reg1 depends on the value of reg2. This
  92. is very similar to SuperRegisterEquals, except it takes into account that
  93. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  94. depend on the value in AH). }
  95. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  96. { Replaces all references to AOldReg in a memory reference to ANewReg }
  97. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Replaces all references to AOldReg in an operand to ANewReg }
  99. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  100. { Replaces all references to AOldReg in an instruction to ANewReg,
  101. except where the register is being written }
  102. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  103. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  104. or writes to a global symbol }
  105. class function IsRefSafe(const ref: PReference): Boolean; static;
  106. { Returns true if the given MOV instruction can be safely converted to CMOV }
  107. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  108. { Like UpdateUsedRegs, but ignores deallocations }
  109. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  110. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  111. class function IsBTXAcceptable(p : tai) : boolean; static;
  112. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  113. conversion was successful }
  114. function ConvertLEA(const p : taicpu): Boolean;
  115. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  116. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  117. procedure DebugMsg(const s : string; p : tai);inline;
  118. class function IsExitCode(p : tai) : boolean; static;
  119. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  120. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  121. procedure RemoveLastDeallocForFuncRes(p : tai);
  122. function DoArithCombineOpt(var p : tai) : Boolean;
  123. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  124. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  125. function PrePeepholeOptSxx(var p : tai) : boolean;
  126. function PrePeepholeOptIMUL(var p : tai) : boolean;
  127. function PrePeepholeOptAND(var p : tai) : boolean;
  128. function OptPass1Test(var p: tai): boolean;
  129. function OptPass1Add(var p: tai): boolean;
  130. function OptPass1AND(var p : tai) : boolean;
  131. function OptPass1CMOVcc(var p: tai): Boolean;
  132. function OptPass1_V_MOVAP(var p : tai) : boolean;
  133. function OptPass1VOP(var p : tai) : boolean;
  134. function OptPass1MOV(var p : tai) : boolean;
  135. function OptPass1Movx(var p : tai) : boolean;
  136. function OptPass1MOVXX(var p : tai) : boolean;
  137. function OptPass1OP(var p : tai) : boolean;
  138. function OptPass1LEA(var p : tai) : boolean;
  139. function OptPass1Sub(var p : tai) : boolean;
  140. function OptPass1SHLSAL(var p : tai) : boolean;
  141. function OptPass1SHR(var p : tai) : boolean;
  142. function OptPass1FSTP(var p : tai) : boolean;
  143. function OptPass1FLD(var p : tai) : boolean;
  144. function OptPass1Cmp(var p : tai) : boolean;
  145. function OptPass1PXor(var p : tai) : boolean;
  146. function OptPass1VPXor(var p: tai): boolean;
  147. function OptPass1Imul(var p : tai) : boolean;
  148. function OptPass1Jcc(var p : tai) : boolean;
  149. function OptPass1SHXX(var p: tai): boolean;
  150. function OptPass1VMOVDQ(var p: tai): Boolean;
  151. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  152. function OptPass1STCCLC(var p: tai): Boolean;
  153. function OptPass2STCCLC(var p: tai): Boolean;
  154. function OptPass2CMOVcc(var p: tai): Boolean;
  155. function OptPass2Movx(var p : tai): Boolean;
  156. function OptPass2MOV(var p : tai) : boolean;
  157. function OptPass2Imul(var p : tai) : boolean;
  158. function OptPass2Jmp(var p : tai) : boolean;
  159. function OptPass2Jcc(var p : tai) : boolean;
  160. function OptPass2Lea(var p: tai): Boolean;
  161. function OptPass2SUB(var p: tai): Boolean;
  162. function OptPass2ADD(var p : tai): Boolean;
  163. function OptPass2SETcc(var p : tai) : boolean;
  164. function OptPass2Cmp(var p: tai): Boolean;
  165. function OptPass2Test(var p: tai): Boolean;
  166. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  167. function PostPeepholeOptMov(var p : tai) : Boolean;
  168. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  169. function PostPeepholeOptXor(var p : tai) : Boolean;
  170. function PostPeepholeOptAnd(var p : tai) : boolean;
  171. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  172. function PostPeepholeOptCmp(var p : tai) : Boolean;
  173. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  174. function PostPeepholeOptCall(var p : tai) : Boolean;
  175. function PostPeepholeOptLea(var p : tai) : Boolean;
  176. function PostPeepholeOptPush(var p: tai): Boolean;
  177. function PostPeepholeOptShr(var p : tai) : boolean;
  178. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  179. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  180. function PostPeepholeOptRET(var p: tai): Boolean;
  181. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  182. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  183. function TrySwapMovOp(var p, hp1: tai): Boolean;
  184. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  185. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  186. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  187. { Processor-dependent reference optimisation }
  188. class procedure OptimizeRefs(var p: taicpu); static;
  189. end;
  190. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  191. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  192. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  193. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  194. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  195. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  196. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  197. {$if max_operands>2}
  198. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  199. {$endif max_operands>2}
  200. function RefsEqual(const r1, r2: treference): boolean;
  201. { Like RefsEqual, but doesn't compare the offsets }
  202. function RefsAlmostEqual(const r1, r2: treference): boolean;
  203. { Note that Result is set to True if the references COULD overlap but the
  204. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  205. might still overlap because %reg2 could be equal to %reg1-4 }
  206. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  207. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  208. { returns true, if ref is a reference using only the registers passed as base and index
  209. and having an offset }
  210. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  211. implementation
  212. uses
  213. cutils,verbose,
  214. systems,
  215. globals,
  216. cpuinfo,
  217. procinfo,
  218. paramgr,
  219. aasmbase,
  220. aoptbase,aoptutils,
  221. symconst,symsym,
  222. cgx86,
  223. itcpugas;
  224. {$ifndef 8086}
  225. const
  226. MAX_CMOV_INSTRUCTIONS = 4;
  227. MAX_CMOV_REGISTERS = 8;
  228. type
  229. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  230. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  231. tsProcessed);
  232. { For OptPass2Jcc }
  233. TCMOVTracking = object
  234. private
  235. CMOVScore, ConstCount: LongInt;
  236. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  237. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  238. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  239. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  240. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  241. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  242. fOptimizer: TX86AsmOptimizer;
  243. fLabel: TAsmSymbol;
  244. fInsertionPoint,
  245. fCondition,
  246. fInitialJump,
  247. fFirstMovBlock,
  248. fFirstMovBlockStop,
  249. fSecondJump,
  250. fThirdJump,
  251. fSecondMovBlock,
  252. fSecondMovBlockStop,
  253. fMidLabel,
  254. fEndLabel,
  255. fAllocationRange: tai;
  256. fState: TCMovTrackingState;
  257. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  258. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  259. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  260. public
  261. RegisterTracking: TAllUsedRegs;
  262. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  263. destructor Done;
  264. procedure Process(out new_p: tai);
  265. property State: TCMovTrackingState read fState;
  266. end;
  267. PCMOVTracking = ^TCMOVTracking;
  268. {$endif 8086}
  269. {$ifdef DEBUG_AOPTCPU}
  270. const
  271. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  272. {$else DEBUG_AOPTCPU}
  273. { Empty strings help the optimizer to remove string concatenations that won't
  274. ever appear to the user on release builds. [Kit] }
  275. const
  276. SPeepholeOptimization = '';
  277. {$endif DEBUG_AOPTCPU}
  278. LIST_STEP_SIZE = 4;
  279. type
  280. TJumpTrackingItem = class(TLinkedListItem)
  281. private
  282. FSymbol: TAsmSymbol;
  283. FRefs: LongInt;
  284. public
  285. constructor Create(ASymbol: TAsmSymbol);
  286. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  287. property Symbol: TAsmSymbol read FSymbol;
  288. property Refs: LongInt read FRefs;
  289. end;
  290. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  291. begin
  292. inherited Create;
  293. FSymbol := ASymbol;
  294. FRefs := 0;
  295. end;
  296. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  297. begin
  298. Inc(FRefs);
  299. end;
  300. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  301. begin
  302. result :=
  303. (instr.typ = ait_instruction) and
  304. (taicpu(instr).opcode = op) and
  305. ((opsize = []) or (taicpu(instr).opsize in opsize));
  306. end;
  307. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  308. begin
  309. result :=
  310. (instr.typ = ait_instruction) and
  311. ((taicpu(instr).opcode = op1) or
  312. (taicpu(instr).opcode = op2)
  313. ) and
  314. ((opsize = []) or (taicpu(instr).opsize in opsize));
  315. end;
  316. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  317. begin
  318. result :=
  319. (instr.typ = ait_instruction) and
  320. ((taicpu(instr).opcode = op1) or
  321. (taicpu(instr).opcode = op2) or
  322. (taicpu(instr).opcode = op3)
  323. ) and
  324. ((opsize = []) or (taicpu(instr).opsize in opsize));
  325. end;
  326. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  327. const opsize : topsizes) : boolean;
  328. var
  329. op : TAsmOp;
  330. begin
  331. result:=false;
  332. if (instr.typ <> ait_instruction) or
  333. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  334. exit;
  335. for op in ops do
  336. begin
  337. if taicpu(instr).opcode = op then
  338. begin
  339. result:=true;
  340. exit;
  341. end;
  342. end;
  343. end;
  344. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  345. begin
  346. result := (oper.typ = top_reg) and (oper.reg = reg);
  347. end;
  348. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  349. begin
  350. result := (oper.typ = top_const) and (oper.val = a);
  351. end;
  352. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  353. begin
  354. result := oper1.typ = oper2.typ;
  355. if result then
  356. case oper1.typ of
  357. top_const:
  358. Result:=oper1.val = oper2.val;
  359. top_reg:
  360. Result:=oper1.reg = oper2.reg;
  361. top_ref:
  362. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  363. else
  364. internalerror(2013102801);
  365. end
  366. end;
  367. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  368. begin
  369. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  370. if result then
  371. case oper1.typ of
  372. top_const:
  373. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  374. top_reg:
  375. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  376. top_ref:
  377. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  378. else
  379. internalerror(2020052401);
  380. end
  381. end;
  382. function RefsEqual(const r1, r2: treference): boolean;
  383. begin
  384. RefsEqual :=
  385. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  386. (r1.relsymbol = r2.relsymbol) and
  387. (r1.segment = r2.segment) and (r1.base = r2.base) and
  388. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  389. (r1.offset = r2.offset) and
  390. (r1.volatility + r2.volatility = []);
  391. end;
  392. function RefsAlmostEqual(const r1, r2: treference): boolean;
  393. begin
  394. RefsAlmostEqual :=
  395. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  396. (r1.relsymbol = r2.relsymbol) and
  397. (r1.segment = r2.segment) and (r1.base = r2.base) and
  398. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  399. { Don't compare the offsets }
  400. (r1.volatility + r2.volatility = []);
  401. end;
  402. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  403. begin
  404. if (r1.symbol<>r2.symbol) then
  405. { If the index registers are different, there's a chance one could
  406. be set so it equals the other symbol }
  407. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  408. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  409. (r1.relsymbol = r2.relsymbol) and
  410. (r1.segment = r2.segment) and (r1.base = r2.base) and
  411. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  412. (r1.volatility + r2.volatility = []) then
  413. { In this case, it all depends on the offsets }
  414. Exit(abs(r1.offset - r2.offset) < Range);
  415. { There's a chance things MIGHT overlap, so take no chances }
  416. Result := True;
  417. end;
  418. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  419. begin
  420. Result:=(ref.offset=0) and
  421. (ref.scalefactor in [0,1]) and
  422. (ref.segment=NR_NO) and
  423. (ref.symbol=nil) and
  424. (ref.relsymbol=nil) and
  425. ((base=NR_INVALID) or
  426. (ref.base=base)) and
  427. ((index=NR_INVALID) or
  428. (ref.index=index)) and
  429. (ref.volatility=[]);
  430. end;
  431. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  432. begin
  433. Result:=(ref.scalefactor in [0,1]) and
  434. (ref.segment=NR_NO) and
  435. (ref.symbol=nil) and
  436. (ref.relsymbol=nil) and
  437. ((base=NR_INVALID) or
  438. (ref.base=base)) and
  439. ((index=NR_INVALID) or
  440. (ref.index=index)) and
  441. (ref.volatility=[]);
  442. end;
  443. function InstrReadsFlags(p: tai): boolean;
  444. begin
  445. InstrReadsFlags := true;
  446. case p.typ of
  447. ait_instruction:
  448. if InsProp[taicpu(p).opcode].Ch*
  449. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  450. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  451. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  452. exit;
  453. ait_label:
  454. exit;
  455. else
  456. ;
  457. end;
  458. InstrReadsFlags := false;
  459. end;
  460. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  461. begin
  462. Next:=Current;
  463. repeat
  464. Result:=GetNextInstruction(Next,Next);
  465. until not (Result) or
  466. not(cs_opt_level3 in current_settings.optimizerswitches) or
  467. (Next.typ<>ait_instruction) or
  468. RegInInstruction(reg,Next) or
  469. is_calljmp(taicpu(Next).opcode);
  470. end;
  471. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  472. var
  473. GetNextResult: Boolean;
  474. begin
  475. Result:=0;
  476. Next:=Current;
  477. repeat
  478. GetNextResult := GetNextInstruction(Next,Next);
  479. if GetNextResult then
  480. Inc(Result)
  481. else
  482. { Must return zero upon hitting the end of the linked list without a match }
  483. Result := 0;
  484. until not (GetNextResult) or
  485. not(cs_opt_level3 in current_settings.optimizerswitches) or
  486. (Next.typ<>ait_instruction) or
  487. RegInInstruction(reg,Next) or
  488. is_calljmp(taicpu(Next).opcode);
  489. end;
  490. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  491. procedure TrackJump(Symbol: TAsmSymbol);
  492. var
  493. Search: TJumpTrackingItem;
  494. begin
  495. { See if an entry already exists in our jump tracking list
  496. (faster to search backwards due to the higher chance of
  497. matching destinations) }
  498. Search := TJumpTrackingItem(JumpTracking.Last);
  499. while Assigned(Search) do
  500. begin
  501. if Search.Symbol = Symbol then
  502. begin
  503. { Found it - remove it so it can be pushed to the front }
  504. JumpTracking.Remove(Search);
  505. Break;
  506. end;
  507. Search := TJumpTrackingItem(Search.Previous);
  508. end;
  509. if not Assigned(Search) then
  510. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  511. JumpTracking.Concat(Search);
  512. Search.IncRefs;
  513. end;
  514. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  515. var
  516. Search: TJumpTrackingItem;
  517. begin
  518. Result := False;
  519. { See if this label appears in the tracking list }
  520. Search := TJumpTrackingItem(JumpTracking.Last);
  521. while Assigned(Search) do
  522. begin
  523. if Search.Symbol = Symbol then
  524. begin
  525. { Found it - let's see what we can discover }
  526. if Search.Symbol.getrefs = Search.Refs then
  527. begin
  528. { Success - all the references are accounted for }
  529. JumpTracking.Remove(Search);
  530. Search.Free;
  531. { It is logically impossible for CrossJump to be false here
  532. because we must have run into a conditional jump for
  533. this label at some point }
  534. if not CrossJump then
  535. InternalError(2022041710);
  536. if JumpTracking.First = nil then
  537. { Tracking list is now empty - no more cross jumps }
  538. CrossJump := False;
  539. Result := True;
  540. Exit;
  541. end;
  542. { If the references don't match, it's possible to enter
  543. this label through other means, so drop out }
  544. Exit;
  545. end;
  546. Search := TJumpTrackingItem(Search.Previous);
  547. end;
  548. end;
  549. var
  550. Next_Label: tai;
  551. begin
  552. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  553. Next := Current;
  554. repeat
  555. Result := GetNextInstruction(Next,Next);
  556. if not Result then
  557. Break;
  558. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  559. if is_calljmpuncondret(taicpu(Next).opcode) then
  560. begin
  561. if (taicpu(Next).opcode = A_JMP) and
  562. { Remove dead code now to save time }
  563. RemoveDeadCodeAfterJump(taicpu(Next)) then
  564. { A jump was removed, but not the current instruction, and
  565. Result doesn't necessarily translate into an optimisation
  566. routine's Result, so use the "Force New Iteration" flag so
  567. mark a new pass }
  568. Include(OptsToCheck, aoc_ForceNewIteration);
  569. if not Assigned(JumpTracking) then
  570. begin
  571. { Cross-label optimisations often causes other optimisations
  572. to perform worse because they're not given the chance to
  573. optimise locally. In this case, don't do the cross-label
  574. optimisations yet, but flag them as a potential possibility
  575. for the next iteration of Pass 1 }
  576. if not NotFirstIteration then
  577. Include(OptsToCheck, aoc_ForceNewIteration);
  578. end
  579. else if IsJumpToLabel(taicpu(Next)) and
  580. GetNextInstruction(Next, Next_Label) then
  581. begin
  582. { If we have JMP .lbl, and the label after it has all of its
  583. references tracked, then this is probably an if-else style of
  584. block and we can keep tracking. If the label for this jump
  585. then appears later and is fully tracked, then it's the end
  586. of the if-else blocks and the code paths converge (thus
  587. marking the end of the cross-jump) }
  588. if (Next_Label.typ = ait_label) then
  589. begin
  590. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  591. begin
  592. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  593. Next := Next_Label;
  594. { CrossJump gets set to false by LabelAccountedFor if the
  595. list is completely emptied (as it indicates that all
  596. code paths have converged). We could avoid this nuance
  597. by moving the TrackJump call to before the
  598. LabelAccountedFor call, but this is slower in situations
  599. where LabelAccountedFor would return False due to the
  600. creation of a new object that is not used and destroyed
  601. soon after. }
  602. CrossJump := True;
  603. Continue;
  604. end;
  605. end
  606. else if (Next_Label.typ <> ait_marker) then
  607. { We just did a RemoveDeadCodeAfterJump, so either we find
  608. a label, the end of the procedure or some kind of marker}
  609. InternalError(2022041720);
  610. end;
  611. Result := False;
  612. Exit;
  613. end
  614. else
  615. begin
  616. if not Assigned(JumpTracking) then
  617. begin
  618. { Cross-label optimisations often causes other optimisations
  619. to perform worse because they're not given the chance to
  620. optimise locally. In this case, don't do the cross-label
  621. optimisations yet, but flag them as a potential possibility
  622. for the next iteration of Pass 1 }
  623. if not NotFirstIteration then
  624. Include(OptsToCheck, aoc_ForceNewIteration);
  625. end
  626. else if IsJumpToLabel(taicpu(Next)) then
  627. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  628. else
  629. { Conditional jumps should always be a jump to label }
  630. InternalError(2022041701);
  631. CrossJump := True;
  632. Continue;
  633. end;
  634. if Next.typ = ait_label then
  635. begin
  636. if not Assigned(JumpTracking) then
  637. begin
  638. { Cross-label optimisations often causes other optimisations
  639. to perform worse because they're not given the chance to
  640. optimise locally. In this case, don't do the cross-label
  641. optimisations yet, but flag them as a potential possibility
  642. for the next iteration of Pass 1 }
  643. if not NotFirstIteration then
  644. Include(OptsToCheck, aoc_ForceNewIteration);
  645. end
  646. else if LabelAccountedFor(tai_label(Next).labsym) then
  647. Continue;
  648. { If we reach here, we're at a label that hasn't been seen before
  649. (or JumpTracking was nil) }
  650. Break;
  651. end;
  652. until not Result or
  653. not (cs_opt_level3 in current_settings.optimizerswitches) or
  654. not (Next.typ in [ait_label, ait_instruction]) or
  655. RegInInstruction(reg,Next);
  656. end;
  657. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  658. begin
  659. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  660. begin
  661. Result:=GetNextInstruction(Current,Next);
  662. exit;
  663. end;
  664. Next:=tai(Current.Next);
  665. Result:=false;
  666. while assigned(Next) do
  667. begin
  668. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  669. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  670. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  671. exit
  672. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  673. begin
  674. Result:=true;
  675. exit;
  676. end;
  677. Next:=tai(Next.Next);
  678. end;
  679. end;
  680. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  681. begin
  682. Result:=RegReadByInstruction(reg,hp);
  683. end;
  684. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  685. var
  686. p: taicpu;
  687. opcount: longint;
  688. begin
  689. RegReadByInstruction := false;
  690. if hp.typ <> ait_instruction then
  691. exit;
  692. p := taicpu(hp);
  693. case p.opcode of
  694. A_CALL:
  695. regreadbyinstruction := true;
  696. A_IMUL:
  697. case p.ops of
  698. 1:
  699. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  700. (
  701. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  702. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  703. );
  704. 2,3:
  705. regReadByInstruction :=
  706. reginop(reg,p.oper[0]^) or
  707. reginop(reg,p.oper[1]^);
  708. else
  709. InternalError(2019112801);
  710. end;
  711. A_MUL:
  712. begin
  713. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  714. (
  715. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  716. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  717. );
  718. end;
  719. A_IDIV,A_DIV:
  720. begin
  721. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  722. (
  723. (getregtype(reg)=R_INTREGISTER) and
  724. (
  725. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  726. )
  727. );
  728. end;
  729. else
  730. begin
  731. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  732. begin
  733. RegReadByInstruction := false;
  734. exit;
  735. end;
  736. for opcount := 0 to p.ops-1 do
  737. if (p.oper[opCount]^.typ = top_ref) and
  738. RegInRef(reg,p.oper[opcount]^.ref^) then
  739. begin
  740. RegReadByInstruction := true;
  741. exit
  742. end;
  743. { special handling for SSE MOVSD }
  744. if (p.opcode=A_MOVSD) and (p.ops>0) then
  745. begin
  746. if p.ops<>2 then
  747. internalerror(2017042702);
  748. regReadByInstruction := reginop(reg,p.oper[0]^) or
  749. (
  750. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  751. );
  752. exit;
  753. end;
  754. with insprop[p.opcode] do
  755. begin
  756. case getregtype(reg) of
  757. R_INTREGISTER:
  758. begin
  759. case getsupreg(reg) of
  760. RS_EAX:
  761. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  762. begin
  763. RegReadByInstruction := true;
  764. exit
  765. end;
  766. RS_ECX:
  767. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  768. begin
  769. RegReadByInstruction := true;
  770. exit
  771. end;
  772. RS_EDX:
  773. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  774. begin
  775. RegReadByInstruction := true;
  776. exit
  777. end;
  778. RS_EBX:
  779. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  780. begin
  781. RegReadByInstruction := true;
  782. exit
  783. end;
  784. RS_ESP:
  785. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  786. begin
  787. RegReadByInstruction := true;
  788. exit
  789. end;
  790. RS_EBP:
  791. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  792. begin
  793. RegReadByInstruction := true;
  794. exit
  795. end;
  796. RS_ESI:
  797. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. RS_EDI:
  803. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  804. begin
  805. RegReadByInstruction := true;
  806. exit
  807. end;
  808. end;
  809. end;
  810. R_MMREGISTER:
  811. begin
  812. case getsupreg(reg) of
  813. RS_XMM0:
  814. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  815. begin
  816. RegReadByInstruction := true;
  817. exit
  818. end;
  819. end;
  820. end;
  821. else
  822. ;
  823. end;
  824. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  825. begin
  826. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  827. begin
  828. case p.condition of
  829. C_A,C_NBE, { CF=0 and ZF=0 }
  830. C_BE,C_NA: { CF=1 or ZF=1 }
  831. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  832. C_AE,C_NB,C_NC, { CF=0 }
  833. C_B,C_NAE,C_C: { CF=1 }
  834. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  835. C_NE,C_NZ, { ZF=0 }
  836. C_E,C_Z: { ZF=1 }
  837. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  838. C_G,C_NLE, { ZF=0 and SF=OF }
  839. C_LE,C_NG: { ZF=1 or SF<>OF }
  840. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  841. C_GE,C_NL, { SF=OF }
  842. C_L,C_NGE: { SF<>OF }
  843. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  844. C_NO, { OF=0 }
  845. C_O: { OF=1 }
  846. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  847. C_NP,C_PO, { PF=0 }
  848. C_P,C_PE: { PF=1 }
  849. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  850. C_NS, { SF=0 }
  851. C_S: { SF=1 }
  852. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  853. else
  854. internalerror(2017042701);
  855. end;
  856. if RegReadByInstruction then
  857. exit;
  858. end;
  859. case getsubreg(reg) of
  860. R_SUBW,R_SUBD,R_SUBQ:
  861. RegReadByInstruction :=
  862. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  863. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  864. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  865. R_SUBFLAGCARRY:
  866. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  867. R_SUBFLAGPARITY:
  868. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  869. R_SUBFLAGAUXILIARY:
  870. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  871. R_SUBFLAGZERO:
  872. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  873. R_SUBFLAGSIGN:
  874. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  875. R_SUBFLAGOVERFLOW:
  876. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  877. R_SUBFLAGINTERRUPT:
  878. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  879. R_SUBFLAGDIRECTION:
  880. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  881. else
  882. internalerror(2017042601);
  883. end;
  884. exit;
  885. end;
  886. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  887. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  888. (p.oper[0]^.reg=p.oper[1]^.reg) then
  889. exit;
  890. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  891. begin
  892. RegReadByInstruction := true;
  893. exit
  894. end;
  895. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  896. begin
  897. RegReadByInstruction := true;
  898. exit
  899. end;
  900. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  901. begin
  902. RegReadByInstruction := true;
  903. exit
  904. end;
  905. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  906. begin
  907. RegReadByInstruction := true;
  908. exit
  909. end;
  910. end;
  911. end;
  912. end;
  913. end;
  914. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  915. begin
  916. result:=false;
  917. if p1.typ<>ait_instruction then
  918. exit;
  919. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  920. exit(true);
  921. if (getregtype(reg)=R_INTREGISTER) and
  922. { change information for xmm movsd are not correct }
  923. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  924. begin
  925. { Handle instructions that behave differently depending on the size and operand count }
  926. case taicpu(p1).opcode of
  927. A_MUL, A_DIV, A_IDIV:
  928. if taicpu(p1).opsize = S_B then
  929. Result := (getsupreg(Reg) = RS_EAX)
  930. else
  931. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  932. A_IMUL:
  933. if taicpu(p1).ops = 1 then
  934. begin
  935. if taicpu(p1).opsize = S_B then
  936. Result := (getsupreg(Reg) = RS_EAX)
  937. else
  938. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  939. end;
  940. { If ops are greater than 1, call inherited method }
  941. else
  942. case getsupreg(reg) of
  943. { RS_EAX = RS_RAX on x86-64 }
  944. RS_EAX:
  945. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  946. RS_ECX:
  947. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  948. RS_EDX:
  949. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  950. RS_EBX:
  951. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  952. RS_ESP:
  953. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  954. RS_EBP:
  955. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  956. RS_ESI:
  957. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  958. RS_EDI:
  959. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  960. else
  961. ;
  962. end;
  963. end;
  964. if result then
  965. exit;
  966. end
  967. else if getregtype(reg)=R_MMREGISTER then
  968. begin
  969. case getsupreg(reg) of
  970. RS_XMM0:
  971. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  972. else
  973. ;
  974. end;
  975. if result then
  976. exit;
  977. end
  978. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  979. begin
  980. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  981. exit(true);
  982. case getsubreg(reg) of
  983. R_SUBFLAGCARRY:
  984. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  985. R_SUBFLAGPARITY:
  986. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  987. R_SUBFLAGAUXILIARY:
  988. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  989. R_SUBFLAGZERO:
  990. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  991. R_SUBFLAGSIGN:
  992. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  993. R_SUBFLAGOVERFLOW:
  994. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  995. R_SUBFLAGINTERRUPT:
  996. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  997. R_SUBFLAGDIRECTION:
  998. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  999. R_SUBW,R_SUBD,R_SUBQ:
  1000. { Everything except the direction bits }
  1001. Result:=
  1002. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  1003. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1004. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1005. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1006. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1007. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  1008. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  1009. else
  1010. ;
  1011. end;
  1012. if result then
  1013. exit;
  1014. end
  1015. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  1016. exit(true);
  1017. Result:=inherited RegInInstruction(Reg, p1);
  1018. end;
  1019. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1020. const
  1021. WriteOps: array[0..3] of set of TInsChange =
  1022. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1023. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1024. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1025. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1026. var
  1027. OperIdx: Integer;
  1028. begin
  1029. Result := False;
  1030. if p1.typ <> ait_instruction then
  1031. exit;
  1032. with insprop[taicpu(p1).opcode] do
  1033. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1034. begin
  1035. case getsubreg(reg) of
  1036. R_SUBW,R_SUBD,R_SUBQ:
  1037. Result :=
  1038. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1039. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1040. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1041. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1042. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1043. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1044. R_SUBFLAGCARRY:
  1045. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1046. R_SUBFLAGPARITY:
  1047. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1048. R_SUBFLAGAUXILIARY:
  1049. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1050. R_SUBFLAGZERO:
  1051. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1052. R_SUBFLAGSIGN:
  1053. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1054. R_SUBFLAGOVERFLOW:
  1055. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1056. R_SUBFLAGINTERRUPT:
  1057. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1058. R_SUBFLAGDIRECTION:
  1059. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1060. else
  1061. internalerror(2017042602);
  1062. end;
  1063. exit;
  1064. end;
  1065. case taicpu(p1).opcode of
  1066. A_CALL:
  1067. { We could potentially set Result to False if the register in
  1068. question is non-volatile for the subroutine's calling convention,
  1069. but this would require detecting the calling convention in use and
  1070. also assuming that the routine doesn't contain malformed assembly
  1071. language, for example... so it could only be done under -O4 as it
  1072. would be considered a side-effect. [Kit] }
  1073. Result := True;
  1074. A_MOVSD:
  1075. { special handling for SSE MOVSD }
  1076. if (taicpu(p1).ops>0) then
  1077. begin
  1078. if taicpu(p1).ops<>2 then
  1079. internalerror(2017042703);
  1080. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1081. end;
  1082. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1083. so fix it here (FK)
  1084. }
  1085. A_VMOVSS,
  1086. A_VMOVSD:
  1087. begin
  1088. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1089. exit;
  1090. end;
  1091. A_MUL, A_DIV, A_IDIV:
  1092. begin
  1093. if taicpu(p1).opsize = S_B then
  1094. Result := (getsupreg(Reg) = RS_EAX)
  1095. else
  1096. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1097. end;
  1098. A_IMUL:
  1099. begin
  1100. if taicpu(p1).ops = 1 then
  1101. begin
  1102. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1103. end
  1104. else
  1105. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1106. Exit;
  1107. end;
  1108. else
  1109. ;
  1110. end;
  1111. if Result then
  1112. exit;
  1113. with insprop[taicpu(p1).opcode] do
  1114. begin
  1115. if getregtype(reg)=R_INTREGISTER then
  1116. begin
  1117. case getsupreg(reg) of
  1118. RS_EAX:
  1119. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1120. begin
  1121. Result := True;
  1122. exit
  1123. end;
  1124. RS_ECX:
  1125. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1126. begin
  1127. Result := True;
  1128. exit
  1129. end;
  1130. RS_EDX:
  1131. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1132. begin
  1133. Result := True;
  1134. exit
  1135. end;
  1136. RS_EBX:
  1137. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1138. begin
  1139. Result := True;
  1140. exit
  1141. end;
  1142. RS_ESP:
  1143. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1144. begin
  1145. Result := True;
  1146. exit
  1147. end;
  1148. RS_EBP:
  1149. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1150. begin
  1151. Result := True;
  1152. exit
  1153. end;
  1154. RS_ESI:
  1155. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1156. begin
  1157. Result := True;
  1158. exit
  1159. end;
  1160. RS_EDI:
  1161. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1162. begin
  1163. Result := True;
  1164. exit
  1165. end;
  1166. end;
  1167. end;
  1168. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1169. if (WriteOps[OperIdx]*Ch<>[]) and
  1170. { The register doesn't get modified inside a reference }
  1171. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1172. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1173. begin
  1174. Result := true;
  1175. exit
  1176. end;
  1177. end;
  1178. end;
  1179. function TX86AsmOptimizer.RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  1180. const
  1181. WriteOps: array[0..3] of set of TInsChange =
  1182. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1183. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1184. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1185. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1186. var
  1187. X: Integer;
  1188. CurrentP1Size: asizeint;
  1189. begin
  1190. Result := (
  1191. (Ref.base <> NR_NO) and
  1192. {$ifdef x86_64}
  1193. (Ref.base <> NR_RIP) and
  1194. {$endif x86_64}
  1195. RegModifiedBetween(Ref.base, p1, p2)
  1196. ) or
  1197. (
  1198. (Ref.index <> NR_NO) and
  1199. (Ref.index <> Ref.base) and
  1200. RegModifiedBetween(Ref.index, p1, p2)
  1201. );
  1202. { Now check to see if the memory itself is written to }
  1203. if not Result then
  1204. begin
  1205. while assigned(p1) and assigned(p2) and GetNextInstruction(p1,p1) and (p1<>p2) do
  1206. if p1.typ = ait_instruction then
  1207. begin
  1208. CurrentP1Size := topsize2memsize[taicpu(p1).opsize] shr 3; { Convert to bytes }
  1209. with insprop[taicpu(p1).opcode] do
  1210. for X := 0 to taicpu(p1).ops - 1 do
  1211. if (taicpu(p1).oper[X]^.typ = top_ref) and
  1212. RefsAlmostEqual(Ref, taicpu(p1).oper[X]^.ref^) and
  1213. { Catch any potential overlaps }
  1214. (
  1215. (RefSize = 0) or
  1216. ((taicpu(p1).oper[X]^.ref^.offset - Ref.offset) < RefSize)
  1217. ) and
  1218. (
  1219. (CurrentP1Size = 0) or
  1220. ((Ref.offset - taicpu(p1).oper[X]^.ref^.offset) < CurrentP1Size)
  1221. ) and
  1222. { Reference is used, but does the instruction write to it? }
  1223. (
  1224. (Ch_All in Ch) or
  1225. ((WriteOps[X] * Ch) <> [])
  1226. ) then
  1227. begin
  1228. Result := True;
  1229. Break;
  1230. end;
  1231. end;
  1232. end;
  1233. end;
  1234. {$ifdef DEBUG_AOPTCPU}
  1235. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1236. begin
  1237. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1238. end;
  1239. function debug_tostr(i: tcgint): string; inline;
  1240. begin
  1241. Result := tostr(i);
  1242. end;
  1243. function debug_hexstr(i: tcgint): string;
  1244. begin
  1245. Result := '0x';
  1246. case i of
  1247. 0..$FF:
  1248. Result := Result + hexstr(i, 2);
  1249. $100..$FFFF:
  1250. Result := Result + hexstr(i, 4);
  1251. $10000..$FFFFFF:
  1252. Result := Result + hexstr(i, 6);
  1253. $1000000..$FFFFFFFF:
  1254. Result := Result + hexstr(i, 8);
  1255. else
  1256. Result := Result + hexstr(i, 16);
  1257. end;
  1258. end;
  1259. function debug_regname(r: TRegister): string; inline;
  1260. begin
  1261. Result := '%' + std_regname(r);
  1262. end;
  1263. { Debug output function - creates a string representation of an operator }
  1264. function debug_operstr(oper: TOper): string;
  1265. begin
  1266. case oper.typ of
  1267. top_const:
  1268. Result := '$' + debug_tostr(oper.val);
  1269. top_reg:
  1270. Result := debug_regname(oper.reg);
  1271. top_ref:
  1272. begin
  1273. if oper.ref^.offset <> 0 then
  1274. Result := debug_tostr(oper.ref^.offset) + '('
  1275. else
  1276. Result := '(';
  1277. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1278. begin
  1279. Result := Result + debug_regname(oper.ref^.base);
  1280. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1281. Result := Result + ',' + debug_regname(oper.ref^.index);
  1282. end
  1283. else
  1284. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1285. Result := Result + debug_regname(oper.ref^.index);
  1286. if (oper.ref^.scalefactor > 1) then
  1287. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1288. else
  1289. Result := Result + ')';
  1290. end;
  1291. else
  1292. Result := '[UNKNOWN]';
  1293. end;
  1294. end;
  1295. function debug_op2str(opcode: tasmop): string; inline;
  1296. begin
  1297. Result := std_op2str[opcode];
  1298. end;
  1299. function debug_opsize2str(opsize: topsize): string; inline;
  1300. begin
  1301. Result := gas_opsize2str[opsize];
  1302. end;
  1303. {$else DEBUG_AOPTCPU}
  1304. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1305. begin
  1306. end;
  1307. function debug_tostr(i: tcgint): string; inline;
  1308. begin
  1309. Result := '';
  1310. end;
  1311. function debug_hexstr(i: tcgint): string; inline;
  1312. begin
  1313. Result := '';
  1314. end;
  1315. function debug_regname(r: TRegister): string; inline;
  1316. begin
  1317. Result := '';
  1318. end;
  1319. function debug_operstr(oper: TOper): string; inline;
  1320. begin
  1321. Result := '';
  1322. end;
  1323. function debug_op2str(opcode: tasmop): string; inline;
  1324. begin
  1325. Result := '';
  1326. end;
  1327. function debug_opsize2str(opsize: topsize): string; inline;
  1328. begin
  1329. Result := '';
  1330. end;
  1331. {$endif DEBUG_AOPTCPU}
  1332. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1333. begin
  1334. {$ifdef x86_64}
  1335. { Always fine on x86-64 }
  1336. Result := True;
  1337. {$else x86_64}
  1338. Result :=
  1339. {$ifdef i8086}
  1340. (current_settings.cputype >= cpu_386) and
  1341. {$endif i8086}
  1342. (
  1343. { Always accept if optimising for size }
  1344. (cs_opt_size in current_settings.optimizerswitches) or
  1345. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1346. (current_settings.optimizecputype >= cpu_Pentium2)
  1347. );
  1348. {$endif x86_64}
  1349. end;
  1350. { Attempts to allocate a volatile integer register for use between p and hp,
  1351. using AUsedRegs for the current register usage information. Returns NR_NO
  1352. if no free register could be found }
  1353. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1354. var
  1355. RegSet: TCPURegisterSet;
  1356. CurrentSuperReg: Integer;
  1357. CurrentReg: TRegister;
  1358. Currentp: tai;
  1359. Breakout: Boolean;
  1360. begin
  1361. Result := NR_NO;
  1362. RegSet :=
  1363. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1364. current_procinfo.saved_regs_int;
  1365. (*
  1366. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1367. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1368. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1369. *)
  1370. for CurrentSuperReg in RegSet do
  1371. begin
  1372. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1373. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1374. {$if defined(i386) or defined(i8086)}
  1375. { If the target size is 8-bit, make sure we can actually encode it }
  1376. and (
  1377. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1378. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1379. )
  1380. {$endif i386 or i8086}
  1381. then
  1382. begin
  1383. Currentp := p;
  1384. Breakout := False;
  1385. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1386. begin
  1387. case Currentp.typ of
  1388. ait_instruction:
  1389. begin
  1390. if RegInInstruction(CurrentReg, Currentp) then
  1391. begin
  1392. Breakout := True;
  1393. Break;
  1394. end;
  1395. { Cannot allocate across an unconditional jump }
  1396. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1397. Exit;
  1398. end;
  1399. ait_marker:
  1400. { Don't try anything more if a marker is hit }
  1401. Exit;
  1402. ait_regalloc:
  1403. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1404. begin
  1405. Breakout := True;
  1406. Break;
  1407. end;
  1408. else
  1409. ;
  1410. end;
  1411. end;
  1412. if Breakout then
  1413. { Try the next register }
  1414. Continue;
  1415. { We have a free register available }
  1416. Result := CurrentReg;
  1417. if not DontAlloc then
  1418. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1419. Exit;
  1420. end;
  1421. end;
  1422. end;
  1423. { Attempts to allocate a volatile MM register for use between p and hp,
  1424. using AUsedRegs for the current register usage information. Returns NR_NO
  1425. if no free register could be found }
  1426. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1427. var
  1428. RegSet: TCPURegisterSet;
  1429. CurrentSuperReg: Integer;
  1430. CurrentReg: TRegister;
  1431. Currentp: tai;
  1432. Breakout: Boolean;
  1433. begin
  1434. Result := NR_NO;
  1435. RegSet :=
  1436. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1437. current_procinfo.saved_regs_mm;
  1438. for CurrentSuperReg in RegSet do
  1439. begin
  1440. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1441. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1442. begin
  1443. Currentp := p;
  1444. Breakout := False;
  1445. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1446. begin
  1447. case Currentp.typ of
  1448. ait_instruction:
  1449. begin
  1450. if RegInInstruction(CurrentReg, Currentp) then
  1451. begin
  1452. Breakout := True;
  1453. Break;
  1454. end;
  1455. { Cannot allocate across an unconditional jump }
  1456. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1457. Exit;
  1458. end;
  1459. ait_marker:
  1460. { Don't try anything more if a marker is hit }
  1461. Exit;
  1462. ait_regalloc:
  1463. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1464. begin
  1465. Breakout := True;
  1466. Break;
  1467. end;
  1468. else
  1469. ;
  1470. end;
  1471. end;
  1472. if Breakout then
  1473. { Try the next register }
  1474. Continue;
  1475. { We have a free register available }
  1476. Result := CurrentReg;
  1477. if not DontAlloc then
  1478. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1479. Exit;
  1480. end;
  1481. end;
  1482. end;
  1483. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1484. begin
  1485. if not SuperRegistersEqual(reg1,reg2) then
  1486. exit(false);
  1487. if getregtype(reg1)<>R_INTREGISTER then
  1488. exit(true); {because SuperRegisterEqual is true}
  1489. case getsubreg(reg1) of
  1490. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1491. higher, it preserves the high bits, so the new value depends on
  1492. reg2's previous value. In other words, it is equivalent to doing:
  1493. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1494. R_SUBL:
  1495. exit(getsubreg(reg2)=R_SUBL);
  1496. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1497. higher, it actually does a:
  1498. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1499. R_SUBH:
  1500. exit(getsubreg(reg2)=R_SUBH);
  1501. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1502. bits of reg2:
  1503. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1504. R_SUBW:
  1505. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1506. { a write to R_SUBD always overwrites every other subregister,
  1507. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1508. R_SUBD,
  1509. R_SUBQ:
  1510. exit(true);
  1511. else
  1512. internalerror(2017042801);
  1513. end;
  1514. end;
  1515. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1516. begin
  1517. if not SuperRegistersEqual(reg1,reg2) then
  1518. exit(false);
  1519. if getregtype(reg1)<>R_INTREGISTER then
  1520. exit(true); {because SuperRegisterEqual is true}
  1521. case getsubreg(reg1) of
  1522. R_SUBL:
  1523. exit(getsubreg(reg2)<>R_SUBH);
  1524. R_SUBH:
  1525. exit(getsubreg(reg2)<>R_SUBL);
  1526. R_SUBW,
  1527. R_SUBD,
  1528. R_SUBQ:
  1529. exit(true);
  1530. else
  1531. internalerror(2017042802);
  1532. end;
  1533. end;
  1534. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1535. var
  1536. hp1 : tai;
  1537. l : TCGInt;
  1538. begin
  1539. result:=false;
  1540. if not(GetNextInstruction(p, hp1)) then
  1541. exit;
  1542. { changes the code sequence
  1543. shr/sar const1, x
  1544. shl const2, x
  1545. to
  1546. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1547. if (taicpu(p).oper[0]^.typ = top_const) and
  1548. MatchInstruction(hp1,A_SHL,[]) and
  1549. (taicpu(hp1).oper[0]^.typ = top_const) and
  1550. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1551. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1552. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1553. begin
  1554. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1555. not(cs_opt_size in current_settings.optimizerswitches) then
  1556. begin
  1557. { shr/sar const1, %reg
  1558. shl const2, %reg
  1559. with const1 > const2 }
  1560. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1561. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1562. taicpu(hp1).opcode := A_AND;
  1563. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1564. case taicpu(p).opsize Of
  1565. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1566. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1567. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1568. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1569. else
  1570. Internalerror(2017050703)
  1571. end;
  1572. end
  1573. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1574. not(cs_opt_size in current_settings.optimizerswitches) then
  1575. begin
  1576. { shr/sar const1, %reg
  1577. shl const2, %reg
  1578. with const1 < const2 }
  1579. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1580. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1581. taicpu(p).opcode := A_AND;
  1582. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1583. case taicpu(p).opsize Of
  1584. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1585. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1586. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1587. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1588. else
  1589. Internalerror(2017050702)
  1590. end;
  1591. end
  1592. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1593. begin
  1594. { shr/sar const1, %reg
  1595. shl const2, %reg
  1596. with const1 = const2 }
  1597. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1598. taicpu(p).opcode := A_AND;
  1599. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1600. case taicpu(p).opsize Of
  1601. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1602. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1603. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1604. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1605. else
  1606. Internalerror(2017050701)
  1607. end;
  1608. RemoveInstruction(hp1);
  1609. end;
  1610. end;
  1611. end;
  1612. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1613. var
  1614. opsize : topsize;
  1615. hp1, hp2 : tai;
  1616. tmpref : treference;
  1617. ShiftValue : Cardinal;
  1618. BaseValue : TCGInt;
  1619. begin
  1620. result:=false;
  1621. opsize:=taicpu(p).opsize;
  1622. { changes certain "imul const, %reg"'s to lea sequences }
  1623. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1624. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1625. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1626. if (taicpu(p).oper[0]^.val = 1) then
  1627. if (taicpu(p).ops = 2) then
  1628. { remove "imul $1, reg" }
  1629. begin
  1630. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1631. Result := RemoveCurrentP(p);
  1632. end
  1633. else
  1634. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1635. begin
  1636. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1637. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1638. asml.InsertAfter(hp1, p);
  1639. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1640. RemoveCurrentP(p, hp1);
  1641. Result := True;
  1642. end
  1643. else if ((taicpu(p).ops <= 2) or
  1644. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1645. not(cs_opt_size in current_settings.optimizerswitches) and
  1646. (not(GetNextInstruction(p, hp1)) or
  1647. not((tai(hp1).typ = ait_instruction) and
  1648. ((taicpu(hp1).opcode=A_Jcc) and
  1649. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1650. begin
  1651. {
  1652. imul X, reg1, reg2 to
  1653. lea (reg1,reg1,Y), reg2
  1654. shl ZZ,reg2
  1655. imul XX, reg1 to
  1656. lea (reg1,reg1,YY), reg1
  1657. shl ZZ,reg2
  1658. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1659. it does not exist as a separate optimization target in FPC though.
  1660. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1661. at most two zeros
  1662. }
  1663. reference_reset(tmpref,1,[]);
  1664. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1665. begin
  1666. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1667. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1668. TmpRef.base := taicpu(p).oper[1]^.reg;
  1669. TmpRef.index := taicpu(p).oper[1]^.reg;
  1670. if not(BaseValue in [3,5,9]) then
  1671. Internalerror(2018110101);
  1672. TmpRef.ScaleFactor := BaseValue-1;
  1673. if (taicpu(p).ops = 2) then
  1674. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1675. else
  1676. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1677. AsmL.InsertAfter(hp1,p);
  1678. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1679. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1680. RemoveCurrentP(p, hp1);
  1681. if ShiftValue>0 then
  1682. begin
  1683. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1684. AsmL.InsertAfter(hp2,hp1);
  1685. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1686. end;
  1687. Result := True;
  1688. end;
  1689. end;
  1690. end;
  1691. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1692. begin
  1693. Result := False;
  1694. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1695. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1696. begin
  1697. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1698. taicpu(p).opcode := A_MOV;
  1699. Result := True;
  1700. end;
  1701. end;
  1702. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1703. var
  1704. p: taicpu absolute hp; { Implicit typecast }
  1705. i: Integer;
  1706. begin
  1707. Result := False;
  1708. if not assigned(hp) or
  1709. (hp.typ <> ait_instruction) then
  1710. Exit;
  1711. Prefetch(insprop[p.opcode]);
  1712. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1713. with insprop[p.opcode] do
  1714. begin
  1715. case getsubreg(reg) of
  1716. R_SUBW,R_SUBD,R_SUBQ:
  1717. Result:=
  1718. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1719. uncommon flags are checked first }
  1720. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1721. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1722. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1723. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1724. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1725. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1726. R_SUBFLAGCARRY:
  1727. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1728. R_SUBFLAGPARITY:
  1729. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1730. R_SUBFLAGAUXILIARY:
  1731. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1732. R_SUBFLAGZERO:
  1733. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1734. R_SUBFLAGSIGN:
  1735. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1736. R_SUBFLAGOVERFLOW:
  1737. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1738. R_SUBFLAGINTERRUPT:
  1739. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1740. R_SUBFLAGDIRECTION:
  1741. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1742. else
  1743. internalerror(2017050501);
  1744. end;
  1745. exit;
  1746. end;
  1747. { Handle special cases first }
  1748. case p.opcode of
  1749. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1750. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1751. begin
  1752. Result :=
  1753. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1754. (p.oper[1]^.typ = top_reg) and
  1755. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1756. (
  1757. (p.oper[0]^.typ = top_const) or
  1758. (
  1759. (p.oper[0]^.typ = top_reg) and
  1760. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1761. ) or (
  1762. (p.oper[0]^.typ = top_ref) and
  1763. not RegInRef(reg,p.oper[0]^.ref^)
  1764. )
  1765. );
  1766. end;
  1767. A_MUL, A_IMUL:
  1768. Result :=
  1769. (
  1770. (p.ops=3) and { IMUL only }
  1771. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1772. (
  1773. (
  1774. (p.oper[1]^.typ=top_reg) and
  1775. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1776. ) or (
  1777. (p.oper[1]^.typ=top_ref) and
  1778. not RegInRef(reg,p.oper[1]^.ref^)
  1779. )
  1780. )
  1781. ) or (
  1782. (
  1783. (p.ops=1) and
  1784. (
  1785. (
  1786. (
  1787. (p.oper[0]^.typ=top_reg) and
  1788. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1789. )
  1790. ) or (
  1791. (p.oper[0]^.typ=top_ref) and
  1792. not RegInRef(reg,p.oper[0]^.ref^)
  1793. )
  1794. ) and (
  1795. (
  1796. (p.opsize=S_B) and
  1797. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1798. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1799. ) or (
  1800. (p.opsize=S_W) and
  1801. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1802. ) or (
  1803. (p.opsize=S_L) and
  1804. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1805. {$ifdef x86_64}
  1806. ) or (
  1807. (p.opsize=S_Q) and
  1808. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1809. {$endif x86_64}
  1810. )
  1811. )
  1812. )
  1813. );
  1814. A_CBW:
  1815. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1816. {$ifndef x86_64}
  1817. A_LDS:
  1818. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1819. A_LES:
  1820. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1821. {$endif not x86_64}
  1822. A_LFS:
  1823. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1824. A_LGS:
  1825. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1826. A_LSS:
  1827. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1828. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1829. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1830. A_LODSB:
  1831. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1832. A_LODSW:
  1833. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1834. {$ifdef x86_64}
  1835. A_LODSQ:
  1836. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1837. {$endif x86_64}
  1838. A_LODSD:
  1839. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1840. A_FSTSW, A_FNSTSW:
  1841. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1842. else
  1843. begin
  1844. with insprop[p.opcode] do
  1845. begin
  1846. if (
  1847. { xor %reg,%reg etc. is classed as a new value }
  1848. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1849. MatchOpType(p, top_reg, top_reg) and
  1850. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1851. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1852. ) then
  1853. begin
  1854. Result := True;
  1855. Exit;
  1856. end;
  1857. { Make sure the entire register is overwritten }
  1858. if (getregtype(reg) = R_INTREGISTER) then
  1859. begin
  1860. if (p.ops > 0) then
  1861. begin
  1862. if RegInOp(reg, p.oper[0]^) then
  1863. begin
  1864. if (p.oper[0]^.typ = top_ref) then
  1865. begin
  1866. if RegInRef(reg, p.oper[0]^.ref^) then
  1867. begin
  1868. Result := False;
  1869. Exit;
  1870. end;
  1871. end
  1872. else if (p.oper[0]^.typ = top_reg) then
  1873. begin
  1874. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1875. begin
  1876. Result := False;
  1877. Exit;
  1878. end
  1879. else if ([Ch_WOp1]*Ch<>[]) then
  1880. begin
  1881. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1882. Result := True
  1883. else
  1884. begin
  1885. Result := False;
  1886. Exit;
  1887. end;
  1888. end;
  1889. end;
  1890. end;
  1891. if (p.ops > 1) then
  1892. begin
  1893. if RegInOp(reg, p.oper[1]^) then
  1894. begin
  1895. if (p.oper[1]^.typ = top_ref) then
  1896. begin
  1897. if RegInRef(reg, p.oper[1]^.ref^) then
  1898. begin
  1899. Result := False;
  1900. Exit;
  1901. end;
  1902. end
  1903. else if (p.oper[1]^.typ = top_reg) then
  1904. begin
  1905. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1906. begin
  1907. Result := False;
  1908. Exit;
  1909. end
  1910. else if ([Ch_WOp2]*Ch<>[]) then
  1911. begin
  1912. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1913. Result := True
  1914. else
  1915. begin
  1916. Result := False;
  1917. Exit;
  1918. end;
  1919. end;
  1920. end;
  1921. end;
  1922. if (p.ops > 2) then
  1923. begin
  1924. if RegInOp(reg, p.oper[2]^) then
  1925. begin
  1926. if (p.oper[2]^.typ = top_ref) then
  1927. begin
  1928. if RegInRef(reg, p.oper[2]^.ref^) then
  1929. begin
  1930. Result := False;
  1931. Exit;
  1932. end;
  1933. end
  1934. else if (p.oper[2]^.typ = top_reg) then
  1935. begin
  1936. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1937. begin
  1938. Result := False;
  1939. Exit;
  1940. end
  1941. else if ([Ch_WOp3]*Ch<>[]) then
  1942. begin
  1943. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1944. Result := True
  1945. else
  1946. begin
  1947. Result := False;
  1948. Exit;
  1949. end;
  1950. end;
  1951. end;
  1952. end;
  1953. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1954. begin
  1955. if (p.oper[3]^.typ = top_ref) then
  1956. begin
  1957. if RegInRef(reg, p.oper[3]^.ref^) then
  1958. begin
  1959. Result := False;
  1960. Exit;
  1961. end;
  1962. end
  1963. else if (p.oper[3]^.typ = top_reg) then
  1964. begin
  1965. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1966. begin
  1967. Result := False;
  1968. Exit;
  1969. end
  1970. else if ([Ch_WOp4]*Ch<>[]) then
  1971. begin
  1972. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1973. Result := True
  1974. else
  1975. begin
  1976. Result := False;
  1977. Exit;
  1978. end;
  1979. end;
  1980. end;
  1981. end;
  1982. end;
  1983. end;
  1984. end;
  1985. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1986. case getsupreg(reg) of
  1987. RS_EAX:
  1988. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1989. begin
  1990. Result := True;
  1991. Exit;
  1992. end;
  1993. RS_ECX:
  1994. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1995. begin
  1996. Result := True;
  1997. Exit;
  1998. end;
  1999. RS_EDX:
  2000. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  2001. begin
  2002. Result := True;
  2003. Exit;
  2004. end;
  2005. RS_EBX:
  2006. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  2007. begin
  2008. Result := True;
  2009. Exit;
  2010. end;
  2011. RS_ESP:
  2012. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  2013. begin
  2014. Result := True;
  2015. Exit;
  2016. end;
  2017. RS_EBP:
  2018. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  2019. begin
  2020. Result := True;
  2021. Exit;
  2022. end;
  2023. RS_ESI:
  2024. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  2025. begin
  2026. Result := True;
  2027. Exit;
  2028. end;
  2029. RS_EDI:
  2030. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  2031. begin
  2032. Result := True;
  2033. Exit;
  2034. end;
  2035. else
  2036. ;
  2037. end;
  2038. end;
  2039. end;
  2040. end;
  2041. end;
  2042. end;
  2043. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  2044. var
  2045. hp2,hp3 : tai;
  2046. begin
  2047. { some x86-64 issue a NOP before the real exit code }
  2048. if MatchInstruction(p,A_NOP,[]) then
  2049. GetNextInstruction(p,p);
  2050. result:=assigned(p) and (p.typ=ait_instruction) and
  2051. ((taicpu(p).opcode = A_RET) or
  2052. ((taicpu(p).opcode=A_LEAVE) and
  2053. GetNextInstruction(p,hp2) and
  2054. MatchInstruction(hp2,A_RET,[S_NO])
  2055. ) or
  2056. (((taicpu(p).opcode=A_LEA) and
  2057. MatchOpType(taicpu(p),top_ref,top_reg) and
  2058. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  2059. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2060. ) and
  2061. GetNextInstruction(p,hp2) and
  2062. MatchInstruction(hp2,A_RET,[S_NO])
  2063. ) or
  2064. ((((taicpu(p).opcode=A_MOV) and
  2065. MatchOpType(taicpu(p),top_reg,top_reg) and
  2066. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  2067. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  2068. ((taicpu(p).opcode=A_LEA) and
  2069. MatchOpType(taicpu(p),top_ref,top_reg) and
  2070. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  2071. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2072. )
  2073. ) and
  2074. GetNextInstruction(p,hp2) and
  2075. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2076. MatchOpType(taicpu(hp2),top_reg) and
  2077. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2078. GetNextInstruction(hp2,hp3) and
  2079. MatchInstruction(hp3,A_RET,[S_NO])
  2080. )
  2081. );
  2082. end;
  2083. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2084. begin
  2085. isFoldableArithOp := False;
  2086. case hp1.opcode of
  2087. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2088. isFoldableArithOp :=
  2089. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2090. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2091. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2092. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2093. (taicpu(hp1).oper[1]^.reg = reg);
  2094. A_INC,A_DEC,A_NEG,A_NOT:
  2095. isFoldableArithOp :=
  2096. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2097. (taicpu(hp1).oper[0]^.reg = reg);
  2098. else
  2099. ;
  2100. end;
  2101. end;
  2102. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2103. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2104. var
  2105. hp2: tai;
  2106. begin
  2107. hp2 := p;
  2108. repeat
  2109. hp2 := tai(hp2.previous);
  2110. if assigned(hp2) and
  2111. (hp2.typ = ait_regalloc) and
  2112. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2113. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2114. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2115. begin
  2116. RemoveInstruction(hp2);
  2117. break;
  2118. end;
  2119. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2120. end;
  2121. begin
  2122. case current_procinfo.procdef.returndef.typ of
  2123. arraydef,recorddef,pointerdef,
  2124. stringdef,enumdef,procdef,objectdef,errordef,
  2125. filedef,setdef,procvardef,
  2126. classrefdef,forwarddef:
  2127. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2128. orddef:
  2129. if current_procinfo.procdef.returndef.size <> 0 then
  2130. begin
  2131. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2132. { for int64/qword }
  2133. if current_procinfo.procdef.returndef.size = 8 then
  2134. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2135. end;
  2136. else
  2137. ;
  2138. end;
  2139. end;
  2140. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2141. var
  2142. hp1: tai;
  2143. operswap: poper;
  2144. begin
  2145. Result := False;
  2146. { Optimise:
  2147. cmov(c) %reg1,%reg2
  2148. mov %reg2,%reg1
  2149. (%reg2 dealloc.)
  2150. To:
  2151. cmov(~c) %reg2,%reg1
  2152. }
  2153. if (taicpu(p).oper[0]^.typ = top_reg) then
  2154. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2155. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2156. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2157. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2158. begin
  2159. TransferUsedRegs(TmpUsedRegs);
  2160. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2161. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2162. begin
  2163. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2164. { Save time by swapping the pointers (they're both registers, so
  2165. we don't need to worry about reference counts) }
  2166. operswap := taicpu(p).oper[0];
  2167. taicpu(p).oper[0] := taicpu(p).oper[1];
  2168. taicpu(p).oper[1] := operswap;
  2169. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2170. RemoveInstruction(hp1);
  2171. { It's still a CMOV, so we can look further ahead }
  2172. Include(OptsToCheck, aoc_ForceNewIteration);
  2173. { But first, let's see if this will get optimised again
  2174. (probably won't happen, but best to be sure) }
  2175. Continue;
  2176. end;
  2177. Break;
  2178. end;
  2179. end;
  2180. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2181. var
  2182. hp1,hp2 : tai;
  2183. begin
  2184. result:=false;
  2185. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2186. begin
  2187. { vmova* reg1,reg1
  2188. =>
  2189. <nop> }
  2190. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2191. begin
  2192. RemoveCurrentP(p);
  2193. result:=true;
  2194. exit;
  2195. end;
  2196. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2197. (hp1.typ = ait_instruction) and
  2198. (
  2199. { Under -O2 and below, the instructions are always adjacent }
  2200. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2201. (taicpu(hp1).ops <= 1) or
  2202. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2203. { If reg1 = reg3, reg1 must not be modified in between }
  2204. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2205. ) then
  2206. begin
  2207. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2208. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2209. begin
  2210. { vmova* reg1,reg2
  2211. ...
  2212. vmova* reg2,reg3
  2213. dealloc reg2
  2214. =>
  2215. vmova* reg1,reg3 }
  2216. TransferUsedRegs(TmpUsedRegs);
  2217. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2218. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2219. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2220. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2221. begin
  2222. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2223. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2224. TransferUsedRegs(TmpUsedRegs);
  2225. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2226. RemoveInstruction(hp1);
  2227. result:=true;
  2228. exit;
  2229. end;
  2230. { special case:
  2231. vmova* reg1,<op>
  2232. ...
  2233. vmova* <op>,reg1
  2234. =>
  2235. vmova* reg1,<op> }
  2236. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2237. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2238. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2239. ) then
  2240. begin
  2241. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2242. RemoveInstruction(hp1);
  2243. result:=true;
  2244. exit;
  2245. end
  2246. end
  2247. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2248. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2249. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2250. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2251. ) and
  2252. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2253. begin
  2254. { vmova* reg1,reg2
  2255. ...
  2256. vmovs* reg2,<op>
  2257. dealloc reg2
  2258. =>
  2259. vmovs* reg1,<op> }
  2260. TransferUsedRegs(TmpUsedRegs);
  2261. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2262. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2263. begin
  2264. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2265. taicpu(p).opcode:=taicpu(hp1).opcode;
  2266. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2267. TransferUsedRegs(TmpUsedRegs);
  2268. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2269. RemoveInstruction(hp1);
  2270. result:=true;
  2271. exit;
  2272. end
  2273. end;
  2274. if MatchInstruction(hp1,[A_VFMADDPD,
  2275. A_VFMADD132PD,
  2276. A_VFMADD132PS,
  2277. A_VFMADD132SD,
  2278. A_VFMADD132SS,
  2279. A_VFMADD213PD,
  2280. A_VFMADD213PS,
  2281. A_VFMADD213SD,
  2282. A_VFMADD213SS,
  2283. A_VFMADD231PD,
  2284. A_VFMADD231PS,
  2285. A_VFMADD231SD,
  2286. A_VFMADD231SS,
  2287. A_VFMADDSUB132PD,
  2288. A_VFMADDSUB132PS,
  2289. A_VFMADDSUB213PD,
  2290. A_VFMADDSUB213PS,
  2291. A_VFMADDSUB231PD,
  2292. A_VFMADDSUB231PS,
  2293. A_VFMSUB132PD,
  2294. A_VFMSUB132PS,
  2295. A_VFMSUB132SD,
  2296. A_VFMSUB132SS,
  2297. A_VFMSUB213PD,
  2298. A_VFMSUB213PS,
  2299. A_VFMSUB213SD,
  2300. A_VFMSUB213SS,
  2301. A_VFMSUB231PD,
  2302. A_VFMSUB231PS,
  2303. A_VFMSUB231SD,
  2304. A_VFMSUB231SS,
  2305. A_VFMSUBADD132PD,
  2306. A_VFMSUBADD132PS,
  2307. A_VFMSUBADD213PD,
  2308. A_VFMSUBADD213PS,
  2309. A_VFMSUBADD231PD,
  2310. A_VFMSUBADD231PS,
  2311. A_VFNMADD132PD,
  2312. A_VFNMADD132PS,
  2313. A_VFNMADD132SD,
  2314. A_VFNMADD132SS,
  2315. A_VFNMADD213PD,
  2316. A_VFNMADD213PS,
  2317. A_VFNMADD213SD,
  2318. A_VFNMADD213SS,
  2319. A_VFNMADD231PD,
  2320. A_VFNMADD231PS,
  2321. A_VFNMADD231SD,
  2322. A_VFNMADD231SS,
  2323. A_VFNMSUB132PD,
  2324. A_VFNMSUB132PS,
  2325. A_VFNMSUB132SD,
  2326. A_VFNMSUB132SS,
  2327. A_VFNMSUB213PD,
  2328. A_VFNMSUB213PS,
  2329. A_VFNMSUB213SD,
  2330. A_VFNMSUB213SS,
  2331. A_VFNMSUB231PD,
  2332. A_VFNMSUB231PS,
  2333. A_VFNMSUB231SD,
  2334. A_VFNMSUB231SS],[S_NO]) and
  2335. { we mix single and double opperations here because we assume that the compiler
  2336. generates vmovapd only after double operations and vmovaps only after single operations }
  2337. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2338. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2339. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2340. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2341. begin
  2342. TransferUsedRegs(TmpUsedRegs);
  2343. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2344. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2345. begin
  2346. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2347. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2348. RemoveCurrentP(p)
  2349. else
  2350. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2351. RemoveInstruction(hp2);
  2352. end;
  2353. end
  2354. else if (hp1.typ = ait_instruction) and
  2355. (((taicpu(p).opcode=A_MOVAPS) and
  2356. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2357. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2358. ((taicpu(p).opcode=A_MOVAPD) and
  2359. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2360. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2361. ) and
  2362. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2363. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2364. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2365. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2366. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2367. { change
  2368. movapX reg,reg2
  2369. addsX/subsX/... reg3, reg2
  2370. movapX reg2,reg
  2371. to
  2372. addsX/subsX/... reg3,reg
  2373. }
  2374. begin
  2375. TransferUsedRegs(TmpUsedRegs);
  2376. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2377. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2378. begin
  2379. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2380. debug_op2str(taicpu(p).opcode)+' '+
  2381. debug_op2str(taicpu(hp1).opcode)+' '+
  2382. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2383. { we cannot eliminate the first move if
  2384. the operations uses the same register for source and dest }
  2385. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2386. { Remember that hp1 is not necessarily the immediate
  2387. next instruction }
  2388. RemoveCurrentP(p);
  2389. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2390. RemoveInstruction(hp2);
  2391. result:=true;
  2392. end;
  2393. end
  2394. else if (hp1.typ = ait_instruction) and
  2395. (((taicpu(p).opcode=A_VMOVAPD) and
  2396. (taicpu(hp1).opcode=A_VCOMISD)) or
  2397. ((taicpu(p).opcode=A_VMOVAPS) and
  2398. ((taicpu(hp1).opcode=A_VCOMISS))
  2399. )
  2400. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2401. { change
  2402. movapX reg,reg1
  2403. vcomisX reg1,reg1
  2404. to
  2405. vcomisX reg,reg
  2406. }
  2407. begin
  2408. TransferUsedRegs(TmpUsedRegs);
  2409. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2410. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2411. begin
  2412. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2413. debug_op2str(taicpu(p).opcode)+' '+
  2414. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2415. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2416. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2417. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2418. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2419. RemoveCurrentP(p);
  2420. result:=true;
  2421. exit;
  2422. end;
  2423. end
  2424. end;
  2425. end;
  2426. end;
  2427. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2428. var
  2429. hp1 : tai;
  2430. begin
  2431. result:=false;
  2432. { replace
  2433. V<Op>X %mreg1,%mreg2,%mreg3
  2434. VMovX %mreg3,%mreg4
  2435. dealloc %mreg3
  2436. by
  2437. V<Op>X %mreg1,%mreg2,%mreg4
  2438. ?
  2439. }
  2440. if GetNextInstruction(p,hp1) and
  2441. { we mix single and double operations here because we assume that the compiler
  2442. generates vmovapd only after double operations and vmovaps only after single operations }
  2443. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2444. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2445. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2446. begin
  2447. TransferUsedRegs(TmpUsedRegs);
  2448. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2449. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2450. begin
  2451. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2452. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2453. RemoveInstruction(hp1);
  2454. result:=true;
  2455. end;
  2456. end;
  2457. end;
  2458. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2459. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2460. begin
  2461. Result := False;
  2462. { For safety reasons, only check for exact register matches }
  2463. { Check base register }
  2464. if (ref.base = AOldReg) then
  2465. begin
  2466. ref.base := ANewReg;
  2467. Result := True;
  2468. end;
  2469. { Check index register }
  2470. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2471. begin
  2472. ref.index := ANewReg;
  2473. Result := True;
  2474. end;
  2475. end;
  2476. { Replaces all references to AOldReg in an operand to ANewReg }
  2477. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2478. var
  2479. OldSupReg, NewSupReg: TSuperRegister;
  2480. OldSubReg, NewSubReg: TSubRegister;
  2481. OldRegType: TRegisterType;
  2482. ThisOper: POper;
  2483. begin
  2484. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2485. Result := False;
  2486. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2487. InternalError(2020011801);
  2488. OldSupReg := getsupreg(AOldReg);
  2489. OldSubReg := getsubreg(AOldReg);
  2490. OldRegType := getregtype(AOldReg);
  2491. NewSupReg := getsupreg(ANewReg);
  2492. NewSubReg := getsubreg(ANewReg);
  2493. if OldRegType <> getregtype(ANewReg) then
  2494. InternalError(2020011802);
  2495. if OldSubReg <> NewSubReg then
  2496. InternalError(2020011803);
  2497. case ThisOper^.typ of
  2498. top_reg:
  2499. if (
  2500. (ThisOper^.reg = AOldReg) or
  2501. (
  2502. (OldRegType = R_INTREGISTER) and
  2503. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2504. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2505. (
  2506. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2507. {$ifndef x86_64}
  2508. and (
  2509. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2510. don't have an 8-bit representation }
  2511. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2512. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2513. )
  2514. {$endif x86_64}
  2515. )
  2516. )
  2517. ) then
  2518. begin
  2519. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2520. Result := True;
  2521. end;
  2522. top_ref:
  2523. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2524. Result := True;
  2525. else
  2526. ;
  2527. end;
  2528. end;
  2529. { Replaces all references to AOldReg in an instruction to ANewReg }
  2530. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2531. const
  2532. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2533. var
  2534. OperIdx: Integer;
  2535. begin
  2536. Result := False;
  2537. for OperIdx := 0 to p.ops - 1 do
  2538. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2539. begin
  2540. { The shift and rotate instructions can only use CL }
  2541. if not (
  2542. (OperIdx = 0) and
  2543. { This second condition just helps to avoid unnecessarily
  2544. calling MatchInstruction for 10 different opcodes }
  2545. (p.oper[0]^.reg = NR_CL) and
  2546. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2547. ) then
  2548. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2549. end
  2550. else if p.oper[OperIdx]^.typ = top_ref then
  2551. { It's okay to replace registers in references that get written to }
  2552. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2553. end;
  2554. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2555. begin
  2556. Result :=
  2557. (ref^.index = NR_NO) and
  2558. (
  2559. {$ifdef x86_64}
  2560. (
  2561. (ref^.base = NR_RIP) and
  2562. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2563. ) or
  2564. {$endif x86_64}
  2565. (ref^.refaddr = addr_full) or
  2566. (ref^.base = NR_STACK_POINTER_REG) or
  2567. (ref^.base = current_procinfo.framepointer)
  2568. );
  2569. end;
  2570. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2571. var
  2572. l: asizeint;
  2573. begin
  2574. Result := False;
  2575. { Should have been checked previously }
  2576. if p.opcode <> A_LEA then
  2577. InternalError(2020072501);
  2578. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2579. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2580. not(cs_opt_size in current_settings.optimizerswitches) then
  2581. exit;
  2582. with p.oper[0]^.ref^ do
  2583. begin
  2584. if (base <> p.oper[1]^.reg) or
  2585. (index <> NR_NO) or
  2586. assigned(symbol) then
  2587. exit;
  2588. l:=offset;
  2589. if (l=1) and UseIncDec then
  2590. begin
  2591. p.opcode:=A_INC;
  2592. p.loadreg(0,p.oper[1]^.reg);
  2593. p.ops:=1;
  2594. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2595. end
  2596. else if (l=-1) and UseIncDec then
  2597. begin
  2598. p.opcode:=A_DEC;
  2599. p.loadreg(0,p.oper[1]^.reg);
  2600. p.ops:=1;
  2601. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2602. end
  2603. else
  2604. begin
  2605. if (l<0) and (l<>-2147483648) then
  2606. begin
  2607. p.opcode:=A_SUB;
  2608. p.loadConst(0,-l);
  2609. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2610. end
  2611. else
  2612. begin
  2613. p.opcode:=A_ADD;
  2614. p.loadConst(0,l);
  2615. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2616. end;
  2617. end;
  2618. end;
  2619. Result := True;
  2620. end;
  2621. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2622. var
  2623. CurrentReg, ReplaceReg: TRegister;
  2624. begin
  2625. Result := False;
  2626. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2627. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2628. case hp.opcode of
  2629. A_FSTSW, A_FNSTSW,
  2630. A_IN, A_INS, A_OUT, A_OUTS,
  2631. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2632. { These routines have explicit operands, but they are restricted in
  2633. what they can be (e.g. IN and OUT can only read from AL, AX or
  2634. EAX. }
  2635. Exit;
  2636. A_IMUL:
  2637. begin
  2638. { The 1-operand version writes to implicit registers
  2639. The 2-operand version reads from the first operator, and reads
  2640. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2641. the 3-operand version reads from a register that it doesn't write to
  2642. }
  2643. case hp.ops of
  2644. 1:
  2645. if (
  2646. (
  2647. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2648. ) or
  2649. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2650. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2651. begin
  2652. Result := True;
  2653. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2654. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2655. end;
  2656. 2:
  2657. { Only modify the first parameter }
  2658. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2659. begin
  2660. Result := True;
  2661. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2662. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2663. end;
  2664. 3:
  2665. { Only modify the second parameter }
  2666. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2667. begin
  2668. Result := True;
  2669. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2670. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2671. end;
  2672. else
  2673. InternalError(2020012901);
  2674. end;
  2675. end;
  2676. else
  2677. if (hp.ops > 0) and
  2678. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2679. begin
  2680. Result := True;
  2681. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2682. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2683. end;
  2684. end;
  2685. end;
  2686. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2687. var
  2688. hp2, hp_regalloc: tai;
  2689. p_SourceReg, p_TargetReg: TRegister;
  2690. begin
  2691. Result := False;
  2692. { Backward optimisation. If we have:
  2693. func. %reg1,%reg2
  2694. mov %reg2,%reg3
  2695. (dealloc %reg2)
  2696. Change to:
  2697. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2698. Perform similar optimisations with 1, 3 and 4-operand instructions
  2699. that only have one output.
  2700. }
  2701. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2702. begin
  2703. p_SourceReg := taicpu(p).oper[0]^.reg;
  2704. p_TargetReg := taicpu(p).oper[1]^.reg;
  2705. TransferUsedRegs(TmpUsedRegs);
  2706. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2707. GetLastInstruction(p, hp2) and
  2708. (hp2.typ = ait_instruction) and
  2709. { Have to make sure it's an instruction that only reads from
  2710. the first operands and only writes (not reads or modifies) to
  2711. the last one; in essence, a pure function such as BSR, POPCNT
  2712. or ANDN }
  2713. (
  2714. (
  2715. (taicpu(hp2).ops = 1) and
  2716. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2717. ) or
  2718. (
  2719. (taicpu(hp2).ops = 2) and
  2720. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2721. ) or
  2722. (
  2723. (taicpu(hp2).ops = 3) and
  2724. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2725. ) or
  2726. (
  2727. (taicpu(hp2).ops = 4) and
  2728. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2729. )
  2730. ) and
  2731. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2732. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2733. begin
  2734. case taicpu(hp2).opcode of
  2735. A_FSTSW, A_FNSTSW,
  2736. A_IN, A_INS, A_OUT, A_OUTS,
  2737. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2738. { These routines have explicit operands, but they are restricted in
  2739. what they can be (e.g. IN and OUT can only read from AL, AX or
  2740. EAX. }
  2741. ;
  2742. else
  2743. begin
  2744. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2745. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2746. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2747. if Assigned(hp_regalloc) then
  2748. begin
  2749. Asml.Remove(hp_regalloc);
  2750. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2751. begin
  2752. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2753. hp_regalloc.Free;
  2754. end
  2755. else
  2756. { If the register is not explicitly deallocated, it's
  2757. being reused, so move the allocation to after func. }
  2758. AsmL.InsertAfter(hp_regalloc, hp2);
  2759. end;
  2760. if not RegInInstruction(p_TargetReg, hp2) then
  2761. begin
  2762. TransferUsedRegs(TmpUsedRegs);
  2763. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2764. end;
  2765. { Actually make the changes }
  2766. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2767. RemoveCurrentp(p, hp1);
  2768. { If the Func was another MOV instruction, we might get
  2769. "mov %reg,%reg" that doesn't get removed in Pass 2
  2770. otherwise, so deal with it here (also do something
  2771. similar with lea (%reg),%reg}
  2772. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2773. begin
  2774. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2775. if p = hp2 then
  2776. RemoveCurrentp(p)
  2777. else
  2778. RemoveInstruction(hp2);
  2779. end;
  2780. Result := True;
  2781. Exit;
  2782. end;
  2783. end;
  2784. end;
  2785. end;
  2786. end;
  2787. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2788. begin
  2789. Result := False;
  2790. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2791. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2792. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2793. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2794. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2795. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2796. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2797. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2798. begin
  2799. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2800. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2801. Result := True;
  2802. Include(OptsToCheck, aoc_ForceNewIteration);
  2803. end;
  2804. end;
  2805. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2806. var
  2807. hp1, hp2, hp3, hp4: tai;
  2808. DoOptimisation, TempBool: Boolean;
  2809. {$ifdef x86_64}
  2810. NewConst: TCGInt;
  2811. {$endif x86_64}
  2812. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2813. begin
  2814. if taicpu(hp1).opcode = signed_movop then
  2815. begin
  2816. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2817. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2818. end
  2819. else
  2820. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2821. end;
  2822. function TryConstMerge(var p1, p2: tai): Boolean;
  2823. var
  2824. ThisRef: TReference;
  2825. begin
  2826. Result := False;
  2827. ThisRef := taicpu(p2).oper[1]^.ref^;
  2828. { Only permit writes to the stack, since we can guarantee alignment with that }
  2829. if (ThisRef.index = NR_NO) and
  2830. (
  2831. (ThisRef.base = NR_STACK_POINTER_REG) or
  2832. (ThisRef.base = current_procinfo.framepointer)
  2833. ) then
  2834. begin
  2835. case taicpu(p).opsize of
  2836. S_B:
  2837. begin
  2838. { Word writes must be on a 2-byte boundary }
  2839. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2840. begin
  2841. { Reduce offset of second reference to see if it is sequential with the first }
  2842. Dec(ThisRef.offset, 1);
  2843. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2844. begin
  2845. { Make sure the constants aren't represented as a
  2846. negative number, as these won't merge properly }
  2847. taicpu(p1).opsize := S_W;
  2848. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2849. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2850. RemoveInstruction(p2);
  2851. Result := True;
  2852. end;
  2853. end;
  2854. end;
  2855. S_W:
  2856. begin
  2857. { Longword writes must be on a 4-byte boundary }
  2858. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2859. begin
  2860. { Reduce offset of second reference to see if it is sequential with the first }
  2861. Dec(ThisRef.offset, 2);
  2862. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2863. begin
  2864. { Make sure the constants aren't represented as a
  2865. negative number, as these won't merge properly }
  2866. taicpu(p1).opsize := S_L;
  2867. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2868. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2869. RemoveInstruction(p2);
  2870. Result := True;
  2871. end;
  2872. end;
  2873. end;
  2874. {$ifdef x86_64}
  2875. S_L:
  2876. begin
  2877. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2878. see if the constants can be encoded this way. }
  2879. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2880. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2881. { Quadword writes must be on an 8-byte boundary }
  2882. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2883. begin
  2884. { Reduce offset of second reference to see if it is sequential with the first }
  2885. Dec(ThisRef.offset, 4);
  2886. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2887. begin
  2888. { Make sure the constants aren't represented as a
  2889. negative number, as these won't merge properly }
  2890. taicpu(p1).opsize := S_Q;
  2891. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2892. taicpu(p1).oper[0]^.val := NewConst;
  2893. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2894. RemoveInstruction(p2);
  2895. Result := True;
  2896. end;
  2897. end;
  2898. end;
  2899. {$endif x86_64}
  2900. else
  2901. ;
  2902. end;
  2903. end;
  2904. end;
  2905. var
  2906. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2907. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2908. NewSize: topsize; NewOffset: asizeint;
  2909. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2910. SourceRef, TargetRef: TReference;
  2911. MovAligned, MovUnaligned: TAsmOp;
  2912. ThisRef: TReference;
  2913. JumpTracking: TLinkedList;
  2914. begin
  2915. Result:=false;
  2916. { remove mov reg1,reg1? }
  2917. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2918. then
  2919. begin
  2920. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2921. { take care of the register (de)allocs following p }
  2922. RemoveCurrentP(p);
  2923. Result := True;
  2924. exit;
  2925. end;
  2926. { Prevent compiler warnings }
  2927. p_SourceReg := NR_NO;
  2928. p_TargetReg := NR_NO;
  2929. if taicpu(p).oper[1]^.typ = top_reg then
  2930. begin
  2931. { Saves on a large number of dereferences }
  2932. p_TargetReg := taicpu(p).oper[1]^.reg;
  2933. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  2934. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_TargetReg)
  2935. else
  2936. GetNextInstruction_p := GetNextInstruction(p, hp1);
  2937. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  2938. begin
  2939. if (taicpu(hp1).opcode = A_AND) and
  2940. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2941. begin
  2942. if MatchOperand(taicpu(hp1).oper[1]^, p_TargetReg) then
  2943. begin
  2944. case taicpu(p).opsize of
  2945. S_L:
  2946. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2947. begin
  2948. { Optimize out:
  2949. mov x, %reg
  2950. and ffffffffh, %reg
  2951. }
  2952. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2953. RemoveInstruction(hp1);
  2954. Result:=true;
  2955. exit;
  2956. end;
  2957. S_Q: { TODO: Confirm if this is even possible }
  2958. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2959. begin
  2960. { Optimize out:
  2961. mov x, %reg
  2962. and ffffffffffffffffh, %reg
  2963. }
  2964. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2965. RemoveInstruction(hp1);
  2966. Result:=true;
  2967. exit;
  2968. end;
  2969. else
  2970. ;
  2971. end;
  2972. if (
  2973. { Make sure that if a reference is used, its registers
  2974. are not modified in between }
  2975. (
  2976. (taicpu(p).oper[0]^.typ = top_reg) and
  2977. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2978. ) or
  2979. (
  2980. (taicpu(p).oper[0]^.typ = top_ref) and
  2981. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  2982. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1)
  2983. )
  2984. ) and
  2985. GetNextInstruction(hp1,hp2) and
  2986. MatchInstruction(hp2,A_TEST,[]) and
  2987. (
  2988. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2989. (
  2990. { If the register being tested is smaller than the one
  2991. that received a bitwise AND, permit it if the constant
  2992. fits into the smaller size }
  2993. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2994. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2995. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2996. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2997. (
  2998. (
  2999. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3000. (taicpu(hp1).oper[0]^.val <= $FF)
  3001. ) or
  3002. (
  3003. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3004. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3005. {$ifdef x86_64}
  3006. ) or
  3007. (
  3008. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3009. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3010. {$endif x86_64}
  3011. )
  3012. )
  3013. )
  3014. ) and
  3015. (
  3016. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3017. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3018. ) and
  3019. GetNextInstruction(hp2,hp3) and
  3020. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3021. (taicpu(hp3).condition in [C_E,C_NE]) then
  3022. begin
  3023. TransferUsedRegs(TmpUsedRegs);
  3024. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3025. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3026. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3027. begin
  3028. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3029. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3030. taicpu(hp1).opcode:=A_TEST;
  3031. { Shrink the TEST instruction down to the smallest possible size }
  3032. case taicpu(hp1).oper[0]^.val of
  3033. 0..255:
  3034. if (taicpu(hp1).opsize <> S_B)
  3035. {$ifndef x86_64}
  3036. and (
  3037. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3038. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3039. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3040. )
  3041. {$endif x86_64}
  3042. then
  3043. begin
  3044. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3045. { Only print debug message if the TEST instruction
  3046. is a different size before and after }
  3047. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3048. taicpu(hp1).opsize := S_B;
  3049. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3050. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3051. end;
  3052. 256..65535:
  3053. if (taicpu(hp1).opsize <> S_W) then
  3054. begin
  3055. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3056. { Only print debug message if the TEST instruction
  3057. is a different size before and after }
  3058. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3059. taicpu(hp1).opsize := S_W;
  3060. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3061. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3062. end;
  3063. {$ifdef x86_64}
  3064. 65536..$7FFFFFFF:
  3065. if (taicpu(hp1).opsize <> S_L) then
  3066. begin
  3067. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3068. { Only print debug message if the TEST instruction
  3069. is a different size before and after }
  3070. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3071. taicpu(hp1).opsize := S_L;
  3072. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3073. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3074. end;
  3075. {$endif x86_64}
  3076. else
  3077. ;
  3078. end;
  3079. RemoveInstruction(hp2);
  3080. RemoveCurrentP(p);
  3081. Result:=true;
  3082. exit;
  3083. end;
  3084. end;
  3085. end;
  3086. if IsMOVZXAcceptable and
  3087. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3088. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3089. (getsupreg(p_TargetReg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3090. then
  3091. begin
  3092. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3093. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3094. case taicpu(p).opsize of
  3095. S_B:
  3096. if (taicpu(hp1).oper[0]^.val = $ff) then
  3097. begin
  3098. { Convert:
  3099. movb x, %regl movb x, %regl
  3100. andw ffh, %regw andl ffh, %regd
  3101. To:
  3102. movzbw x, %regd movzbl x, %regd
  3103. (Identical registers, just different sizes)
  3104. }
  3105. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3106. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3107. case taicpu(hp1).opsize of
  3108. S_W: NewSize := S_BW;
  3109. S_L: NewSize := S_BL;
  3110. {$ifdef x86_64}
  3111. S_Q: NewSize := S_BQ;
  3112. {$endif x86_64}
  3113. else
  3114. InternalError(2018011510);
  3115. end;
  3116. end
  3117. else
  3118. NewSize := S_NO;
  3119. S_W:
  3120. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3121. begin
  3122. { Convert:
  3123. movw x, %regw
  3124. andl ffffh, %regd
  3125. To:
  3126. movzwl x, %regd
  3127. (Identical registers, just different sizes)
  3128. }
  3129. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3130. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3131. case taicpu(hp1).opsize of
  3132. S_L: NewSize := S_WL;
  3133. {$ifdef x86_64}
  3134. S_Q: NewSize := S_WQ;
  3135. {$endif x86_64}
  3136. else
  3137. InternalError(2018011511);
  3138. end;
  3139. end
  3140. else
  3141. NewSize := S_NO;
  3142. else
  3143. NewSize := S_NO;
  3144. end;
  3145. if NewSize <> S_NO then
  3146. begin
  3147. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3148. { The actual optimization }
  3149. taicpu(p).opcode := A_MOVZX;
  3150. taicpu(p).changeopsize(NewSize);
  3151. taicpu(p).loadoper(1, taicpu(hp1).oper[1]^);
  3152. { Make sure we deal with any reference counts that were increased }
  3153. if taicpu(hp1).oper[1]^.typ = top_ref then
  3154. begin
  3155. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  3156. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  3157. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  3158. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  3159. end;
  3160. { Safeguard if "and" is followed by a conditional command }
  3161. TransferUsedRegs(TmpUsedRegs);
  3162. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  3163. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3164. begin
  3165. { At this point, the "and" command is effectively equivalent to
  3166. "test %reg,%reg". This will be handled separately by the
  3167. Peephole Optimizer. [Kit] }
  3168. DebugMsg(SPeepholeOptimization + PreMessage +
  3169. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3170. end
  3171. else
  3172. begin
  3173. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3174. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3175. RemoveInstruction(hp1);
  3176. end;
  3177. Result := True;
  3178. Exit;
  3179. end;
  3180. end;
  3181. end;
  3182. if taicpu(p).oper[0]^.typ = top_reg then
  3183. begin
  3184. p_SourceReg := taicpu(p).oper[0]^.reg;
  3185. { Look for:
  3186. mov %reg1,%reg2
  3187. ??? %reg2,r/m
  3188. Change to:
  3189. mov %reg1,%reg2
  3190. ??? %reg1,r/m
  3191. }
  3192. if RegReadByInstruction(p_TargetReg, hp1) and
  3193. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3194. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  3195. begin
  3196. { A change has occurred, just not in p }
  3197. Include(OptsToCheck, aoc_ForceNewIteration);
  3198. TransferUsedRegs(TmpUsedRegs);
  3199. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3200. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3201. { Just in case something didn't get modified (e.g. an
  3202. implicit register) }
  3203. not RegReadByInstruction(p_TargetReg, hp1) then
  3204. begin
  3205. { We can remove the original MOV }
  3206. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  3207. RemoveCurrentP(p);
  3208. { UsedRegs got updated by RemoveCurrentp }
  3209. Result := True;
  3210. Exit;
  3211. end;
  3212. { If we know a MOV instruction has become a null operation, we might as well
  3213. get rid of it now to save time. }
  3214. if (taicpu(hp1).opcode = A_MOV) and
  3215. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3216. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  3217. { Just being a register is enough to confirm it's a null operation }
  3218. (taicpu(hp1).oper[0]^.typ = top_reg) then
  3219. begin
  3220. Result := True;
  3221. { Speed-up to reduce a pipeline stall... if we had something like...
  3222. movl %eax,%edx
  3223. movw %dx,%ax
  3224. ... the second instruction would change to movw %ax,%ax, but
  3225. given that it is now %ax that's active rather than %eax,
  3226. penalties might occur due to a partial register write, so instead,
  3227. change it to a MOVZX instruction when optimising for speed.
  3228. }
  3229. if not (cs_opt_size in current_settings.optimizerswitches) and
  3230. IsMOVZXAcceptable and
  3231. (taicpu(hp1).opsize < taicpu(p).opsize)
  3232. {$ifdef x86_64}
  3233. { operations already implicitly set the upper 64 bits to zero }
  3234. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  3235. {$endif x86_64}
  3236. then
  3237. begin
  3238. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  3239. case taicpu(p).opsize of
  3240. S_W:
  3241. if taicpu(hp1).opsize = S_B then
  3242. taicpu(hp1).opsize := S_BL
  3243. else
  3244. InternalError(2020012911);
  3245. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  3246. case taicpu(hp1).opsize of
  3247. S_B:
  3248. taicpu(hp1).opsize := S_BL;
  3249. S_W:
  3250. taicpu(hp1).opsize := S_WL;
  3251. else
  3252. InternalError(2020012912);
  3253. end;
  3254. else
  3255. InternalError(2020012910);
  3256. end;
  3257. taicpu(hp1).opcode := A_MOVZX;
  3258. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3259. end
  3260. else
  3261. begin
  3262. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  3263. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  3264. RemoveInstruction(hp1);
  3265. { The instruction after what was hp1 is now the immediate next instruction,
  3266. so we can continue to make optimisations if it's present }
  3267. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  3268. Exit;
  3269. hp1 := hp2;
  3270. end;
  3271. end;
  3272. end;
  3273. {$ifdef x86_64}
  3274. { Change:
  3275. movl %reg1l,%reg2l
  3276. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3277. To:
  3278. movl %reg1l,%reg2l
  3279. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3280. If %reg1 = %reg3, convert to:
  3281. movl %reg1l,%reg2l
  3282. andl %reg1l,%reg1l
  3283. }
  3284. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3285. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3286. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3287. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg) then
  3288. begin
  3289. TransferUsedRegs(TmpUsedRegs);
  3290. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3291. taicpu(hp1).opsize := S_L;
  3292. taicpu(hp1).loadreg(0, p_SourceReg);
  3293. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3294. AllocRegBetween(p_SourceReg, p, hp1, UsedRegs);
  3295. if (p_SourceReg = taicpu(hp1).oper[1]^.reg) then
  3296. begin
  3297. { %reg1 = %reg3 }
  3298. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3299. taicpu(hp1).opcode := A_AND;
  3300. end
  3301. else
  3302. begin
  3303. { %reg1 <> %reg3 }
  3304. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3305. end;
  3306. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3307. begin
  3308. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3309. RemoveCurrentP(p);
  3310. Result := True;
  3311. Exit;
  3312. end
  3313. else
  3314. begin
  3315. { Initial instruction wasn't actually changed }
  3316. Include(OptsToCheck, aoc_ForceNewIteration);
  3317. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3318. appears below since %reg1 has technically changed }
  3319. if taicpu(hp1).opcode = A_AND then
  3320. Exit;
  3321. end;
  3322. end;
  3323. {$endif x86_64}
  3324. end
  3325. else if taicpu(p).oper[0]^.typ = top_const then
  3326. begin
  3327. if (taicpu(hp1).opcode = A_OR) and
  3328. (taicpu(p).oper[1]^.typ = top_reg) and
  3329. MatchOperand(taicpu(p).oper[0]^, 0) and
  3330. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3331. begin
  3332. { mov 0, %reg
  3333. or ###,%reg
  3334. Change to (only if the flags are not used):
  3335. mov ###,%reg
  3336. }
  3337. TransferUsedRegs(TmpUsedRegs);
  3338. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3339. DoOptimisation := True;
  3340. { Even if the flags are used, we might be able to do the optimisation
  3341. if the conditions are predictable }
  3342. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3343. begin
  3344. { Only perform if ### = %reg (the same register) or equal to 0,
  3345. so %reg is guaranteed to still have a value of zero }
  3346. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3347. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3348. begin
  3349. hp2 := hp1;
  3350. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3351. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3352. GetNextInstruction(hp2, hp3) do
  3353. begin
  3354. { Don't continue modifying if the flags state is getting changed }
  3355. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3356. Break;
  3357. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3358. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3359. begin
  3360. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3361. begin
  3362. { Condition is always true }
  3363. case taicpu(hp3).opcode of
  3364. A_Jcc:
  3365. begin
  3366. { Check for jump shortcuts before we destroy the condition }
  3367. hp4 := hp3;
  3368. DoJumpOptimizations(hp3, TempBool);
  3369. { Make sure hp3 hasn't changed }
  3370. if (hp4 = hp3) then
  3371. begin
  3372. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3373. MakeUnconditional(taicpu(hp3));
  3374. end;
  3375. Result := True;
  3376. end;
  3377. A_CMOVcc:
  3378. begin
  3379. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3380. taicpu(hp3).opcode := A_MOV;
  3381. taicpu(hp3).condition := C_None;
  3382. Result := True;
  3383. end;
  3384. A_SETcc:
  3385. begin
  3386. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3387. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3388. taicpu(hp3).opcode := A_MOV;
  3389. taicpu(hp3).ops := 2;
  3390. taicpu(hp3).condition := C_None;
  3391. taicpu(hp3).opsize := S_B;
  3392. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3393. taicpu(hp3).loadconst(0, 1);
  3394. Result := True;
  3395. end;
  3396. else
  3397. InternalError(2021090701);
  3398. end;
  3399. end
  3400. 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
  3401. begin
  3402. { Condition is always false }
  3403. case taicpu(hp3).opcode of
  3404. A_Jcc:
  3405. begin
  3406. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3407. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3408. RemoveInstruction(hp3);
  3409. Result := True;
  3410. { Since hp3 was deleted, hp2 must not be updated }
  3411. Continue;
  3412. end;
  3413. A_CMOVcc:
  3414. begin
  3415. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3416. RemoveInstruction(hp3);
  3417. Result := True;
  3418. { Since hp3 was deleted, hp2 must not be updated }
  3419. Continue;
  3420. end;
  3421. A_SETcc:
  3422. begin
  3423. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3424. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3425. taicpu(hp3).opcode := A_MOV;
  3426. taicpu(hp3).ops := 2;
  3427. taicpu(hp3).condition := C_None;
  3428. taicpu(hp3).opsize := S_B;
  3429. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3430. taicpu(hp3).loadconst(0, 0);
  3431. Result := True;
  3432. end;
  3433. else
  3434. InternalError(2021090702);
  3435. end;
  3436. end
  3437. else
  3438. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3439. DoOptimisation := False;
  3440. end;
  3441. hp2 := hp3;
  3442. end;
  3443. if DoOptimisation then
  3444. begin
  3445. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3446. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3447. { Flags are still in use - don't optimise }
  3448. DoOptimisation := False;
  3449. end;
  3450. end
  3451. else
  3452. DoOptimisation := False;
  3453. end;
  3454. if DoOptimisation then
  3455. begin
  3456. {$ifdef x86_64}
  3457. { OR only supports 32-bit sign-extended constants for 64-bit
  3458. instructions, so compensate for this if the constant is
  3459. encoded as a value greater than or equal to 2^31 }
  3460. if (taicpu(hp1).opsize = S_Q) and
  3461. (taicpu(hp1).oper[0]^.typ = top_const) and
  3462. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3463. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3464. {$endif x86_64}
  3465. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3466. taicpu(hp1).opcode := A_MOV;
  3467. RemoveCurrentP(p);
  3468. Result := True;
  3469. Exit;
  3470. end;
  3471. end;
  3472. end
  3473. else if
  3474. { oper[0] is a reference }
  3475. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) then
  3476. begin
  3477. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  3478. begin
  3479. if ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3480. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3481. ) or
  3482. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3483. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3484. )
  3485. ) and
  3486. not RegModifiedBetween(Taicpu(hp1).oper[1]^.reg, p, hp1) then
  3487. { mov ref,reg1
  3488. lea (reg1,reg2),reg2
  3489. to
  3490. add ref,reg2 }
  3491. begin
  3492. TransferUsedRegs(TmpUsedRegs);
  3493. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3494. { If the flags register is in use, don't change the instruction to an
  3495. ADD otherwise this will scramble the flags. [Kit] }
  3496. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3497. { reg1 may not be used afterwards }
  3498. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3499. begin
  3500. Taicpu(hp1).opcode:=A_ADD;
  3501. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3502. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3503. RemoveCurrentp(p);
  3504. result:=true;
  3505. exit;
  3506. end;
  3507. end;
  3508. { If the LEA instruction can be converted into an arithmetic instruction,
  3509. it may be possible to then fold it in the next optimisation. }
  3510. if ConvertLEA(taicpu(hp1)) then
  3511. Include(OptsToCheck, aoc_ForceNewIteration);
  3512. end;
  3513. {
  3514. mov ref,reg0
  3515. <op> reg0,reg1
  3516. dealloc reg0
  3517. to
  3518. <op> ref,reg1
  3519. }
  3520. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3521. (taicpu(hp1).oper[0]^.reg = p_TargetReg) and
  3522. MatchInstruction(hp1, [A_AND, A_OR, A_XOR, A_ADD, A_SUB, A_CMP, A_TEST, A_CMOVcc, A_BSR, A_BSF, A_POPCNT, A_LZCNT], [taicpu(p).opsize]) and
  3523. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, p_TargetReg) and
  3524. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3525. begin
  3526. TransferUsedRegs(TmpUsedRegs);
  3527. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3528. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3529. begin
  3530. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  3531. { loadref increases the reference count, so decrement it again }
  3532. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3533. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3534. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3535. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3536. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3537. { See if we can remove the allocation of reg0 }
  3538. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3539. TryRemoveRegAlloc(p_TargetReg, p, hp1);
  3540. RemoveCurrentp(p);
  3541. Result:=true;
  3542. exit;
  3543. end;
  3544. end;
  3545. end;
  3546. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  3547. overwrites the original destination register. e.g.
  3548. movl ###,%reg2d
  3549. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  3550. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  3551. }
  3552. if MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  3553. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3554. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  3555. begin
  3556. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  3557. begin
  3558. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  3559. case taicpu(p).oper[0]^.typ of
  3560. top_const:
  3561. { We have something like:
  3562. movb $x, %regb
  3563. movzbl %regb,%regd
  3564. Change to:
  3565. movl $x, %regd
  3566. }
  3567. begin
  3568. case taicpu(hp1).opsize of
  3569. S_BW:
  3570. begin
  3571. convert_mov_value(A_MOVSX, $FF);
  3572. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  3573. taicpu(p).opsize := S_W;
  3574. end;
  3575. S_BL:
  3576. begin
  3577. convert_mov_value(A_MOVSX, $FF);
  3578. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3579. taicpu(p).opsize := S_L;
  3580. end;
  3581. S_WL:
  3582. begin
  3583. convert_mov_value(A_MOVSX, $FFFF);
  3584. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3585. taicpu(p).opsize := S_L;
  3586. end;
  3587. {$ifdef x86_64}
  3588. S_BQ:
  3589. begin
  3590. convert_mov_value(A_MOVSX, $FF);
  3591. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3592. taicpu(p).opsize := S_Q;
  3593. end;
  3594. S_WQ:
  3595. begin
  3596. convert_mov_value(A_MOVSX, $FFFF);
  3597. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3598. taicpu(p).opsize := S_Q;
  3599. end;
  3600. S_LQ:
  3601. begin
  3602. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3603. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3604. taicpu(p).opsize := S_Q;
  3605. end;
  3606. {$endif x86_64}
  3607. else
  3608. { If hp1 was a MOV instruction, it should have been
  3609. optimised already }
  3610. InternalError(2020021001);
  3611. end;
  3612. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3613. RemoveInstruction(hp1);
  3614. Result := True;
  3615. Exit;
  3616. end;
  3617. top_ref:
  3618. begin
  3619. { We have something like:
  3620. movb mem, %regb
  3621. movzbl %regb,%regd
  3622. Change to:
  3623. movzbl mem, %regd
  3624. }
  3625. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3626. begin
  3627. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3628. taicpu(p).opcode := taicpu(hp1).opcode;
  3629. taicpu(p).opsize := taicpu(hp1).opsize;
  3630. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  3631. RemoveInstruction(hp1);
  3632. Result := True;
  3633. Exit;
  3634. end;
  3635. end;
  3636. else
  3637. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3638. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3639. Exit;
  3640. end;
  3641. end
  3642. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3643. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3644. optimised }
  3645. else
  3646. begin
  3647. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3648. RemoveCurrentP(p);
  3649. Result := True;
  3650. Exit;
  3651. end;
  3652. end;
  3653. if (taicpu(hp1).opcode = A_MOV) and
  3654. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3655. begin
  3656. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3657. TransferUsedRegs(TmpUsedRegs);
  3658. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3659. { we have
  3660. mov x, %treg
  3661. mov %treg, y
  3662. }
  3663. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3664. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3665. begin
  3666. { we've got
  3667. mov x, %treg
  3668. mov %treg, y
  3669. with %treg is not used after }
  3670. case taicpu(p).oper[0]^.typ Of
  3671. { top_reg is covered by DeepMOVOpt }
  3672. top_const:
  3673. begin
  3674. { change
  3675. mov const, %treg
  3676. mov %treg, y
  3677. to
  3678. mov const, y
  3679. }
  3680. {$ifdef x86_64}
  3681. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3682. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3683. {$endif x86_64}
  3684. begin
  3685. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3686. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done', hp1);
  3687. RemoveCurrentP(p);
  3688. Result := True;
  3689. Exit;
  3690. end;
  3691. end;
  3692. top_ref:
  3693. case taicpu(hp1).oper[1]^.typ of
  3694. top_reg:
  3695. { change
  3696. mov mem, %treg
  3697. mov %treg, %reg
  3698. to
  3699. mov mem, %reg"
  3700. }
  3701. if not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) then
  3702. begin
  3703. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3704. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3a done', p);
  3705. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  3706. RemoveInstruction(hp1);
  3707. Result := True;
  3708. Exit;
  3709. end
  3710. else if
  3711. { Make sure that if a reference is used, its
  3712. registers are not modified in between }
  3713. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3714. begin
  3715. if (taicpu(p).oper[0]^.ref^.base <> NR_NO){$ifdef x86_64} and (taicpu(p).oper[0]^.ref^.base <> NR_RIP){$endif x86_64} then
  3716. AllocRegBetween(taicpu(p).oper[0]^.ref^.base, p, hp1, UsedRegs);
  3717. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and (taicpu(p).oper[0]^.ref^.index <> taicpu(p).oper[0]^.ref^.base) then
  3718. AllocRegBetween(taicpu(p).oper[0]^.ref^.index, p, hp1, UsedRegs);
  3719. taicpu(hp1).loadref(0, taicpu(p).oper[0]^.ref^);
  3720. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3721. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3722. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3723. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3724. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done', hp1);
  3725. RemoveCurrentP(p);
  3726. Result := True;
  3727. Exit;
  3728. end;
  3729. top_ref:
  3730. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3731. begin
  3732. {$ifdef x86_64}
  3733. { Look for the following to simplify:
  3734. mov x(mem1), %reg
  3735. mov %reg, y(mem2)
  3736. mov x+8(mem1), %reg
  3737. mov %reg, y+8(mem2)
  3738. Change to:
  3739. movdqu x(mem1), %xmmreg
  3740. movdqu %xmmreg, y(mem2)
  3741. ...but only as long as the memory blocks don't overlap
  3742. }
  3743. SourceRef := taicpu(p).oper[0]^.ref^;
  3744. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3745. if (taicpu(p).opsize = S_Q) and
  3746. not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3747. GetNextInstruction(hp1, hp2) and
  3748. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3749. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3750. begin
  3751. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3752. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3753. Inc(SourceRef.offset, 8);
  3754. if UseAVX then
  3755. begin
  3756. MovAligned := A_VMOVDQA;
  3757. MovUnaligned := A_VMOVDQU;
  3758. end
  3759. else
  3760. begin
  3761. MovAligned := A_MOVDQA;
  3762. MovUnaligned := A_MOVDQU;
  3763. end;
  3764. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3765. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3766. begin
  3767. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3768. Inc(TargetRef.offset, 8);
  3769. if GetNextInstruction(hp2, hp3) and
  3770. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3771. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3772. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3773. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3774. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3775. begin
  3776. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3777. if NewMMReg <> NR_NO then
  3778. begin
  3779. { Remember that the offsets are 8 ahead }
  3780. if ((SourceRef.offset mod 16) = 8) and
  3781. (
  3782. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3783. (SourceRef.base = current_procinfo.framepointer) or
  3784. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3785. ) then
  3786. taicpu(p).opcode := MovAligned
  3787. else
  3788. taicpu(p).opcode := MovUnaligned;
  3789. taicpu(p).opsize := S_XMM;
  3790. taicpu(p).oper[1]^.reg := NewMMReg;
  3791. if ((TargetRef.offset mod 16) = 8) and
  3792. (
  3793. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3794. (TargetRef.base = current_procinfo.framepointer) or
  3795. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3796. ) then
  3797. taicpu(hp1).opcode := MovAligned
  3798. else
  3799. taicpu(hp1).opcode := MovUnaligned;
  3800. taicpu(hp1).opsize := S_XMM;
  3801. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3802. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3803. RemoveInstruction(hp2);
  3804. RemoveInstruction(hp3);
  3805. Result := True;
  3806. Exit;
  3807. end;
  3808. end;
  3809. end
  3810. else
  3811. begin
  3812. { See if the next references are 8 less rather than 8 greater }
  3813. Dec(SourceRef.offset, 16); { -8 the other way }
  3814. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3815. begin
  3816. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3817. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3818. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3819. GetNextInstruction(hp2, hp3) and
  3820. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3821. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3822. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3823. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3824. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3825. begin
  3826. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3827. if NewMMReg <> NR_NO then
  3828. begin
  3829. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3830. if ((SourceRef.offset mod 16) = 0) and
  3831. (
  3832. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3833. (SourceRef.base = current_procinfo.framepointer) or
  3834. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3835. ) then
  3836. taicpu(hp2).opcode := MovAligned
  3837. else
  3838. taicpu(hp2).opcode := MovUnaligned;
  3839. taicpu(hp2).opsize := S_XMM;
  3840. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3841. if ((TargetRef.offset mod 16) = 0) and
  3842. (
  3843. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3844. (TargetRef.base = current_procinfo.framepointer) or
  3845. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3846. ) then
  3847. taicpu(hp3).opcode := MovAligned
  3848. else
  3849. taicpu(hp3).opcode := MovUnaligned;
  3850. taicpu(hp3).opsize := S_XMM;
  3851. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3852. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3853. RemoveInstruction(hp1);
  3854. RemoveCurrentP(p);
  3855. Result := True;
  3856. Exit;
  3857. end;
  3858. end;
  3859. end;
  3860. end;
  3861. end;
  3862. {$endif x86_64}
  3863. end;
  3864. else
  3865. { The write target should be a reg or a ref }
  3866. InternalError(2021091601);
  3867. end;
  3868. else
  3869. ;
  3870. end;
  3871. end
  3872. else if (taicpu(p).oper[0]^.typ = top_const) and
  3873. { %treg is used afterwards, but all eventualities other
  3874. than the first MOV instruction being a constant are
  3875. covered by DeepMOVOpt, so only check for that }
  3876. (
  3877. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3878. not (cs_opt_size in current_settings.optimizerswitches) or
  3879. (taicpu(hp1).opsize = S_B)
  3880. ) and
  3881. (
  3882. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3883. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3884. ) then
  3885. begin
  3886. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3887. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3888. Include(OptsToCheck, aoc_ForceNewIteration);
  3889. end;
  3890. end;
  3891. end;
  3892. end;
  3893. if taicpu(p).oper[0]^.typ = top_reg then
  3894. begin
  3895. { oper[1] is a reference }
  3896. { Saves on a large number of dereferences }
  3897. p_SourceReg := taicpu(p).oper[0]^.reg;
  3898. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  3899. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_SourceReg)
  3900. else
  3901. GetNextInstruction_p := GetNextInstruction(p, hp1);
  3902. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  3903. begin
  3904. if taicpu(p).oper[1]^.typ = top_reg then
  3905. begin
  3906. p_TargetReg := taicpu(p).oper[1]^.reg;
  3907. { Change:
  3908. movl %reg1,%reg2
  3909. ...
  3910. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3911. ...
  3912. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3913. To:
  3914. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3915. ...
  3916. movl x(%reg1),%reg1
  3917. ...
  3918. movl %reg1,%regX
  3919. }
  3920. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  3921. (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3922. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3923. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3924. not RegModifiedBetween(p_TargetReg, p, hp1) and
  3925. GetNextInstructionUsingReg(hp1, hp2, p_TargetReg) and
  3926. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3927. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3928. not RegModifiedBetween(p_SourceReg, hp1, hp2) then
  3929. begin
  3930. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3931. if RegInRef(p_TargetReg, SourceRef) and
  3932. { If %reg1 also appears in the second reference, then it will
  3933. not refer to the same memory block as the first reference }
  3934. not RegInRef(p_SourceReg, SourceRef) then
  3935. begin
  3936. { Check to see if the references match if %reg2 is changed to %reg1 }
  3937. if SourceRef.base = p_TargetReg then
  3938. SourceRef.base := p_SourceReg;
  3939. if SourceRef.index = p_TargetReg then
  3940. SourceRef.index := p_SourceReg;
  3941. { RefsEqual also checks to ensure both references are non-volatile }
  3942. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3943. begin
  3944. taicpu(hp2).loadreg(0, p_SourceReg);
  3945. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3946. Result := True;
  3947. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3948. begin
  3949. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3950. RemoveCurrentP(p);
  3951. Exit;
  3952. end
  3953. else
  3954. begin
  3955. { Check to see if %reg2 is no longer in use }
  3956. TransferUsedRegs(TmpUsedRegs);
  3957. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3958. UpdateUsedRegsBetween(TmpUsedRegs, tai(hp1.Next), hp2);
  3959. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3960. begin
  3961. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3962. RemoveCurrentP(p);
  3963. Exit;
  3964. end;
  3965. end;
  3966. { If we reach this point, p and hp1 weren't actually modified,
  3967. so we can do a bit more work on this pass }
  3968. end;
  3969. end;
  3970. end;
  3971. end;
  3972. end;
  3973. end;
  3974. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  3975. { All the next optimisations require a next instruction }
  3976. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  3977. Exit;
  3978. { Next instruction is also a MOV ? }
  3979. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3980. begin
  3981. if MatchOpType(taicpu(p), top_const, top_ref) and
  3982. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3983. TryConstMerge(p, hp1) then
  3984. begin
  3985. Result := True;
  3986. { In case we have four byte writes in a row, check for 2 more
  3987. right now so we don't have to wait for another iteration of
  3988. pass 1
  3989. }
  3990. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3991. case taicpu(p).opsize of
  3992. S_W:
  3993. begin
  3994. if GetNextInstruction(p, hp1) and
  3995. MatchInstruction(hp1, A_MOV, [S_B]) and
  3996. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3997. GetNextInstruction(hp1, hp2) and
  3998. MatchInstruction(hp2, A_MOV, [S_B]) and
  3999. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4000. { Try to merge the two bytes }
  4001. TryConstMerge(hp1, hp2) then
  4002. { Now try to merge the two words (hp2 will get deleted) }
  4003. TryConstMerge(p, hp1);
  4004. end;
  4005. S_L:
  4006. begin
  4007. { Though this only really benefits x86_64 and not i386, it
  4008. gets a potential optimisation done faster and hence
  4009. reduces the number of times OptPass1MOV is entered }
  4010. if GetNextInstruction(p, hp1) and
  4011. MatchInstruction(hp1, A_MOV, [S_W]) and
  4012. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4013. GetNextInstruction(hp1, hp2) and
  4014. MatchInstruction(hp2, A_MOV, [S_W]) and
  4015. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4016. { Try to merge the two words }
  4017. TryConstMerge(hp1, hp2) then
  4018. { This will always fail on i386, so don't bother
  4019. calling it unless we're doing x86_64 }
  4020. {$ifdef x86_64}
  4021. { Now try to merge the two longwords (hp2 will get deleted) }
  4022. TryConstMerge(p, hp1)
  4023. {$endif x86_64}
  4024. ;
  4025. end;
  4026. else
  4027. ;
  4028. end;
  4029. Exit;
  4030. end;
  4031. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4032. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4033. { mov reg1, mem1 or mov mem1, reg1
  4034. mov mem2, reg2 mov reg2, mem2}
  4035. begin
  4036. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4037. { mov reg1, mem1 or mov mem1, reg1
  4038. mov mem2, reg1 mov reg2, mem1}
  4039. begin
  4040. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4041. { Removes the second statement from
  4042. mov reg1, mem1/reg2
  4043. mov mem1/reg2, reg1 }
  4044. begin
  4045. if taicpu(p).oper[0]^.typ=top_reg then
  4046. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4047. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  4048. RemoveInstruction(hp1);
  4049. Result:=true;
  4050. exit;
  4051. end
  4052. else
  4053. begin
  4054. TransferUsedRegs(TmpUsedRegs);
  4055. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4056. if (taicpu(p).oper[1]^.typ = top_ref) and
  4057. { mov reg1, mem1
  4058. mov mem2, reg1 }
  4059. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  4060. GetNextInstruction(hp1, hp2) and
  4061. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  4062. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  4063. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  4064. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  4065. { change to
  4066. mov reg1, mem1 mov reg1, mem1
  4067. mov mem2, reg1 cmp reg1, mem2
  4068. cmp mem1, reg1
  4069. }
  4070. begin
  4071. RemoveInstruction(hp2);
  4072. taicpu(hp1).opcode := A_CMP;
  4073. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  4074. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4075. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4076. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  4077. end;
  4078. end;
  4079. end
  4080. else if (taicpu(p).oper[1]^.typ=top_ref) and
  4081. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4082. begin
  4083. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4084. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4085. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  4086. end
  4087. else
  4088. begin
  4089. TransferUsedRegs(TmpUsedRegs);
  4090. if GetNextInstruction(hp1, hp2) and
  4091. MatchOpType(taicpu(p),top_ref,top_reg) and
  4092. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4093. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4094. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  4095. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  4096. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4097. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  4098. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  4099. { mov mem1, %reg1
  4100. mov %reg1, mem2
  4101. mov mem2, reg2
  4102. to:
  4103. mov mem1, reg2
  4104. mov reg2, mem2}
  4105. begin
  4106. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  4107. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  4108. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  4109. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  4110. RemoveInstruction(hp2);
  4111. Result := True;
  4112. end
  4113. {$ifdef i386}
  4114. { this is enabled for i386 only, as the rules to create the reg sets below
  4115. are too complicated for x86-64, so this makes this code too error prone
  4116. on x86-64
  4117. }
  4118. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  4119. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  4120. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  4121. { mov mem1, reg1 mov mem1, reg1
  4122. mov reg1, mem2 mov reg1, mem2
  4123. mov mem2, reg2 mov mem2, reg1
  4124. to: to:
  4125. mov mem1, reg1 mov mem1, reg1
  4126. mov mem1, reg2 mov reg1, mem2
  4127. mov reg1, mem2
  4128. or (if mem1 depends on reg1
  4129. and/or if mem2 depends on reg2)
  4130. to:
  4131. mov mem1, reg1
  4132. mov reg1, mem2
  4133. mov reg1, reg2
  4134. }
  4135. begin
  4136. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  4137. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  4138. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  4139. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  4140. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4141. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4142. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4143. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  4144. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  4145. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4146. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  4147. end
  4148. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  4149. begin
  4150. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  4151. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4152. end
  4153. else
  4154. begin
  4155. RemoveInstruction(hp2);
  4156. end
  4157. {$endif i386}
  4158. ;
  4159. end;
  4160. end
  4161. { movl [mem1],reg1
  4162. movl [mem1],reg2
  4163. to
  4164. movl [mem1],reg1
  4165. movl reg1,reg2
  4166. }
  4167. else if not CheckMovMov2MovMov2(p, hp1) and
  4168. { movl const1,[mem1]
  4169. movl [mem1],reg1
  4170. to
  4171. movl const1,reg1
  4172. movl reg1,[mem1]
  4173. }
  4174. MatchOpType(Taicpu(p),top_const,top_ref) and
  4175. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  4176. (taicpu(p).opsize = taicpu(hp1).opsize) and
  4177. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  4178. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  4179. begin
  4180. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  4181. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  4182. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  4183. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  4184. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  4185. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  4186. Result:=true;
  4187. exit;
  4188. end;
  4189. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  4190. end;
  4191. { search further than the next instruction for a mov (as long as it's not a jump) }
  4192. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4193. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4194. (taicpu(p).oper[1]^.typ = top_reg) and
  4195. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4196. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4197. begin
  4198. { we work with hp2 here, so hp1 can be still used later on when
  4199. checking for GetNextInstruction_p }
  4200. hp3 := hp1;
  4201. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4202. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4203. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4204. TransferUsedRegs(TmpUsedRegs);
  4205. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4206. if NotFirstIteration then
  4207. JumpTracking := TLinkedList.Create
  4208. else
  4209. JumpTracking := nil;
  4210. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4211. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4212. (hp2.typ=ait_instruction) do
  4213. begin
  4214. case taicpu(hp2).opcode of
  4215. A_POP:
  4216. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4217. begin
  4218. if not CrossJump and
  4219. not RegUsedBetween(p_TargetReg, p, hp2) then
  4220. begin
  4221. { We can remove the original MOV since the register
  4222. wasn't used between it and its popping from the stack }
  4223. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4224. RemoveCurrentp(p, hp1);
  4225. Result := True;
  4226. JumpTracking.Free;
  4227. Exit;
  4228. end;
  4229. { Can't go any further }
  4230. Break;
  4231. end;
  4232. A_MOV:
  4233. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4234. ((taicpu(p).oper[0]^.typ=top_const) or
  4235. ((taicpu(p).oper[0]^.typ=top_reg) and
  4236. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4237. )
  4238. ) then
  4239. begin
  4240. { we have
  4241. mov x, %treg
  4242. mov %treg, y
  4243. }
  4244. { We don't need to call UpdateUsedRegs for every instruction between
  4245. p and hp2 because the register we're concerned about will not
  4246. become deallocated (otherwise GetNextInstructionUsingReg would
  4247. have stopped at an earlier instruction). [Kit] }
  4248. TempRegUsed :=
  4249. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4250. RegReadByInstruction(p_TargetReg, hp3) or
  4251. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4252. case taicpu(p).oper[0]^.typ Of
  4253. top_reg:
  4254. begin
  4255. { change
  4256. mov %reg, %treg
  4257. mov %treg, y
  4258. to
  4259. mov %reg, y
  4260. }
  4261. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4262. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4263. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4264. begin
  4265. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4266. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4267. if TempRegUsed then
  4268. begin
  4269. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4270. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4271. { Set the start of the next GetNextInstructionUsingRegCond search
  4272. to start at the entry right before hp2 (which is about to be removed) }
  4273. hp3 := tai(hp2.Previous);
  4274. RemoveInstruction(hp2);
  4275. Include(OptsToCheck, aoc_ForceNewIteration);
  4276. { See if there's more we can optimise }
  4277. Continue;
  4278. end
  4279. else
  4280. begin
  4281. RemoveInstruction(hp2);
  4282. { We can remove the original MOV too }
  4283. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4284. RemoveCurrentP(p, hp1);
  4285. Result:=true;
  4286. JumpTracking.Free;
  4287. Exit;
  4288. end;
  4289. end
  4290. else
  4291. begin
  4292. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4293. taicpu(hp2).loadReg(0, p_SourceReg);
  4294. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4295. { Check to see if the register also appears in the reference }
  4296. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4297. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4298. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4299. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4300. begin
  4301. { Don't remove the first instruction if the temporary register is in use }
  4302. if not TempRegUsed then
  4303. begin
  4304. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4305. RemoveCurrentP(p, hp1);
  4306. Result:=true;
  4307. JumpTracking.Free;
  4308. Exit;
  4309. end;
  4310. { No need to set Result to True here. If there's another instruction later
  4311. on that can be optimised, it will be detected when the main Pass 1 loop
  4312. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4313. hp3 := hp2;
  4314. Continue;
  4315. end;
  4316. end;
  4317. end;
  4318. top_const:
  4319. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4320. begin
  4321. { change
  4322. mov const, %treg
  4323. mov %treg, y
  4324. to
  4325. mov const, y
  4326. }
  4327. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4328. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4329. begin
  4330. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4331. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4332. if TempRegUsed then
  4333. begin
  4334. { Don't remove the first instruction if the temporary register is in use }
  4335. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4336. { No need to set Result to True. If there's another instruction later on
  4337. that can be optimised, it will be detected when the main Pass 1 loop
  4338. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4339. end
  4340. else
  4341. begin
  4342. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4343. RemoveCurrentP(p, hp1);
  4344. Result:=true;
  4345. Exit;
  4346. end;
  4347. end;
  4348. end;
  4349. else
  4350. Internalerror(2019103001);
  4351. end;
  4352. end
  4353. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4354. begin
  4355. if not CrossJump and
  4356. not RegUsedBetween(p_TargetReg, p, hp2) and
  4357. not RegReadByInstruction(p_TargetReg, hp2) then
  4358. begin
  4359. { Register is not used before it is overwritten }
  4360. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4361. RemoveCurrentp(p, hp1);
  4362. Result := True;
  4363. Exit;
  4364. end;
  4365. if (taicpu(p).oper[0]^.typ = top_const) and
  4366. (taicpu(hp2).oper[0]^.typ = top_const) then
  4367. begin
  4368. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4369. begin
  4370. { Same value - register hasn't changed }
  4371. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4372. RemoveInstruction(hp2);
  4373. Include(OptsToCheck, aoc_ForceNewIteration);
  4374. { See if there's more we can optimise }
  4375. Continue;
  4376. end;
  4377. end;
  4378. {$ifdef x86_64}
  4379. end
  4380. { Change:
  4381. movl %reg1l,%reg2l
  4382. ...
  4383. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4384. To:
  4385. movl %reg1l,%reg2l
  4386. ...
  4387. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4388. If %reg1 = %reg3, convert to:
  4389. movl %reg1l,%reg2l
  4390. ...
  4391. andl %reg1l,%reg1l
  4392. }
  4393. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4394. (taicpu(p).oper[0]^.typ = top_reg) and
  4395. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4396. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4397. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4398. begin
  4399. TempRegUsed :=
  4400. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4401. RegReadByInstruction(p_TargetReg, hp3) or
  4402. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4403. taicpu(hp2).opsize := S_L;
  4404. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4405. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4406. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4407. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4408. begin
  4409. { %reg1 = %reg3 }
  4410. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4411. taicpu(hp2).opcode := A_AND;
  4412. end
  4413. else
  4414. begin
  4415. { %reg1 <> %reg3 }
  4416. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4417. end;
  4418. if not TempRegUsed then
  4419. begin
  4420. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4421. RemoveCurrentP(p, hp1);
  4422. Result := True;
  4423. Exit;
  4424. end
  4425. else
  4426. begin
  4427. { Initial instruction wasn't actually changed }
  4428. Include(OptsToCheck, aoc_ForceNewIteration);
  4429. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4430. appears below since %reg1 has technically changed }
  4431. if taicpu(hp2).opcode = A_AND then
  4432. Break;
  4433. end;
  4434. {$endif x86_64}
  4435. end
  4436. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4437. GetNextInstruction(hp2, hp4) and
  4438. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4439. { Optimise the following first:
  4440. movl [mem1],reg1
  4441. movl [mem1],reg2
  4442. to
  4443. movl [mem1],reg1
  4444. movl reg1,reg2
  4445. If [mem1] contains the target register and reg1 is the
  4446. the source register, this optimisation will get missed
  4447. and produce less efficient code later on.
  4448. }
  4449. if CheckMovMov2MovMov2(hp2, hp4) then
  4450. { Initial instruction wasn't actually changed }
  4451. Include(OptsToCheck, aoc_ForceNewIteration);
  4452. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4453. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4454. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4455. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4456. begin
  4457. {
  4458. Change from:
  4459. mov ###, %reg
  4460. ...
  4461. movs/z %reg,%reg (Same register, just different sizes)
  4462. To:
  4463. movs/z ###, %reg (Longer version)
  4464. ...
  4465. (remove)
  4466. }
  4467. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4468. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4469. { Keep the first instruction as mov if ### is a constant }
  4470. if taicpu(p).oper[0]^.typ = top_const then
  4471. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4472. else
  4473. begin
  4474. taicpu(p).opcode := taicpu(hp2).opcode;
  4475. taicpu(p).opsize := taicpu(hp2).opsize;
  4476. end;
  4477. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4478. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4479. RemoveInstruction(hp2);
  4480. Result := True;
  4481. JumpTracking.Free;
  4482. Exit;
  4483. end;
  4484. else
  4485. { Move down to the if-block below };
  4486. end;
  4487. { Also catches MOV/S/Z instructions that aren't modified }
  4488. if taicpu(p).oper[0]^.typ = top_reg then
  4489. begin
  4490. p_SourceReg := taicpu(p).oper[0]^.reg;
  4491. if
  4492. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4493. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4494. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4495. begin
  4496. Result := True;
  4497. { Just in case something didn't get modified (e.g. an
  4498. implicit register). Also, if it does read from this
  4499. register, then there's no longer an advantage to
  4500. changing the register on subsequent instructions.}
  4501. if not RegReadByInstruction(p_TargetReg, hp2) then
  4502. begin
  4503. { If a conditional jump was crossed, do not delete
  4504. the original MOV no matter what }
  4505. if not CrossJump and
  4506. { RegEndOfLife returns True if the register is
  4507. deallocated before the next instruction or has
  4508. been loaded with a new value }
  4509. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4510. begin
  4511. { We can remove the original MOV }
  4512. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4513. RemoveCurrentp(p, hp1);
  4514. JumpTracking.Free;
  4515. Result := True;
  4516. Exit;
  4517. end;
  4518. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4519. begin
  4520. { See if there's more we can optimise }
  4521. hp3 := hp2;
  4522. Continue;
  4523. end;
  4524. end;
  4525. end;
  4526. end;
  4527. { Break out of the while loop under normal circumstances }
  4528. Break;
  4529. end;
  4530. JumpTracking.Free;
  4531. end;
  4532. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4533. (taicpu(p).oper[1]^.typ = top_reg) and
  4534. (taicpu(p).opsize = S_L) and
  4535. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4536. (hp2.typ = ait_instruction) and
  4537. (taicpu(hp2).opcode = A_AND) and
  4538. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4539. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4540. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4541. ) then
  4542. begin
  4543. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4544. begin
  4545. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4546. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4547. begin
  4548. { Optimize out:
  4549. mov x, %reg
  4550. and ffffffffh, %reg
  4551. }
  4552. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4553. RemoveInstruction(hp2);
  4554. Result:=true;
  4555. exit;
  4556. end;
  4557. end;
  4558. end;
  4559. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4560. x >= RetOffset) as it doesn't do anything (it writes either to a
  4561. parameter or to the temporary storage room for the function
  4562. result)
  4563. }
  4564. if IsExitCode(hp1) and
  4565. (taicpu(p).oper[1]^.typ = top_ref) and
  4566. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4567. (
  4568. (
  4569. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4570. not (
  4571. assigned(current_procinfo.procdef.funcretsym) and
  4572. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4573. )
  4574. ) or
  4575. { Also discard writes to the stack that are below the base pointer,
  4576. as this is temporary storage rather than a function result on the
  4577. stack, say. }
  4578. (
  4579. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4580. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4581. )
  4582. ) then
  4583. begin
  4584. RemoveCurrentp(p, hp1);
  4585. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4586. RemoveLastDeallocForFuncRes(p);
  4587. Result:=true;
  4588. exit;
  4589. end;
  4590. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4591. begin
  4592. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4593. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4594. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4595. begin
  4596. { change
  4597. mov reg1, mem1
  4598. test/cmp x, mem1
  4599. to
  4600. mov reg1, mem1
  4601. test/cmp x, reg1
  4602. }
  4603. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4604. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4605. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4606. Result := True;
  4607. Exit;
  4608. end;
  4609. if DoMovCmpMemOpt(p, hp1) then
  4610. begin
  4611. Result := True;
  4612. Exit;
  4613. end;
  4614. end;
  4615. if (taicpu(p).oper[1]^.typ = top_reg) and
  4616. (hp1.typ = ait_instruction) and
  4617. GetNextInstruction(hp1, hp2) and
  4618. MatchInstruction(hp2,A_MOV,[]) and
  4619. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4620. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4621. (
  4622. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4623. {$ifdef x86_64}
  4624. or
  4625. (
  4626. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4627. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4628. )
  4629. {$endif x86_64}
  4630. ) then
  4631. begin
  4632. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4633. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4634. { change movsX/movzX reg/ref, reg2
  4635. add/sub/or/... reg3/$const, reg2
  4636. mov reg2 reg/ref
  4637. dealloc reg2
  4638. to
  4639. add/sub/or/... reg3/$const, reg/ref }
  4640. begin
  4641. TransferUsedRegs(TmpUsedRegs);
  4642. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4643. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4644. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4645. begin
  4646. { by example:
  4647. movswl %si,%eax movswl %si,%eax p
  4648. decl %eax addl %edx,%eax hp1
  4649. movw %ax,%si movw %ax,%si hp2
  4650. ->
  4651. movswl %si,%eax movswl %si,%eax p
  4652. decw %eax addw %edx,%eax hp1
  4653. movw %ax,%si movw %ax,%si hp2
  4654. }
  4655. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4656. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4657. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4658. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4659. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4660. {
  4661. ->
  4662. movswl %si,%eax movswl %si,%eax p
  4663. decw %si addw %dx,%si hp1
  4664. movw %ax,%si movw %ax,%si hp2
  4665. }
  4666. case taicpu(hp1).ops of
  4667. 1:
  4668. begin
  4669. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4670. if taicpu(hp1).oper[0]^.typ=top_reg then
  4671. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4672. end;
  4673. 2:
  4674. begin
  4675. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4676. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4677. (taicpu(hp1).opcode<>A_SHL) and
  4678. (taicpu(hp1).opcode<>A_SHR) and
  4679. (taicpu(hp1).opcode<>A_SAR) then
  4680. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4681. end;
  4682. else
  4683. internalerror(2008042701);
  4684. end;
  4685. {
  4686. ->
  4687. decw %si addw %dx,%si p
  4688. }
  4689. RemoveInstruction(hp2);
  4690. RemoveCurrentP(p, hp1);
  4691. Result:=True;
  4692. Exit;
  4693. end;
  4694. end;
  4695. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4696. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4697. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4698. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4699. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4700. )
  4701. {$ifdef i386}
  4702. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4703. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4704. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4705. {$endif i386}
  4706. then
  4707. { change movsX/movzX reg/ref, reg2
  4708. add/sub/or/... regX/$const, reg2
  4709. mov reg2, reg3
  4710. dealloc reg2
  4711. to
  4712. movsX/movzX reg/ref, reg3
  4713. add/sub/or/... reg3/$const, reg3
  4714. }
  4715. begin
  4716. TransferUsedRegs(TmpUsedRegs);
  4717. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4718. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4719. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4720. begin
  4721. { by example:
  4722. movswl %si,%eax movswl %si,%eax p
  4723. decl %eax addl %edx,%eax hp1
  4724. movw %ax,%si movw %ax,%si hp2
  4725. ->
  4726. movswl %si,%eax movswl %si,%eax p
  4727. decw %eax addw %edx,%eax hp1
  4728. movw %ax,%si movw %ax,%si hp2
  4729. }
  4730. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4731. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4732. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4733. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4734. { limit size of constants as well to avoid assembler errors, but
  4735. check opsize to avoid overflow when left shifting the 1 }
  4736. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4737. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4738. {$ifdef x86_64}
  4739. { Be careful of, for example:
  4740. movl %reg1,%reg2
  4741. addl %reg3,%reg2
  4742. movq %reg2,%reg4
  4743. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4744. }
  4745. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4746. begin
  4747. taicpu(hp2).changeopsize(S_L);
  4748. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4749. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4750. end;
  4751. {$endif x86_64}
  4752. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4753. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4754. if taicpu(p).oper[0]^.typ=top_reg then
  4755. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4756. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4757. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4758. {
  4759. ->
  4760. movswl %si,%eax movswl %si,%eax p
  4761. decw %si addw %dx,%si hp1
  4762. movw %ax,%si movw %ax,%si hp2
  4763. }
  4764. case taicpu(hp1).ops of
  4765. 1:
  4766. begin
  4767. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4768. if taicpu(hp1).oper[0]^.typ=top_reg then
  4769. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4770. end;
  4771. 2:
  4772. begin
  4773. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4774. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4775. (taicpu(hp1).opcode<>A_SHL) and
  4776. (taicpu(hp1).opcode<>A_SHR) and
  4777. (taicpu(hp1).opcode<>A_SAR) then
  4778. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4779. end;
  4780. else
  4781. internalerror(2018111801);
  4782. end;
  4783. {
  4784. ->
  4785. decw %si addw %dx,%si p
  4786. }
  4787. RemoveInstruction(hp2);
  4788. end;
  4789. end;
  4790. end;
  4791. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4792. GetNextInstruction(hp1, hp2) and
  4793. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4794. MatchOperand(Taicpu(p).oper[0]^,0) and
  4795. (Taicpu(p).oper[1]^.typ = top_reg) and
  4796. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4797. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4798. { mov reg1,0
  4799. bts reg1,operand1 --> mov reg1,operand2
  4800. or reg1,operand2 bts reg1,operand1}
  4801. begin
  4802. Taicpu(hp2).opcode:=A_MOV;
  4803. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4804. asml.remove(hp1);
  4805. insertllitem(hp2,hp2.next,hp1);
  4806. RemoveCurrentp(p, hp1);
  4807. Result:=true;
  4808. exit;
  4809. end;
  4810. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4811. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4812. GetNextInstruction(hp1, hp2) and
  4813. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4814. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4815. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4816. { change
  4817. mov reg1,reg2
  4818. sub reg3,reg2
  4819. cmp reg3,reg1
  4820. into
  4821. mov reg1,reg2
  4822. sub reg3,reg2
  4823. }
  4824. begin
  4825. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4826. RemoveInstruction(hp2);
  4827. Result:=true;
  4828. exit;
  4829. end;
  4830. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4831. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4832. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4833. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4834. begin
  4835. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4836. {$ifdef x86_64}
  4837. { Convert:
  4838. movq x(ref),%reg64
  4839. shrq y,%reg64
  4840. To:
  4841. movl x+4(ref),%reg32
  4842. shrl y-32,%reg32 (Remove if y = 32)
  4843. }
  4844. if (taicpu(p).opsize = S_Q) and
  4845. (taicpu(hp1).opcode = A_SHR) and
  4846. (taicpu(hp1).oper[0]^.val >= 32) then
  4847. begin
  4848. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4849. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4850. { Convert to 32-bit }
  4851. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4852. taicpu(p).opsize := S_L;
  4853. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4854. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4855. if (taicpu(hp1).oper[0]^.val = 32) then
  4856. begin
  4857. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4858. RemoveInstruction(hp1);
  4859. end
  4860. else
  4861. begin
  4862. { This will potentially open up more arithmetic operations since
  4863. the peephole optimizer now has a big hint that only the lower
  4864. 32 bits are currently in use (and opcodes are smaller in size) }
  4865. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4866. taicpu(hp1).opsize := S_L;
  4867. Dec(taicpu(hp1).oper[0]^.val, 32);
  4868. DebugMsg(SPeepholeOptimization + PreMessage +
  4869. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4870. end;
  4871. Result := True;
  4872. Exit;
  4873. end;
  4874. {$endif x86_64}
  4875. { Convert:
  4876. movl x(ref),%reg
  4877. shrl $24,%reg
  4878. To:
  4879. movzbl x+3(ref),%reg
  4880. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4881. Also accept sar instead of shr, but convert to movsx instead of movzx
  4882. }
  4883. if taicpu(hp1).opcode = A_SHR then
  4884. MovUnaligned := A_MOVZX
  4885. else
  4886. MovUnaligned := A_MOVSX;
  4887. NewSize := S_NO;
  4888. NewOffset := 0;
  4889. case taicpu(p).opsize of
  4890. S_B:
  4891. { No valid combinations };
  4892. S_W:
  4893. if (taicpu(hp1).oper[0]^.val = 8) then
  4894. begin
  4895. NewSize := S_BW;
  4896. NewOffset := 1;
  4897. end;
  4898. S_L:
  4899. case taicpu(hp1).oper[0]^.val of
  4900. 16:
  4901. begin
  4902. NewSize := S_WL;
  4903. NewOffset := 2;
  4904. end;
  4905. 24:
  4906. begin
  4907. NewSize := S_BL;
  4908. NewOffset := 3;
  4909. end;
  4910. else
  4911. ;
  4912. end;
  4913. {$ifdef x86_64}
  4914. S_Q:
  4915. case taicpu(hp1).oper[0]^.val of
  4916. 32:
  4917. begin
  4918. if taicpu(hp1).opcode = A_SAR then
  4919. begin
  4920. { 32-bit to 64-bit is a distinct instruction }
  4921. MovUnaligned := A_MOVSXD;
  4922. NewSize := S_LQ;
  4923. NewOffset := 4;
  4924. end
  4925. else
  4926. { Should have been handled by MovShr2Mov above }
  4927. InternalError(2022081811);
  4928. end;
  4929. 48:
  4930. begin
  4931. NewSize := S_WQ;
  4932. NewOffset := 6;
  4933. end;
  4934. 56:
  4935. begin
  4936. NewSize := S_BQ;
  4937. NewOffset := 7;
  4938. end;
  4939. else
  4940. ;
  4941. end;
  4942. {$endif x86_64}
  4943. else
  4944. InternalError(2022081810);
  4945. end;
  4946. if (NewSize <> S_NO) and
  4947. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4948. begin
  4949. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4950. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4951. debug_op2str(MovUnaligned);
  4952. {$ifdef x86_64}
  4953. if MovUnaligned <> A_MOVSXD then
  4954. { Don't add size suffix for MOVSXD }
  4955. {$endif x86_64}
  4956. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4957. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4958. taicpu(p).opcode := MovUnaligned;
  4959. taicpu(p).opsize := NewSize;
  4960. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4961. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4962. RemoveInstruction(hp1);
  4963. Result := True;
  4964. Exit;
  4965. end;
  4966. end;
  4967. { Backward optimisation shared with OptPass2MOV }
  4968. if FuncMov2Func(p, hp1) then
  4969. begin
  4970. Result := True;
  4971. Exit;
  4972. end;
  4973. end;
  4974. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4975. var
  4976. hp1 : tai;
  4977. begin
  4978. Result:=false;
  4979. if taicpu(p).ops <> 2 then
  4980. exit;
  4981. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4982. GetNextInstruction(p,hp1) then
  4983. begin
  4984. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4985. (taicpu(hp1).ops = 2) then
  4986. begin
  4987. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4988. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4989. { movXX reg1, mem1 or movXX mem1, reg1
  4990. movXX mem2, reg2 movXX reg2, mem2}
  4991. begin
  4992. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4993. { movXX reg1, mem1 or movXX mem1, reg1
  4994. movXX mem2, reg1 movXX reg2, mem1}
  4995. begin
  4996. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4997. begin
  4998. { Removes the second statement from
  4999. movXX reg1, mem1/reg2
  5000. movXX mem1/reg2, reg1
  5001. }
  5002. if taicpu(p).oper[0]^.typ=top_reg then
  5003. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  5004. { Removes the second statement from
  5005. movXX mem1/reg1, reg2
  5006. movXX reg2, mem1/reg1
  5007. }
  5008. if (taicpu(p).oper[1]^.typ=top_reg) and
  5009. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  5010. begin
  5011. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  5012. RemoveInstruction(hp1);
  5013. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  5014. Result:=true;
  5015. exit;
  5016. end
  5017. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  5018. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  5019. begin
  5020. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  5021. RemoveInstruction(hp1);
  5022. Result:=true;
  5023. exit;
  5024. end;
  5025. end
  5026. end;
  5027. end;
  5028. end;
  5029. end;
  5030. end;
  5031. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  5032. var
  5033. hp1 : tai;
  5034. begin
  5035. result:=false;
  5036. { replace
  5037. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  5038. MovX %mreg2,%mreg1
  5039. dealloc %mreg2
  5040. by
  5041. <Op>X %mreg2,%mreg1
  5042. ?
  5043. }
  5044. if GetNextInstruction(p,hp1) and
  5045. { we mix single and double opperations here because we assume that the compiler
  5046. generates vmovapd only after double operations and vmovaps only after single operations }
  5047. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5048. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5049. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5050. (taicpu(p).oper[0]^.typ=top_reg) then
  5051. begin
  5052. TransferUsedRegs(TmpUsedRegs);
  5053. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5054. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5055. begin
  5056. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5057. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5058. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5059. RemoveInstruction(hp1);
  5060. result:=true;
  5061. end;
  5062. end;
  5063. end;
  5064. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5065. var
  5066. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5067. JumpLabel, JumpLabel_dist: TAsmLabel;
  5068. FirstValue, SecondValue: TCGInt;
  5069. function OptimizeJump(var InputP: tai): Boolean;
  5070. var
  5071. TempBool: Boolean;
  5072. begin
  5073. Result := False;
  5074. TempBool := True;
  5075. if DoJumpOptimizations(InputP, TempBool) or
  5076. not TempBool then
  5077. begin
  5078. Result := True;
  5079. if Assigned(InputP) then
  5080. begin
  5081. { CollapseZeroDistJump will be set to the label or an align
  5082. before it after the jump if it optimises, whether or not
  5083. the label is live or dead }
  5084. if (InputP.typ = ait_align) or
  5085. (
  5086. (InputP.typ = ait_label) and
  5087. not (tai_label(InputP).labsym.is_used)
  5088. ) then
  5089. GetNextInstruction(InputP, InputP);
  5090. end;
  5091. Exit;
  5092. end;
  5093. end;
  5094. begin
  5095. Result := False;
  5096. if (taicpu(p).oper[0]^.typ = top_const) and
  5097. (taicpu(p).oper[0]^.val <> -1) then
  5098. begin
  5099. { Convert unsigned maximum constants to -1 to aid optimisation }
  5100. case taicpu(p).opsize of
  5101. S_B:
  5102. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5103. begin
  5104. taicpu(p).oper[0]^.val := -1;
  5105. Result := True;
  5106. Exit;
  5107. end;
  5108. S_W:
  5109. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5110. begin
  5111. taicpu(p).oper[0]^.val := -1;
  5112. Result := True;
  5113. Exit;
  5114. end;
  5115. S_L:
  5116. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5117. begin
  5118. taicpu(p).oper[0]^.val := -1;
  5119. Result := True;
  5120. Exit;
  5121. end;
  5122. {$ifdef x86_64}
  5123. S_Q:
  5124. { Storing anything greater than $7FFFFFFF is not possible so do
  5125. nothing };
  5126. {$endif x86_64}
  5127. else
  5128. InternalError(2021121001);
  5129. end;
  5130. end;
  5131. if GetNextInstruction(p, hp1) and
  5132. TrySwapMovCmp(p, hp1) then
  5133. begin
  5134. Result := True;
  5135. Exit;
  5136. end;
  5137. p_label := nil;
  5138. JumpLabel := nil;
  5139. if MatchInstruction(hp1, A_Jcc, []) then
  5140. begin
  5141. if OptimizeJump(hp1) then
  5142. begin
  5143. Result := True;
  5144. if Assigned(hp1) then
  5145. begin
  5146. { CollapseZeroDistJump will be set to the label or an align
  5147. before it after the jump if it optimises, whether or not
  5148. the label is live or dead }
  5149. if (hp1.typ = ait_align) or
  5150. (
  5151. (hp1.typ = ait_label) and
  5152. not (tai_label(hp1).labsym.is_used)
  5153. ) then
  5154. GetNextInstruction(hp1, hp1);
  5155. end;
  5156. TransferUsedRegs(TmpUsedRegs);
  5157. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5158. if not Assigned(hp1) or
  5159. (
  5160. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5161. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5162. ) then
  5163. begin
  5164. { No more conditional jumps; conditional statement is no longer required }
  5165. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5166. RemoveCurrentP(p);
  5167. end;
  5168. Exit;
  5169. end;
  5170. if IsJumpToLabel(taicpu(hp1)) then
  5171. begin
  5172. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5173. if Assigned(JumpLabel) then
  5174. p_label := getlabelwithsym(JumpLabel);
  5175. end;
  5176. end;
  5177. { Search for:
  5178. test $x,(reg/ref)
  5179. jne @lbl1
  5180. test $y,(reg/ref) (same register or reference)
  5181. jne @lbl1
  5182. Change to:
  5183. test $(x or y),(reg/ref)
  5184. jne @lbl1
  5185. (Note, this doesn't work with je instead of jne)
  5186. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5187. Also search for:
  5188. test $x,(reg/ref)
  5189. je @lbl1
  5190. ...
  5191. test $y,(reg/ref)
  5192. je/jne @lbl2
  5193. If (x or y) = x, then the second jump is deterministic
  5194. }
  5195. if (
  5196. (
  5197. (taicpu(p).oper[0]^.typ = top_const) or
  5198. (
  5199. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5200. (taicpu(p).oper[0]^.typ = top_reg) and
  5201. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5202. )
  5203. ) and
  5204. MatchInstruction(hp1, A_JCC, [])
  5205. ) then
  5206. begin
  5207. if (taicpu(p).oper[0]^.typ = top_reg) and
  5208. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5209. FirstValue := -1
  5210. else
  5211. FirstValue := taicpu(p).oper[0]^.val;
  5212. { If we have several test/jne's in a row, it might be the case that
  5213. the second label doesn't go to the same location, but the one
  5214. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5215. so accommodate for this with a while loop.
  5216. }
  5217. hp1_last := hp1;
  5218. while (
  5219. (
  5220. (taicpu(p).oper[1]^.typ = top_reg) and
  5221. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5222. ) or GetNextInstruction(hp1_last, p_dist)
  5223. ) and (p_dist.typ = ait_instruction) do
  5224. begin
  5225. if (
  5226. (
  5227. (taicpu(p_dist).opcode = A_TEST) and
  5228. (
  5229. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5230. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5231. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5232. )
  5233. ) or
  5234. (
  5235. { cmp 0,%reg = test %reg,%reg }
  5236. (taicpu(p_dist).opcode = A_CMP) and
  5237. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5238. )
  5239. ) and
  5240. { Make sure the destination operands are actually the same }
  5241. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5242. GetNextInstruction(p_dist, hp1_dist) and
  5243. MatchInstruction(hp1_dist, A_JCC, []) then
  5244. begin
  5245. if OptimizeJump(hp1_dist) then
  5246. begin
  5247. Result := True;
  5248. Exit;
  5249. end;
  5250. if
  5251. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5252. (
  5253. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5254. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5255. ) then
  5256. SecondValue := -1
  5257. else
  5258. SecondValue := taicpu(p_dist).oper[0]^.val;
  5259. { If both of the TEST constants are identical, delete the
  5260. second TEST that is unnecessary (be careful though, just
  5261. in case the flags are modified in between) }
  5262. if (FirstValue = SecondValue) then
  5263. begin
  5264. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5265. begin
  5266. { Since the second jump's condition is a subset of the first, we
  5267. know it will never branch because the first jump dominates it.
  5268. Get it out of the way now rather than wait for the jump
  5269. optimisations for a speed boost. }
  5270. if IsJumpToLabel(taicpu(hp1_dist)) then
  5271. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5272. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5273. RemoveInstruction(hp1_dist);
  5274. Result := True;
  5275. end
  5276. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5277. begin
  5278. { If the inverse of the first condition is a subset of the second,
  5279. the second one will definitely branch if the first one doesn't }
  5280. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5281. { We can remove the TEST instruction too }
  5282. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5283. RemoveInstruction(p_dist);
  5284. MakeUnconditional(taicpu(hp1_dist));
  5285. RemoveDeadCodeAfterJump(hp1_dist);
  5286. { Since the jump is now unconditional, we can't
  5287. continue any further with this particular
  5288. optimisation. The original TEST is still intact
  5289. though, so there might be something else we can
  5290. do }
  5291. Include(OptsToCheck, aoc_ForceNewIteration);
  5292. Break;
  5293. end;
  5294. if Result or
  5295. { If a jump wasn't removed or made unconditional, only
  5296. remove the identical TEST instruction if the flags
  5297. weren't modified }
  5298. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5299. begin
  5300. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5301. RemoveInstruction(p_dist);
  5302. { If the jump was removed or made unconditional, we
  5303. don't need to allocate NR_DEFAULTFLAGS over the
  5304. entire range }
  5305. if not Result then
  5306. begin
  5307. { Mark the flags as 'in use' over the entire range }
  5308. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5309. { Speed gain - continue search from the Jcc instruction }
  5310. hp1_last := hp1_dist;
  5311. { Only the TEST instruction was removed, and the
  5312. original was unchanged, so we can safely do
  5313. another iteration of the while loop }
  5314. Include(OptsToCheck, aoc_ForceNewIteration);
  5315. Continue;
  5316. end;
  5317. Exit;
  5318. end;
  5319. end;
  5320. hp1_last := nil;
  5321. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5322. (
  5323. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5324. { Always adjacent under -O2 and under }
  5325. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5326. (
  5327. GetNextInstruction(hp1, hp1_last) and
  5328. (hp1_last = p_dist)
  5329. )
  5330. ) and
  5331. (
  5332. (
  5333. { Test the following variant:
  5334. test $x,(reg/ref)
  5335. jne @lbl1
  5336. test $y,(reg/ref)
  5337. je @lbl2
  5338. @lbl1:
  5339. Becomes:
  5340. test $(x or y),(reg/ref)
  5341. je @lbl2
  5342. @lbl1: (may become a dead label)
  5343. }
  5344. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5345. GetNextInstruction(hp1_dist, hp1_last) and
  5346. (hp1_last = p_label)
  5347. ) or
  5348. (
  5349. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5350. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5351. then the second jump will never branch, so it can also be
  5352. removed regardless of where it goes }
  5353. (
  5354. (FirstValue = -1) or
  5355. (SecondValue = -1) or
  5356. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5357. )
  5358. )
  5359. ) then
  5360. begin
  5361. { Same jump location... can be a register since nothing's changed }
  5362. { If any of the entries are equivalent to test %reg,%reg, then the
  5363. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5364. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5365. if (hp1_last = p_label) then
  5366. begin
  5367. { Variant }
  5368. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5369. RemoveInstruction(p_dist);
  5370. if Assigned(JumpLabel) then
  5371. JumpLabel.decrefs;
  5372. RemoveInstruction(hp1);
  5373. end
  5374. else
  5375. begin
  5376. { Only remove the second test if no jumps or other conditional instructions follow }
  5377. TransferUsedRegs(TmpUsedRegs);
  5378. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5379. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5380. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5381. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5382. begin
  5383. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5384. RemoveInstruction(p_dist);
  5385. { Remove the first jump, not the second, to keep
  5386. any register deallocations between the second
  5387. TEST/JNE pair in the same place. Aids future
  5388. optimisation. }
  5389. if Assigned(JumpLabel) then
  5390. JumpLabel.decrefs;
  5391. RemoveInstruction(hp1);
  5392. end
  5393. else
  5394. begin
  5395. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5396. if IsJumpToLabel(taicpu(hp1_dist)) then
  5397. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5398. { Remove second jump in this instance }
  5399. RemoveInstruction(hp1_dist);
  5400. end;
  5401. end;
  5402. Result := True;
  5403. Exit;
  5404. end;
  5405. end;
  5406. if { If -O2 and under, it may stop on any old instruction }
  5407. (cs_opt_level3 in current_settings.optimizerswitches) and
  5408. (taicpu(p).oper[1]^.typ = top_reg) and
  5409. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5410. begin
  5411. hp1_last := p_dist;
  5412. Continue;
  5413. end;
  5414. Break;
  5415. end;
  5416. end;
  5417. { Search for:
  5418. test %reg,%reg
  5419. j(c1) @lbl1
  5420. ...
  5421. @lbl:
  5422. test %reg,%reg (same register)
  5423. j(c2) @lbl2
  5424. If c2 is a subset of c1, change to:
  5425. test %reg,%reg
  5426. j(c1) @lbl2
  5427. (@lbl1 may become a dead label as a result)
  5428. }
  5429. if (taicpu(p).oper[1]^.typ = top_reg) and
  5430. (taicpu(p).oper[0]^.typ = top_reg) and
  5431. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5432. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5433. Assigned(p_label) and
  5434. GetNextInstruction(p_label, p_dist) and
  5435. MatchInstruction(p_dist, A_TEST, []) and
  5436. { It's fine if the second test uses smaller sub-registers }
  5437. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5438. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5439. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5440. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5441. GetNextInstruction(p_dist, hp1_dist) and
  5442. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5443. begin
  5444. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5445. if JumpLabel = JumpLabel_dist then
  5446. { This is an infinite loop }
  5447. Exit;
  5448. { Best optimisation when the first condition is a subset (or equal) of the second }
  5449. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5450. begin
  5451. { Any registers used here will already be allocated }
  5452. if Assigned(JumpLabel) then
  5453. JumpLabel.DecRefs;
  5454. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5455. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5456. Result := True;
  5457. Exit;
  5458. end;
  5459. end;
  5460. end;
  5461. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5462. var
  5463. hp1, hp2: tai;
  5464. ActiveReg: TRegister;
  5465. OldOffset: asizeint;
  5466. ThisConst: TCGInt;
  5467. function RegDeallocated: Boolean;
  5468. begin
  5469. TransferUsedRegs(TmpUsedRegs);
  5470. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5471. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5472. end;
  5473. begin
  5474. result:=false;
  5475. hp1 := nil;
  5476. { replace
  5477. addX const,%reg1
  5478. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5479. dealloc %reg1
  5480. by
  5481. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5482. }
  5483. if MatchOpType(taicpu(p),top_const,top_reg) then
  5484. begin
  5485. ActiveReg := taicpu(p).oper[1]^.reg;
  5486. { Ensures the entire register was updated }
  5487. if (taicpu(p).opsize >= S_L) and
  5488. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5489. MatchInstruction(hp1,A_LEA,[]) and
  5490. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5491. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5492. (
  5493. { Cover the case where the register in the reference is also the destination register }
  5494. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5495. (
  5496. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5497. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5498. RegDeallocated
  5499. )
  5500. ) then
  5501. begin
  5502. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5503. {$push}
  5504. {$R-}{$Q-}
  5505. { Explicitly disable overflow checking for these offset calculation
  5506. as those do not matter for the final result }
  5507. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5508. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5509. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5510. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5511. {$pop}
  5512. {$ifdef x86_64}
  5513. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5514. begin
  5515. { Overflow; abort }
  5516. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5517. end
  5518. else
  5519. {$endif x86_64}
  5520. begin
  5521. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5522. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5523. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5524. RemoveCurrentP(p, hp1)
  5525. else
  5526. RemoveCurrentP(p);
  5527. result:=true;
  5528. Exit;
  5529. end;
  5530. end;
  5531. if (
  5532. { Save calling GetNextInstructionUsingReg again }
  5533. Assigned(hp1) or
  5534. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5535. ) and
  5536. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5537. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5538. begin
  5539. if taicpu(hp1).oper[0]^.typ = top_const then
  5540. begin
  5541. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5542. if taicpu(hp1).opcode = A_ADD then
  5543. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5544. else
  5545. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5546. Result := True;
  5547. { Handle any overflows }
  5548. case taicpu(p).opsize of
  5549. S_B:
  5550. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5551. S_W:
  5552. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5553. S_L:
  5554. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5555. {$ifdef x86_64}
  5556. S_Q:
  5557. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5558. { Overflow; abort }
  5559. Result := False
  5560. else
  5561. taicpu(p).oper[0]^.val := ThisConst;
  5562. {$endif x86_64}
  5563. else
  5564. InternalError(2021102610);
  5565. end;
  5566. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5567. if Result then
  5568. begin
  5569. if (taicpu(p).oper[0]^.val < 0) and
  5570. (
  5571. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5572. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5573. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5574. ) then
  5575. begin
  5576. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5577. taicpu(p).opcode := A_SUB;
  5578. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5579. end
  5580. else
  5581. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5582. RemoveInstruction(hp1);
  5583. end;
  5584. end
  5585. else
  5586. begin
  5587. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5588. TransferUsedRegs(TmpUsedRegs);
  5589. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5590. hp2 := p;
  5591. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5592. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5593. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5594. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5595. begin
  5596. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5597. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5598. Asml.Remove(p);
  5599. Asml.InsertAfter(p, hp1);
  5600. p := hp1;
  5601. Result := True;
  5602. Exit;
  5603. end;
  5604. end;
  5605. end;
  5606. if DoArithCombineOpt(p) then
  5607. Result:=true;
  5608. end;
  5609. end;
  5610. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5611. var
  5612. hp1, hp2: tai;
  5613. ref: Integer;
  5614. saveref: treference;
  5615. offsetcalc: Int64;
  5616. TempReg: TRegister;
  5617. Multiple: TCGInt;
  5618. Adjacent, IntermediateRegDiscarded: Boolean;
  5619. begin
  5620. Result:=false;
  5621. { play save and throw an error if LEA uses a seg register prefix,
  5622. this is most likely an error somewhere else }
  5623. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5624. internalerror(2022022001);
  5625. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5626. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5627. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5628. (
  5629. { do not mess with leas accessing the stack pointer
  5630. unless it's a null operation }
  5631. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5632. (
  5633. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5634. (taicpu(p).oper[0]^.ref^.offset = 0)
  5635. )
  5636. ) and
  5637. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5638. begin
  5639. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5640. begin
  5641. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5642. begin
  5643. taicpu(p).opcode := A_MOV;
  5644. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5645. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5646. end
  5647. else
  5648. begin
  5649. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5650. RemoveCurrentP(p);
  5651. end;
  5652. Result:=true;
  5653. exit;
  5654. end
  5655. else if (
  5656. { continue to use lea to adjust the stack pointer,
  5657. it is the recommended way, but only if not optimizing for size }
  5658. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5659. (cs_opt_size in current_settings.optimizerswitches)
  5660. ) and
  5661. { If the flags register is in use, don't change the instruction
  5662. to an ADD otherwise this will scramble the flags. [Kit] }
  5663. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5664. ConvertLEA(taicpu(p)) then
  5665. begin
  5666. Result:=true;
  5667. exit;
  5668. end;
  5669. end;
  5670. { Don't optimise if the stack or frame pointer is the destination register }
  5671. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5672. Exit;
  5673. if GetNextInstruction(p,hp1) and
  5674. (hp1.typ=ait_instruction) then
  5675. begin
  5676. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5677. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5678. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5679. begin
  5680. TransferUsedRegs(TmpUsedRegs);
  5681. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5682. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5683. begin
  5684. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5685. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5686. RemoveInstruction(hp1);
  5687. result:=true;
  5688. exit;
  5689. end;
  5690. end;
  5691. { changes
  5692. lea <ref1>, reg1
  5693. <op> ...,<ref. with reg1>,...
  5694. to
  5695. <op> ...,<ref1>,... }
  5696. { find a reference which uses reg1 }
  5697. 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
  5698. ref:=0
  5699. 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
  5700. ref:=1
  5701. else
  5702. ref:=-1;
  5703. if (ref<>-1) and
  5704. { reg1 must be either the base or the index }
  5705. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5706. begin
  5707. { reg1 can be removed from the reference }
  5708. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5709. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5710. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5711. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5712. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5713. else
  5714. Internalerror(2019111201);
  5715. { check if the can insert all data of the lea into the second instruction }
  5716. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5717. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5718. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5719. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5720. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5721. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5722. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5723. {$ifdef x86_64}
  5724. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5725. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5726. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5727. )
  5728. {$endif x86_64}
  5729. then
  5730. begin
  5731. { reg1 might not used by the second instruction after it is remove from the reference }
  5732. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5733. begin
  5734. TransferUsedRegs(TmpUsedRegs);
  5735. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5736. { reg1 is not updated so it might not be used afterwards }
  5737. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5738. begin
  5739. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5740. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5741. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5742. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5743. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5744. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5745. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5746. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5747. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5748. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5749. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5750. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5751. RemoveCurrentP(p, hp1);
  5752. result:=true;
  5753. exit;
  5754. end
  5755. end;
  5756. end;
  5757. { recover }
  5758. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5759. end;
  5760. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5761. if Adjacent or
  5762. { Check further ahead (up to 2 instructions ahead for -O2) }
  5763. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5764. begin
  5765. { Check common LEA/LEA conditions }
  5766. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5767. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5768. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5769. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5770. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5771. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5772. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5773. (
  5774. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5775. calling it (since it calls GetNextInstruction) }
  5776. Adjacent or
  5777. (
  5778. (
  5779. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5780. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5781. ) and (
  5782. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5783. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5784. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5785. )
  5786. )
  5787. ) then
  5788. begin
  5789. TransferUsedRegs(TmpUsedRegs);
  5790. hp2 := p;
  5791. repeat
  5792. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5793. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5794. IntermediateRegDiscarded :=
  5795. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5796. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5797. { changes
  5798. lea offset1(regX,scale), reg1
  5799. lea offset2(reg1,reg1), reg2
  5800. to
  5801. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5802. and
  5803. lea offset1(regX,scale1), reg1
  5804. lea offset2(reg1,scale2), reg2
  5805. to
  5806. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5807. and
  5808. lea offset1(regX,scale1), reg1
  5809. lea offset2(reg3,reg1,scale2), reg2
  5810. to
  5811. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5812. ... so long as the final scale does not exceed 8
  5813. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5814. }
  5815. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5816. (
  5817. { Don't optimise if size is a concern and the intermediate register remains in use }
  5818. IntermediateRegDiscarded or
  5819. not (cs_opt_size in current_settings.optimizerswitches)
  5820. ) and
  5821. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5822. (
  5823. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5824. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5825. ) and (
  5826. (
  5827. { lea (reg1,scale2), reg2 variant }
  5828. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5829. (
  5830. Adjacent or
  5831. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5832. ) and
  5833. (
  5834. (
  5835. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5836. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5837. ) or (
  5838. { lea (regX,regX), reg1 variant }
  5839. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5840. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5841. )
  5842. )
  5843. ) or (
  5844. { lea (reg1,reg1), reg1 variant }
  5845. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5846. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5847. )
  5848. ) then
  5849. begin
  5850. { Make everything homogeneous to make calculations easier }
  5851. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5852. begin
  5853. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5854. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5855. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5856. else
  5857. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5858. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5859. end;
  5860. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5861. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5862. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5863. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5864. begin
  5865. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5866. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5867. begin
  5868. { Put the register to change in the index register }
  5869. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5870. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5871. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5872. end;
  5873. { Change lea (reg,reg) to lea(,reg,2) }
  5874. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5875. begin
  5876. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5877. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5878. end;
  5879. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5880. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5881. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5882. { Just to prevent miscalculations }
  5883. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5884. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5885. else
  5886. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5887. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5888. if IntermediateRegDiscarded then
  5889. begin
  5890. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5891. RemoveCurrentP(p);
  5892. end
  5893. else
  5894. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5895. result:=true;
  5896. exit;
  5897. end;
  5898. end;
  5899. { changes
  5900. lea offset1(regX), reg1
  5901. lea offset2(reg1), reg2
  5902. to
  5903. lea offset1+offset2(regX), reg2 }
  5904. if (
  5905. { Don't optimise if size is a concern and the intermediate register remains in use }
  5906. IntermediateRegDiscarded or
  5907. not (cs_opt_size in current_settings.optimizerswitches)
  5908. ) and
  5909. (
  5910. (
  5911. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5912. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5913. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5914. ) or (
  5915. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5916. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5917. (
  5918. (
  5919. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5920. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5921. ) or (
  5922. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5923. (
  5924. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5925. (
  5926. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5927. (
  5928. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5929. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5930. )
  5931. )
  5932. )
  5933. )
  5934. )
  5935. )
  5936. ) then
  5937. begin
  5938. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5939. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5940. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5941. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5942. begin
  5943. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5944. begin
  5945. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5946. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5947. { if the register is used as index and base, we have to increase for base as well
  5948. and adapt base }
  5949. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5950. begin
  5951. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5952. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5953. end;
  5954. end
  5955. else
  5956. begin
  5957. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5958. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5959. end;
  5960. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5961. begin
  5962. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5963. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5964. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  5965. { Catch the situation where the base = index
  5966. and treat this as *2. The scalefactor of
  5967. p will be 0 or 1 due to the conditional
  5968. checks above. Fixes i40647 }
  5969. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  5970. else
  5971. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  5972. end;
  5973. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5974. if IntermediateRegDiscarded then
  5975. begin
  5976. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5977. RemoveCurrentP(p);
  5978. end
  5979. else
  5980. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5981. result:=true;
  5982. exit;
  5983. end;
  5984. end;
  5985. end;
  5986. { Change:
  5987. leal/q $x(%reg1),%reg2
  5988. ...
  5989. shll/q $y,%reg2
  5990. To:
  5991. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5992. }
  5993. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5994. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5995. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5996. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5997. (taicpu(hp1).oper[0]^.val <= 3) then
  5998. begin
  5999. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  6000. TransferUsedRegs(TmpUsedRegs);
  6001. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6002. if
  6003. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  6004. (this works even if scalefactor is zero) }
  6005. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  6006. { Ensure offset doesn't go out of bounds }
  6007. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  6008. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  6009. (
  6010. (
  6011. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  6012. (
  6013. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6014. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  6015. (
  6016. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  6017. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6018. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6019. )
  6020. )
  6021. ) or (
  6022. (
  6023. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  6024. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  6025. ) and
  6026. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  6027. )
  6028. ) then
  6029. begin
  6030. repeat
  6031. with taicpu(p).oper[0]^.ref^ do
  6032. begin
  6033. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  6034. if index = base then
  6035. begin
  6036. if Multiple > 4 then
  6037. { Optimisation will no longer work because resultant
  6038. scale factor will exceed 8 }
  6039. Break;
  6040. base := NR_NO;
  6041. scalefactor := 2;
  6042. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  6043. end
  6044. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6045. begin
  6046. { Scale factor only works on the index register }
  6047. index := base;
  6048. base := NR_NO;
  6049. end;
  6050. { For safety }
  6051. if scalefactor <= 1 then
  6052. begin
  6053. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6054. scalefactor := Multiple;
  6055. end
  6056. else
  6057. begin
  6058. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6059. scalefactor := scalefactor * Multiple;
  6060. end;
  6061. offset := offset * Multiple;
  6062. end;
  6063. RemoveInstruction(hp1);
  6064. Result := True;
  6065. Exit;
  6066. { This repeat..until loop exists for the benefit of Break }
  6067. until True;
  6068. end;
  6069. end;
  6070. end;
  6071. end;
  6072. end;
  6073. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6074. var
  6075. hp1 : tai;
  6076. SubInstr: Boolean;
  6077. ThisConst: TCGInt;
  6078. const
  6079. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6080. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6081. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6082. begin
  6083. Result := False;
  6084. if taicpu(p).oper[0]^.typ <> top_const then
  6085. { Should have been confirmed before calling }
  6086. InternalError(2021102601);
  6087. SubInstr := (taicpu(p).opcode = A_SUB);
  6088. if GetLastInstruction(p, hp1) and
  6089. (hp1.typ = ait_instruction) and
  6090. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6091. begin
  6092. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6093. { Bad size }
  6094. InternalError(2022042001);
  6095. case taicpu(hp1).opcode Of
  6096. A_INC:
  6097. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6098. begin
  6099. if SubInstr then
  6100. ThisConst := taicpu(p).oper[0]^.val - 1
  6101. else
  6102. ThisConst := taicpu(p).oper[0]^.val + 1;
  6103. end
  6104. else
  6105. Exit;
  6106. A_DEC:
  6107. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6108. begin
  6109. if SubInstr then
  6110. ThisConst := taicpu(p).oper[0]^.val + 1
  6111. else
  6112. ThisConst := taicpu(p).oper[0]^.val - 1;
  6113. end
  6114. else
  6115. Exit;
  6116. A_SUB:
  6117. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6118. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6119. begin
  6120. if SubInstr then
  6121. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6122. else
  6123. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6124. end
  6125. else
  6126. Exit;
  6127. A_ADD:
  6128. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6129. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6130. begin
  6131. if SubInstr then
  6132. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6133. else
  6134. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6135. end
  6136. else
  6137. Exit;
  6138. else
  6139. Exit;
  6140. end;
  6141. { Check that the values are in range }
  6142. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6143. { Overflow; abort }
  6144. Exit;
  6145. if (ThisConst = 0) then
  6146. begin
  6147. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6148. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6149. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6150. RemoveInstruction(hp1);
  6151. hp1 := tai(p.next);
  6152. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6153. if not GetLastInstruction(hp1, p) then
  6154. p := hp1;
  6155. end
  6156. else
  6157. begin
  6158. if taicpu(hp1).opercnt=1 then
  6159. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6160. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6161. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6162. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6163. else
  6164. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6165. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6166. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6167. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6168. RemoveInstruction(hp1);
  6169. taicpu(p).loadconst(0, ThisConst);
  6170. end;
  6171. Result := True;
  6172. end;
  6173. end;
  6174. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6175. begin
  6176. Result := False;
  6177. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6178. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6179. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6180. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6181. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6182. (
  6183. (
  6184. (taicpu(hp1).opcode = A_TEST)
  6185. ) or (
  6186. (taicpu(hp1).opcode = A_CMP) and
  6187. { A sanity check more than anything }
  6188. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6189. )
  6190. ) then
  6191. begin
  6192. { change
  6193. mov mem, %reg
  6194. ...
  6195. cmp/test x, %reg / test %reg,%reg
  6196. (reg deallocated)
  6197. to
  6198. cmp/test x, mem / cmp 0, mem
  6199. }
  6200. TransferUsedRegs(TmpUsedRegs);
  6201. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6202. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6203. begin
  6204. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6205. if (taicpu(hp1).opcode = A_TEST) and
  6206. (
  6207. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6208. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6209. ) then
  6210. begin
  6211. taicpu(hp1).opcode := A_CMP;
  6212. taicpu(hp1).loadconst(0, 0);
  6213. end;
  6214. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6215. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6216. RemoveCurrentP(p);
  6217. if (p <> hp1) then
  6218. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6219. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6220. { Make sure the flags are allocated across the CMP instruction }
  6221. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6222. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6223. Result := True;
  6224. Exit;
  6225. end;
  6226. end;
  6227. end;
  6228. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6229. var
  6230. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6231. ThisReg, SecondReg: TRegister;
  6232. JumpLoc: TAsmLabel;
  6233. NewSize: TOpSize;
  6234. begin
  6235. Result := False;
  6236. {
  6237. Convert:
  6238. j<c> .L1
  6239. .L2:
  6240. mov 1,reg
  6241. jmp .L3 (or ret, although it might not be a RET yet)
  6242. .L1:
  6243. mov 0,reg
  6244. jmp .L3 (or ret)
  6245. ( As long as .L3 <> .L1 or .L2)
  6246. To:
  6247. mov 0,reg
  6248. set<not(c)> reg
  6249. jmp .L3 (or ret)
  6250. .L2:
  6251. mov 1,reg
  6252. jmp .L3 (or ret)
  6253. .L1:
  6254. mov 0,reg
  6255. jmp .L3 (or ret)
  6256. }
  6257. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6258. Exit;
  6259. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6260. if GetNextInstruction(hp_label, hp2) and
  6261. MatchInstruction(hp2,A_MOV,[]) and
  6262. (taicpu(hp2).oper[0]^.typ = top_const) and
  6263. (
  6264. (
  6265. (taicpu(hp2).oper[1]^.typ = top_reg)
  6266. {$ifdef i386}
  6267. { Under i386, ESI, EDI, EBP and ESP
  6268. don't have an 8-bit representation }
  6269. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6270. {$endif i386}
  6271. ) or (
  6272. {$ifdef i386}
  6273. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6274. {$endif i386}
  6275. (taicpu(hp2).opsize = S_B)
  6276. )
  6277. ) and
  6278. GetNextInstruction(hp2, hp3) and
  6279. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6280. (
  6281. (taicpu(hp3).opcode=A_RET) or
  6282. (
  6283. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6284. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6285. )
  6286. ) and
  6287. GetNextInstruction(hp3, hp4) and
  6288. FindLabel(JumpLoc, hp4) and
  6289. (
  6290. not (cs_opt_size in current_settings.optimizerswitches) or
  6291. { If the initial jump is the label's only reference, then it will
  6292. become a dead label if the other conditions are met and hence
  6293. remove at least 2 instructions, including a jump }
  6294. (JumpLoc.getrefs = 1)
  6295. ) and
  6296. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6297. that will be optimised out }
  6298. GetNextInstruction(hp4, hp5) and
  6299. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6300. (taicpu(hp5).oper[0]^.typ = top_const) and
  6301. (
  6302. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6303. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6304. ) and
  6305. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6306. GetNextInstruction(hp5,hp6) and
  6307. (
  6308. not (hp6.typ in [ait_align, ait_label]) or
  6309. SkipLabels(hp6, hp6)
  6310. ) and
  6311. (hp6.typ=ait_instruction) then
  6312. begin
  6313. { First, let's look at the two jumps that are hp3 and hp6 }
  6314. if not
  6315. (
  6316. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6317. (
  6318. (taicpu(hp6).opcode=A_RET) or
  6319. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6320. )
  6321. ) then
  6322. { If condition is False, then the JMP/RET instructions matched conventionally }
  6323. begin
  6324. { See if one of the jumps can be instantly converted into a RET }
  6325. if (taicpu(hp3).opcode=A_JMP) then
  6326. begin
  6327. { Reuse hp5 }
  6328. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6329. { Make sure hp5 doesn't jump back to .L1 (zero distance jump) or .L2 (infinite loop) }
  6330. if not Assigned(hp5) or (hp5 = hp_label) or (hp5 = hp4) or not GetNextInstruction(hp5, hp5) then
  6331. Exit;
  6332. if MatchInstruction(hp5, A_RET, []) then
  6333. begin
  6334. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6335. ConvertJumpToRET(hp3, hp5);
  6336. Result := True;
  6337. end
  6338. else
  6339. Exit;
  6340. end;
  6341. if (taicpu(hp6).opcode=A_JMP) then
  6342. begin
  6343. { Reuse hp5 }
  6344. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6345. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6346. Exit;
  6347. if MatchInstruction(hp5, A_RET, []) then
  6348. begin
  6349. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6350. ConvertJumpToRET(hp6, hp5);
  6351. Result := True;
  6352. end
  6353. else
  6354. Exit;
  6355. end;
  6356. if not
  6357. (
  6358. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6359. (
  6360. (taicpu(hp6).opcode=A_RET) or
  6361. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6362. )
  6363. ) then
  6364. { Still doesn't match }
  6365. Exit;
  6366. end;
  6367. if (taicpu(hp2).oper[0]^.val = 1) then
  6368. begin
  6369. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6370. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6371. end
  6372. else
  6373. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6374. if taicpu(hp2).opsize=S_B then
  6375. begin
  6376. if taicpu(hp2).oper[1]^.typ = top_reg then
  6377. begin
  6378. SecondReg := taicpu(hp2).oper[1]^.reg;
  6379. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6380. end
  6381. else
  6382. begin
  6383. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6384. SecondReg := NR_NO;
  6385. end;
  6386. hp_pos := p;
  6387. hp_allocstart := hp4;
  6388. end
  6389. else
  6390. begin
  6391. { Will be a register because the size can't be S_B otherwise }
  6392. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6393. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6394. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6395. if (cs_opt_size in current_settings.optimizerswitches) then
  6396. begin
  6397. { Favour using MOVZX when optimising for size }
  6398. case taicpu(hp2).opsize of
  6399. S_W:
  6400. NewSize := S_BW;
  6401. S_L:
  6402. NewSize := S_BL;
  6403. {$ifdef x86_64}
  6404. S_Q:
  6405. begin
  6406. NewSize := S_BL;
  6407. { Will implicitly zero-extend to 64-bit }
  6408. setsubreg(SecondReg, R_SUBD);
  6409. end;
  6410. {$endif x86_64}
  6411. else
  6412. InternalError(2022101301);
  6413. end;
  6414. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6415. { Inserting it right before p will guarantee that the flags are also tracked }
  6416. Asml.InsertBefore(hp5, p);
  6417. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6418. hp_pos := hp5;
  6419. hp_allocstart := hp4;
  6420. end
  6421. else
  6422. begin
  6423. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6424. { Inserting it right before p will guarantee that the flags are also tracked }
  6425. Asml.InsertBefore(hp5, p);
  6426. hp_pos := p;
  6427. hp_allocstart := hp5;
  6428. end;
  6429. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6430. end;
  6431. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6432. taicpu(hp4).condition := taicpu(p).condition;
  6433. asml.InsertBefore(hp4, hp_pos);
  6434. if taicpu(hp3).is_jmp then
  6435. begin
  6436. JumpLoc.decrefs;
  6437. MakeUnconditional(taicpu(p));
  6438. { This also increases the reference count }
  6439. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6440. end
  6441. else
  6442. ConvertJumpToRET(p, hp3);
  6443. if SecondReg <> NR_NO then
  6444. { Ensure the destination register is allocated over this region }
  6445. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6446. if (JumpLoc.getrefs = 0) then
  6447. RemoveDeadCodeAfterJump(hp3);
  6448. Result:=true;
  6449. exit;
  6450. end;
  6451. end;
  6452. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6453. var
  6454. hp1, hp2: tai;
  6455. ActiveReg: TRegister;
  6456. OldOffset: asizeint;
  6457. ThisConst: TCGInt;
  6458. function RegDeallocated: Boolean;
  6459. begin
  6460. TransferUsedRegs(TmpUsedRegs);
  6461. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6462. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6463. end;
  6464. begin
  6465. Result:=false;
  6466. hp1 := nil;
  6467. { replace
  6468. subX const,%reg1
  6469. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6470. dealloc %reg1
  6471. by
  6472. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6473. }
  6474. if MatchOpType(taicpu(p),top_const,top_reg) then
  6475. begin
  6476. ActiveReg := taicpu(p).oper[1]^.reg;
  6477. { Ensures the entire register was updated }
  6478. if (taicpu(p).opsize >= S_L) and
  6479. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6480. MatchInstruction(hp1,A_LEA,[]) and
  6481. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6482. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6483. (
  6484. { Cover the case where the register in the reference is also the destination register }
  6485. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6486. (
  6487. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6488. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6489. RegDeallocated
  6490. )
  6491. ) then
  6492. begin
  6493. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6494. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6495. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6496. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6497. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6498. {$ifdef x86_64}
  6499. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6500. begin
  6501. { Overflow; abort }
  6502. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6503. end
  6504. else
  6505. {$endif x86_64}
  6506. begin
  6507. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6508. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6509. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6510. RemoveCurrentP(p, hp1)
  6511. else
  6512. RemoveCurrentP(p);
  6513. result:=true;
  6514. Exit;
  6515. end;
  6516. end;
  6517. if (
  6518. { Save calling GetNextInstructionUsingReg again }
  6519. Assigned(hp1) or
  6520. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6521. ) and
  6522. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6523. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6524. begin
  6525. if taicpu(hp1).oper[0]^.typ = top_const then
  6526. begin
  6527. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6528. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6529. Result := True;
  6530. { Handle any overflows }
  6531. case taicpu(p).opsize of
  6532. S_B:
  6533. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6534. S_W:
  6535. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6536. S_L:
  6537. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6538. {$ifdef x86_64}
  6539. S_Q:
  6540. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6541. { Overflow; abort }
  6542. Result := False
  6543. else
  6544. taicpu(p).oper[0]^.val := ThisConst;
  6545. {$endif x86_64}
  6546. else
  6547. InternalError(2021102611);
  6548. end;
  6549. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6550. if Result then
  6551. begin
  6552. if (taicpu(p).oper[0]^.val < 0) and
  6553. (
  6554. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6555. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6556. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6557. ) then
  6558. begin
  6559. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6560. taicpu(p).opcode := A_SUB;
  6561. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6562. end
  6563. else
  6564. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6565. RemoveInstruction(hp1);
  6566. end;
  6567. end
  6568. else
  6569. begin
  6570. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6571. TransferUsedRegs(TmpUsedRegs);
  6572. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6573. hp2 := p;
  6574. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6575. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6576. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6577. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6578. begin
  6579. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6580. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6581. Asml.Remove(p);
  6582. Asml.InsertAfter(p, hp1);
  6583. p := hp1;
  6584. Result := True;
  6585. Exit;
  6586. end;
  6587. end;
  6588. end;
  6589. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6590. { * change "sub/add const1, reg" or "dec reg" followed by
  6591. "sub const2, reg" to one "sub ..., reg" }
  6592. {$ifdef i386}
  6593. if (taicpu(p).oper[0]^.val = 2) and
  6594. (ActiveReg = NR_ESP) and
  6595. { Don't do the sub/push optimization if the sub }
  6596. { comes from setting up the stack frame (JM) }
  6597. (not(GetLastInstruction(p,hp1)) or
  6598. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6599. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6600. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6601. begin
  6602. hp1 := tai(p.next);
  6603. while Assigned(hp1) and
  6604. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6605. not RegReadByInstruction(NR_ESP,hp1) and
  6606. not RegModifiedByInstruction(NR_ESP,hp1) do
  6607. hp1 := tai(hp1.next);
  6608. if Assigned(hp1) and
  6609. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6610. begin
  6611. taicpu(hp1).changeopsize(S_L);
  6612. if taicpu(hp1).oper[0]^.typ=top_reg then
  6613. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6614. hp1 := tai(p.next);
  6615. RemoveCurrentp(p, hp1);
  6616. Result:=true;
  6617. exit;
  6618. end;
  6619. end;
  6620. {$endif i386}
  6621. if DoArithCombineOpt(p) then
  6622. Result:=true;
  6623. end;
  6624. end;
  6625. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6626. var
  6627. TmpBool1,TmpBool2 : Boolean;
  6628. tmpref : treference;
  6629. hp1,hp2: tai;
  6630. mask, shiftval: tcgint;
  6631. begin
  6632. Result:=false;
  6633. { All these optimisations work on "shl/sal const,%reg" }
  6634. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6635. Exit;
  6636. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6637. (taicpu(p).oper[0]^.val <= 3) then
  6638. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6639. begin
  6640. { should we check the next instruction? }
  6641. TmpBool1 := True;
  6642. { have we found an add/sub which could be
  6643. integrated in the lea? }
  6644. TmpBool2 := False;
  6645. reference_reset(tmpref,2,[]);
  6646. TmpRef.index := taicpu(p).oper[1]^.reg;
  6647. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6648. while TmpBool1 and
  6649. GetNextInstruction(p, hp1) and
  6650. (tai(hp1).typ = ait_instruction) and
  6651. ((((taicpu(hp1).opcode = A_ADD) or
  6652. (taicpu(hp1).opcode = A_SUB)) and
  6653. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6654. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6655. (((taicpu(hp1).opcode = A_INC) or
  6656. (taicpu(hp1).opcode = A_DEC)) and
  6657. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6658. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6659. ((taicpu(hp1).opcode = A_LEA) and
  6660. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6661. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6662. (not GetNextInstruction(hp1,hp2) or
  6663. not instrReadsFlags(hp2)) Do
  6664. begin
  6665. TmpBool1 := False;
  6666. if taicpu(hp1).opcode=A_LEA then
  6667. begin
  6668. if (TmpRef.base = NR_NO) and
  6669. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6670. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6671. { Segment register isn't a concern here }
  6672. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6673. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6674. begin
  6675. TmpBool1 := True;
  6676. TmpBool2 := True;
  6677. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6678. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6679. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6680. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6681. RemoveInstruction(hp1);
  6682. end
  6683. end
  6684. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6685. begin
  6686. TmpBool1 := True;
  6687. TmpBool2 := True;
  6688. case taicpu(hp1).opcode of
  6689. A_ADD:
  6690. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6691. A_SUB:
  6692. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6693. else
  6694. internalerror(2019050536);
  6695. end;
  6696. RemoveInstruction(hp1);
  6697. end
  6698. else
  6699. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6700. (((taicpu(hp1).opcode = A_ADD) and
  6701. (TmpRef.base = NR_NO)) or
  6702. (taicpu(hp1).opcode = A_INC) or
  6703. (taicpu(hp1).opcode = A_DEC)) then
  6704. begin
  6705. TmpBool1 := True;
  6706. TmpBool2 := True;
  6707. case taicpu(hp1).opcode of
  6708. A_ADD:
  6709. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6710. A_INC:
  6711. inc(TmpRef.offset);
  6712. A_DEC:
  6713. dec(TmpRef.offset);
  6714. else
  6715. internalerror(2019050535);
  6716. end;
  6717. RemoveInstruction(hp1);
  6718. end;
  6719. end;
  6720. if TmpBool2
  6721. {$ifndef x86_64}
  6722. or
  6723. ((current_settings.optimizecputype < cpu_Pentium2) and
  6724. (taicpu(p).oper[0]^.val <= 3) and
  6725. not(cs_opt_size in current_settings.optimizerswitches))
  6726. {$endif x86_64}
  6727. then
  6728. begin
  6729. if not(TmpBool2) and
  6730. (taicpu(p).oper[0]^.val=1) then
  6731. begin
  6732. taicpu(p).opcode := A_ADD;
  6733. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6734. end
  6735. else
  6736. begin
  6737. taicpu(p).opcode := A_LEA;
  6738. taicpu(p).loadref(0, TmpRef);
  6739. end;
  6740. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6741. Result := True;
  6742. end;
  6743. end
  6744. {$ifndef x86_64}
  6745. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6746. begin
  6747. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6748. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6749. (unlike shl, which is only Tairable in the U pipe) }
  6750. if taicpu(p).oper[0]^.val=1 then
  6751. begin
  6752. taicpu(p).opcode := A_ADD;
  6753. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6754. Result := True;
  6755. end
  6756. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6757. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6758. else if (taicpu(p).opsize = S_L) and
  6759. (taicpu(p).oper[0]^.val<= 3) then
  6760. begin
  6761. reference_reset(tmpref,2,[]);
  6762. TmpRef.index := taicpu(p).oper[1]^.reg;
  6763. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6764. taicpu(p).opcode := A_LEA;
  6765. taicpu(p).loadref(0, TmpRef);
  6766. Result := True;
  6767. end;
  6768. end
  6769. {$endif x86_64}
  6770. else if
  6771. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6772. (
  6773. (
  6774. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6775. SetAndTest(hp1, hp2)
  6776. {$ifdef x86_64}
  6777. ) or
  6778. (
  6779. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6780. GetNextInstruction(hp1, hp2) and
  6781. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6782. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6783. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6784. {$endif x86_64}
  6785. )
  6786. ) and
  6787. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6788. begin
  6789. { Change:
  6790. shl x, %reg1
  6791. mov -(1<<x), %reg2
  6792. and %reg2, %reg1
  6793. Or:
  6794. shl x, %reg1
  6795. and -(1<<x), %reg1
  6796. To just:
  6797. shl x, %reg1
  6798. Since the and operation only zeroes bits that are already zero from the shl operation
  6799. }
  6800. case taicpu(p).oper[0]^.val of
  6801. 8:
  6802. mask:=$FFFFFFFFFFFFFF00;
  6803. 16:
  6804. mask:=$FFFFFFFFFFFF0000;
  6805. 32:
  6806. mask:=$FFFFFFFF00000000;
  6807. 63:
  6808. { Constant pre-calculated to prevent overflow errors with Int64 }
  6809. mask:=$8000000000000000;
  6810. else
  6811. begin
  6812. if taicpu(p).oper[0]^.val >= 64 then
  6813. { Shouldn't happen realistically, since the register
  6814. is guaranteed to be set to zero at this point }
  6815. mask := 0
  6816. else
  6817. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6818. end;
  6819. end;
  6820. if taicpu(hp1).oper[0]^.val = mask then
  6821. begin
  6822. { Everything checks out, perform the optimisation, as long as
  6823. the FLAGS register isn't being used}
  6824. TransferUsedRegs(TmpUsedRegs);
  6825. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6826. {$ifdef x86_64}
  6827. if (hp1 <> hp2) then
  6828. begin
  6829. { "shl/mov/and" version }
  6830. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6831. { Don't do the optimisation if the FLAGS register is in use }
  6832. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6833. begin
  6834. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6835. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6836. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6837. begin
  6838. RemoveInstruction(hp1);
  6839. Result := True;
  6840. end;
  6841. { Only set Result to True if the 'mov' instruction was removed }
  6842. RemoveInstruction(hp2);
  6843. end;
  6844. end
  6845. else
  6846. {$endif x86_64}
  6847. begin
  6848. { "shl/and" version }
  6849. { Don't do the optimisation if the FLAGS register is in use }
  6850. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6851. begin
  6852. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6853. RemoveInstruction(hp1);
  6854. Result := True;
  6855. end;
  6856. end;
  6857. Exit;
  6858. end
  6859. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6860. begin
  6861. { Even if the mask doesn't allow for its removal, we might be
  6862. able to optimise the mask for the "shl/and" version, which
  6863. may permit other peephole optimisations }
  6864. {$ifdef DEBUG_AOPTCPU}
  6865. mask := taicpu(hp1).oper[0]^.val and mask;
  6866. if taicpu(hp1).oper[0]^.val <> mask then
  6867. begin
  6868. DebugMsg(
  6869. SPeepholeOptimization +
  6870. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6871. ' to $' + debug_tostr(mask) +
  6872. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6873. taicpu(hp1).oper[0]^.val := mask;
  6874. end;
  6875. {$else DEBUG_AOPTCPU}
  6876. { If debugging is off, just set the operand even if it's the same }
  6877. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6878. {$endif DEBUG_AOPTCPU}
  6879. end;
  6880. end;
  6881. {
  6882. change
  6883. shl/sal const,reg
  6884. <op> ...(...,reg,1),...
  6885. into
  6886. <op> ...(...,reg,1 shl const),...
  6887. if const in 1..3
  6888. }
  6889. if MatchOpType(taicpu(p), top_const, top_reg) and
  6890. (taicpu(p).oper[0]^.val in [1..3]) and
  6891. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6892. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6893. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6894. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6895. MatchOpType(taicpu(hp1),top_ref))
  6896. ) and
  6897. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6898. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6899. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6900. begin
  6901. TransferUsedRegs(TmpUsedRegs);
  6902. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6903. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6904. begin
  6905. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6906. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6907. RemoveCurrentP(p);
  6908. Result:=true;
  6909. exit;
  6910. end;
  6911. end;
  6912. if MatchOpType(taicpu(p), top_const, top_reg) and
  6913. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6914. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6915. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6916. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6917. begin
  6918. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6919. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6920. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6921. {$ifdef x86_64}
  6922. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6923. {$endif x86_64}
  6924. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6925. begin
  6926. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6927. taicpu(hp1).opcode:=A_MOV;
  6928. taicpu(hp1).oper[0]^.val:=0;
  6929. end
  6930. else
  6931. begin
  6932. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6933. taicpu(hp1).oper[0]^.val:=shiftval;
  6934. end;
  6935. RemoveCurrentP(p);
  6936. Result:=true;
  6937. exit;
  6938. end;
  6939. end;
  6940. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6941. begin
  6942. case shr_size of
  6943. S_B:
  6944. { No valid combinations }
  6945. Result := False;
  6946. S_W:
  6947. Result := (Shift >= 8) and (movz_size = S_BW);
  6948. S_L:
  6949. Result :=
  6950. (Shift >= 24) { Any opsize is valid for this shift } or
  6951. ((Shift >= 16) and (movz_size = S_WL));
  6952. {$ifdef x86_64}
  6953. S_Q:
  6954. Result :=
  6955. (Shift >= 56) { Any opsize is valid for this shift } or
  6956. ((Shift >= 48) and (movz_size = S_WL));
  6957. {$endif x86_64}
  6958. else
  6959. InternalError(2022081510);
  6960. end;
  6961. end;
  6962. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6963. var
  6964. hp1, hp2: tai;
  6965. Shift: TCGInt;
  6966. LimitSize: Topsize;
  6967. DoNotMerge: Boolean;
  6968. begin
  6969. Result := False;
  6970. { All these optimisations work on "shr const,%reg" }
  6971. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6972. Exit;
  6973. DoNotMerge := False;
  6974. Shift := taicpu(p).oper[0]^.val;
  6975. LimitSize := taicpu(p).opsize;
  6976. hp1 := p;
  6977. repeat
  6978. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6979. Exit;
  6980. case taicpu(hp1).opcode of
  6981. A_TEST, A_CMP, A_Jcc:
  6982. { Skip over conditional jumps and relevant comparisons }
  6983. Continue;
  6984. A_MOVZX:
  6985. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6986. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6987. begin
  6988. { Since the original register is being read as is, subsequent
  6989. SHRs must not be merged at this point }
  6990. DoNotMerge := True;
  6991. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6992. begin
  6993. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6994. begin
  6995. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6996. taicpu(hp1).opcode := A_MOV;
  6997. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6998. case taicpu(hp1).opsize of
  6999. S_BW:
  7000. taicpu(hp1).opsize := S_W;
  7001. S_BL, S_WL:
  7002. taicpu(hp1).opsize := S_L;
  7003. else
  7004. InternalError(2022081503);
  7005. end;
  7006. { p itself hasn't changed, so no need to set Result to True }
  7007. Include(OptsToCheck, aoc_ForceNewIteration);
  7008. { See if there's anything afterwards that can be
  7009. optimised, since the input register hasn't changed }
  7010. Continue;
  7011. end;
  7012. { NOTE: If the MOVZX instruction reads and writes the same
  7013. register, defer this to the post-peephole optimisation stage }
  7014. Exit;
  7015. end;
  7016. end;
  7017. A_SHL, A_SAL, A_SHR:
  7018. if (taicpu(hp1).opsize <= LimitSize) and
  7019. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7020. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  7021. begin
  7022. { Make sure the sizes don't exceed the register size limit
  7023. (measured by the shift value falling below the limit) }
  7024. if taicpu(hp1).opsize < LimitSize then
  7025. LimitSize := taicpu(hp1).opsize;
  7026. if taicpu(hp1).opcode = A_SHR then
  7027. Inc(Shift, taicpu(hp1).oper[0]^.val)
  7028. else
  7029. begin
  7030. Dec(Shift, taicpu(hp1).oper[0]^.val);
  7031. DoNotMerge := True;
  7032. end;
  7033. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  7034. Exit;
  7035. { Since we've established that the combined shift is within
  7036. limits, we can actually combine the adjacent SHR
  7037. instructions even if they're different sizes }
  7038. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  7039. begin
  7040. hp2 := tai(hp1.Previous);
  7041. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  7042. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  7043. RemoveInstruction(hp1);
  7044. hp1 := hp2;
  7045. { Though p has changed, only the constant has, and its
  7046. effects can still be detected on the next iteration of
  7047. the repeat..until loop }
  7048. Include(OptsToCheck, aoc_ForceNewIteration);
  7049. end;
  7050. { Move onto the next instruction }
  7051. Continue;
  7052. end;
  7053. else
  7054. ;
  7055. end;
  7056. Break;
  7057. until False;
  7058. end;
  7059. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7060. var
  7061. CurrentRef: TReference;
  7062. FullReg: TRegister;
  7063. hp1, hp2: tai;
  7064. begin
  7065. Result := False;
  7066. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7067. Exit;
  7068. { We assume you've checked if the operand is actually a reference by
  7069. this point. If it isn't, you'll most likely get an access violation }
  7070. CurrentRef := first_mov.oper[1]^.ref^;
  7071. { Memory must be aligned }
  7072. if (CurrentRef.offset mod 4) <> 0 then
  7073. Exit;
  7074. Inc(CurrentRef.offset);
  7075. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7076. if MatchOperand(second_mov.oper[0]^, 0) and
  7077. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7078. GetNextInstruction(second_mov, hp1) and
  7079. (hp1.typ = ait_instruction) and
  7080. (taicpu(hp1).opcode = A_MOV) and
  7081. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7082. (taicpu(hp1).oper[0]^.val = 0) then
  7083. begin
  7084. Inc(CurrentRef.offset);
  7085. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7086. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7087. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7088. begin
  7089. case taicpu(hp1).opsize of
  7090. S_B:
  7091. if GetNextInstruction(hp1, hp2) and
  7092. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7093. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7094. (taicpu(hp2).oper[0]^.val = 0) then
  7095. begin
  7096. Inc(CurrentRef.offset);
  7097. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7098. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7099. (taicpu(hp2).opsize = S_B) then
  7100. begin
  7101. RemoveInstruction(hp1);
  7102. RemoveInstruction(hp2);
  7103. first_mov.opsize := S_L;
  7104. if first_mov.oper[0]^.typ = top_reg then
  7105. begin
  7106. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7107. { Reuse second_mov as a MOVZX instruction }
  7108. second_mov.opcode := A_MOVZX;
  7109. second_mov.opsize := S_BL;
  7110. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7111. second_mov.loadreg(1, FullReg);
  7112. first_mov.oper[0]^.reg := FullReg;
  7113. asml.Remove(second_mov);
  7114. asml.InsertBefore(second_mov, first_mov);
  7115. end
  7116. else
  7117. { It's a value }
  7118. begin
  7119. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7120. RemoveInstruction(second_mov);
  7121. end;
  7122. Result := True;
  7123. Exit;
  7124. end;
  7125. end;
  7126. S_W:
  7127. begin
  7128. RemoveInstruction(hp1);
  7129. first_mov.opsize := S_L;
  7130. if first_mov.oper[0]^.typ = top_reg then
  7131. begin
  7132. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7133. { Reuse second_mov as a MOVZX instruction }
  7134. second_mov.opcode := A_MOVZX;
  7135. second_mov.opsize := S_BL;
  7136. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7137. second_mov.loadreg(1, FullReg);
  7138. first_mov.oper[0]^.reg := FullReg;
  7139. asml.Remove(second_mov);
  7140. asml.InsertBefore(second_mov, first_mov);
  7141. end
  7142. else
  7143. { It's a value }
  7144. begin
  7145. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7146. RemoveInstruction(second_mov);
  7147. end;
  7148. Result := True;
  7149. Exit;
  7150. end;
  7151. else
  7152. ;
  7153. end;
  7154. end;
  7155. end;
  7156. end;
  7157. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7158. { returns true if a "continue" should be done after this optimization }
  7159. var
  7160. hp1, hp2, hp3: tai;
  7161. begin
  7162. Result := false;
  7163. hp3 := nil;
  7164. if MatchOpType(taicpu(p),top_ref) and
  7165. GetNextInstruction(p, hp1) and
  7166. (hp1.typ = ait_instruction) and
  7167. (((taicpu(hp1).opcode = A_FLD) and
  7168. (taicpu(p).opcode = A_FSTP)) or
  7169. ((taicpu(p).opcode = A_FISTP) and
  7170. (taicpu(hp1).opcode = A_FILD))) and
  7171. MatchOpType(taicpu(hp1),top_ref) and
  7172. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7173. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7174. begin
  7175. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7176. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7177. GetNextInstruction(hp1, hp2) and
  7178. (((hp2.typ = ait_instruction) and
  7179. IsExitCode(hp2) and
  7180. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7181. not(assigned(current_procinfo.procdef.funcretsym) and
  7182. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7183. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7184. { fstp <temp>
  7185. fld <temp>
  7186. <dealloc> <temp>
  7187. }
  7188. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7189. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7190. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7191. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7192. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7193. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7194. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7195. )
  7196. )
  7197. ) then
  7198. begin
  7199. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7200. RemoveInstruction(hp1);
  7201. RemoveCurrentP(p, hp2);
  7202. { first case: exit code }
  7203. if hp2.typ = ait_instruction then
  7204. RemoveLastDeallocForFuncRes(p);
  7205. Result := true;
  7206. end
  7207. else
  7208. { we can do this only in fast math mode as fstp is rounding ...
  7209. ... still disabled as it breaks the compiler and/or rtl }
  7210. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7211. { ... or if another fstp equal to the first one follows }
  7212. GetNextInstruction(hp1,hp2) and
  7213. (hp2.typ = ait_instruction) and
  7214. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7215. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7216. begin
  7217. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7218. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7219. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7220. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7221. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7222. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7223. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7224. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7225. ) then
  7226. begin
  7227. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7228. RemoveCurrentP(p,hp2);
  7229. RemoveInstruction(hp1);
  7230. Result := true;
  7231. end
  7232. else if { fst can't store an extended/comp value }
  7233. (taicpu(p).opsize <> S_FX) and
  7234. (taicpu(p).opsize <> S_IQ) then
  7235. begin
  7236. if (taicpu(p).opcode = A_FSTP) then
  7237. taicpu(p).opcode := A_FST
  7238. else
  7239. taicpu(p).opcode := A_FIST;
  7240. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7241. RemoveInstruction(hp1);
  7242. Result := true;
  7243. end;
  7244. end;
  7245. end;
  7246. end;
  7247. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7248. var
  7249. hp1, hp2, hp3: tai;
  7250. begin
  7251. result:=false;
  7252. if MatchOpType(taicpu(p),top_reg) and
  7253. GetNextInstruction(p, hp1) and
  7254. (hp1.typ = Ait_Instruction) and
  7255. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7256. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7257. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7258. { change to
  7259. fld reg fxxx reg,st
  7260. fxxxp st, st1 (hp1)
  7261. Remark: non commutative operations must be reversed!
  7262. }
  7263. begin
  7264. case taicpu(hp1).opcode Of
  7265. A_FMULP,A_FADDP,
  7266. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7267. begin
  7268. case taicpu(hp1).opcode Of
  7269. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7270. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7271. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7272. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7273. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7274. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7275. else
  7276. internalerror(2019050534);
  7277. end;
  7278. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7279. taicpu(hp1).oper[1]^.reg := NR_ST;
  7280. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7281. RemoveCurrentP(p, hp1);
  7282. Result:=true;
  7283. exit;
  7284. end;
  7285. else
  7286. ;
  7287. end;
  7288. end
  7289. else
  7290. if MatchOpType(taicpu(p),top_ref) and
  7291. GetNextInstruction(p, hp2) and
  7292. (hp2.typ = Ait_Instruction) and
  7293. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7294. (taicpu(p).opsize in [S_FS, S_FL]) and
  7295. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7296. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7297. if GetLastInstruction(p, hp1) and
  7298. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7299. MatchOpType(taicpu(hp1),top_ref) and
  7300. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7301. if ((taicpu(hp2).opcode = A_FMULP) or
  7302. (taicpu(hp2).opcode = A_FADDP)) then
  7303. { change to
  7304. fld/fst mem1 (hp1) fld/fst mem1
  7305. fld mem1 (p) fadd/
  7306. faddp/ fmul st, st
  7307. fmulp st, st1 (hp2) }
  7308. begin
  7309. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7310. RemoveCurrentP(p, hp1);
  7311. if (taicpu(hp2).opcode = A_FADDP) then
  7312. taicpu(hp2).opcode := A_FADD
  7313. else
  7314. taicpu(hp2).opcode := A_FMUL;
  7315. taicpu(hp2).oper[1]^.reg := NR_ST;
  7316. end
  7317. else
  7318. { change to
  7319. fld/fst mem1 (hp1) fld/fst mem1
  7320. fld mem1 (p) fld st
  7321. }
  7322. begin
  7323. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7324. taicpu(p).changeopsize(S_FL);
  7325. taicpu(p).loadreg(0,NR_ST);
  7326. end
  7327. else
  7328. begin
  7329. case taicpu(hp2).opcode Of
  7330. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7331. { change to
  7332. fld/fst mem1 (hp1) fld/fst mem1
  7333. fld mem2 (p) fxxx mem2
  7334. fxxxp st, st1 (hp2) }
  7335. begin
  7336. case taicpu(hp2).opcode Of
  7337. A_FADDP: taicpu(p).opcode := A_FADD;
  7338. A_FMULP: taicpu(p).opcode := A_FMUL;
  7339. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7340. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7341. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7342. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7343. else
  7344. internalerror(2019050533);
  7345. end;
  7346. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7347. RemoveInstruction(hp2);
  7348. end
  7349. else
  7350. ;
  7351. end
  7352. end
  7353. end;
  7354. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7355. begin
  7356. Result := condition_in(cond1, cond2) or
  7357. { Not strictly subsets due to the actual flags checked, but because we're
  7358. comparing integers, E is a subset of AE and GE and their aliases }
  7359. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7360. end;
  7361. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7362. var
  7363. v: TCGInt;
  7364. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7365. FirstMatch, TempBool: Boolean;
  7366. NewReg: TRegister;
  7367. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7368. begin
  7369. Result:=false;
  7370. { All these optimisations need a next instruction }
  7371. if not GetNextInstruction(p, hp1) then
  7372. Exit;
  7373. true_hp1 := hp1;
  7374. { Search for:
  7375. cmp ###,###
  7376. j(c1) @lbl1
  7377. ...
  7378. @lbl:
  7379. cmp ###,### (same comparison as above)
  7380. j(c2) @lbl2
  7381. If c1 is a subset of c2, change to:
  7382. cmp ###,###
  7383. j(c1) @lbl2
  7384. (@lbl1 may become a dead label as a result)
  7385. }
  7386. { Also handle cases where there are multiple jumps in a row }
  7387. p_jump := hp1;
  7388. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7389. begin
  7390. Prefetch(p_jump.Next);
  7391. if IsJumpToLabel(taicpu(p_jump)) then
  7392. begin
  7393. { Do jump optimisations first in case the condition becomes
  7394. unnecessary }
  7395. TempBool := True;
  7396. if DoJumpOptimizations(p_jump, TempBool) or
  7397. not TempBool then
  7398. begin
  7399. if Assigned(p_jump) then
  7400. begin
  7401. { CollapseZeroDistJump will be set to the label or an align
  7402. before it after the jump if it optimises, whether or not
  7403. the label is live or dead }
  7404. if (p_jump.typ = ait_align) or
  7405. (
  7406. (p_jump.typ = ait_label) and
  7407. not (tai_label(p_jump).labsym.is_used)
  7408. ) then
  7409. GetNextInstruction(p_jump, p_jump);
  7410. end;
  7411. TransferUsedRegs(TmpUsedRegs);
  7412. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7413. if not Assigned(p_jump) or
  7414. (
  7415. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7416. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7417. ) then
  7418. begin
  7419. { No more conditional jumps; conditional statement is no longer required }
  7420. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7421. RemoveCurrentP(p);
  7422. Result := True;
  7423. Exit;
  7424. end;
  7425. hp1 := p_jump;
  7426. Include(OptsToCheck, aoc_ForceNewIteration);
  7427. Continue;
  7428. end;
  7429. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7430. if GetNextInstruction(p_jump, hp2) and
  7431. (
  7432. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7433. not TempBool
  7434. ) then
  7435. begin
  7436. hp1 := p_jump;
  7437. Include(OptsToCheck, aoc_ForceNewIteration);
  7438. Continue;
  7439. end;
  7440. p_label := nil;
  7441. if Assigned(JumpLabel) then
  7442. p_label := getlabelwithsym(JumpLabel);
  7443. if Assigned(p_label) and
  7444. GetNextInstruction(p_label, p_dist) and
  7445. MatchInstruction(p_dist, A_CMP, []) and
  7446. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7447. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7448. GetNextInstruction(p_dist, hp1_dist) and
  7449. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7450. begin
  7451. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7452. if JumpLabel = JumpLabel_dist then
  7453. { This is an infinite loop }
  7454. Exit;
  7455. { Best optimisation when the first condition is a subset (or equal) of the second }
  7456. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7457. begin
  7458. { Any registers used here will already be allocated }
  7459. if Assigned(JumpLabel) then
  7460. JumpLabel.DecRefs;
  7461. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7462. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7463. Include(OptsToCheck, aoc_ForceNewIteration);
  7464. { Don't exit yet. Since p and p_jump haven't actually been
  7465. removed, we can check for more on this iteration }
  7466. end
  7467. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7468. GetNextInstruction(hp1_dist, hp1_label) and
  7469. (hp1_label.typ = ait_label) then
  7470. begin
  7471. JumpLabel_far := tai_label(hp1_label).labsym;
  7472. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7473. { This is an infinite loop }
  7474. Exit;
  7475. if Assigned(JumpLabel_far) then
  7476. begin
  7477. { In this situation, if the first jump branches, the second one will never,
  7478. branch so change the destination label to after the second jump }
  7479. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7480. if Assigned(JumpLabel) then
  7481. JumpLabel.DecRefs;
  7482. JumpLabel_far.IncRefs;
  7483. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7484. Result := True;
  7485. { Don't exit yet. Since p and p_jump haven't actually been
  7486. removed, we can check for more on this iteration }
  7487. Continue;
  7488. end;
  7489. end;
  7490. end;
  7491. end;
  7492. { Search for:
  7493. cmp ###,###
  7494. j(c1) @lbl1
  7495. cmp ###,### (same as first)
  7496. Remove second cmp
  7497. }
  7498. if GetNextInstruction(p_jump, hp2) and
  7499. (
  7500. (
  7501. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7502. (
  7503. (
  7504. MatchOpType(taicpu(p), top_const, top_reg) and
  7505. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7506. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7507. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7508. ) or (
  7509. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7510. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7511. )
  7512. )
  7513. ) or (
  7514. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7515. MatchOperand(taicpu(p).oper[0]^, 0) and
  7516. (taicpu(p).oper[1]^.typ = top_reg) and
  7517. MatchInstruction(hp2, A_TEST, []) and
  7518. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7519. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7520. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7521. )
  7522. ) then
  7523. begin
  7524. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7525. TransferUsedRegs(TmpUsedRegs);
  7526. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7527. RemoveInstruction(hp2);
  7528. Result := True;
  7529. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7530. end
  7531. else
  7532. begin
  7533. { hp2 is the next instruction, so save time and just set p_jump
  7534. to it instead of calling GetNextInstruction below }
  7535. p_jump := hp2;
  7536. Continue;
  7537. end;
  7538. GetNextInstruction(p_jump, p_jump);
  7539. end;
  7540. if (
  7541. { Don't call GetNextInstruction again if we already have it }
  7542. (true_hp1 = p_jump) or
  7543. GetNextInstruction(p, hp1)
  7544. ) and
  7545. MatchInstruction(hp1, A_Jcc, []) and
  7546. IsJumpToLabel(taicpu(hp1)) and
  7547. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7548. GetNextInstruction(hp1, hp2) then
  7549. begin
  7550. {
  7551. cmp x, y (or "cmp y, x")
  7552. je @lbl
  7553. mov x, y
  7554. @lbl:
  7555. (x and y can be constants, registers or references)
  7556. Change to:
  7557. mov x, y (x and y will always be equal in the end)
  7558. @lbl: (may beceome a dead label)
  7559. Also:
  7560. cmp x, y (or "cmp y, x")
  7561. jne @lbl
  7562. mov x, y
  7563. @lbl:
  7564. (x and y can be constants, registers or references)
  7565. Change to:
  7566. Absolutely nothing! (Except @lbl if it's still live)
  7567. }
  7568. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7569. (
  7570. (
  7571. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7572. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7573. ) or (
  7574. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7575. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7576. )
  7577. ) and
  7578. GetNextInstruction(hp2, hp1_label) and
  7579. (hp1_label.typ = ait_label) and
  7580. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7581. begin
  7582. tai_label(hp1_label).labsym.DecRefs;
  7583. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7584. begin
  7585. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7586. RemoveInstruction(hp2);
  7587. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7588. end
  7589. else
  7590. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7591. RemoveInstruction(hp1);
  7592. RemoveCurrentp(p, hp2);
  7593. Result := True;
  7594. Exit;
  7595. end;
  7596. {
  7597. Try to optimise the following:
  7598. cmp $x,### ($x and $y can be registers or constants)
  7599. je @lbl1 (only reference)
  7600. cmp $y,### (### are identical)
  7601. @Lbl:
  7602. sete %reg1
  7603. Change to:
  7604. cmp $x,###
  7605. sete %reg2 (allocate new %reg2)
  7606. cmp $y,###
  7607. sete %reg1
  7608. orb %reg2,%reg1
  7609. (dealloc %reg2)
  7610. This adds an instruction (so don't perform under -Os), but it removes
  7611. a conditional branch.
  7612. }
  7613. if not (cs_opt_size in current_settings.optimizerswitches) and
  7614. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7615. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7616. { The first operand of CMP instructions can only be a register or
  7617. immediate anyway, so no need to check }
  7618. GetNextInstruction(hp2, p_label) and
  7619. (p_label.typ = ait_label) and
  7620. (tai_label(p_label).labsym.getrefs = 1) and
  7621. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7622. GetNextInstruction(p_label, p_dist) and
  7623. MatchInstruction(p_dist, A_SETcc, []) and
  7624. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7625. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7626. begin
  7627. TransferUsedRegs(TmpUsedRegs);
  7628. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7629. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7630. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7631. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7632. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7633. { Get the instruction after the SETcc instruction so we can
  7634. allocate a new register over the entire range }
  7635. GetNextInstruction(p_dist, hp1_dist) then
  7636. begin
  7637. { Register can appear in p if it's not used afterwards, so only
  7638. allocate between hp1 and hp1_dist }
  7639. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7640. if NewReg <> NR_NO then
  7641. begin
  7642. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7643. { Change the jump instruction into a SETcc instruction }
  7644. taicpu(hp1).opcode := A_SETcc;
  7645. taicpu(hp1).opsize := S_B;
  7646. taicpu(hp1).loadreg(0, NewReg);
  7647. { This is now a dead label }
  7648. tai_label(p_label).labsym.decrefs;
  7649. { Prefer adding before the next instruction so the FLAGS
  7650. register is deallicated first }
  7651. AsmL.InsertBefore(
  7652. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7653. hp1_dist
  7654. );
  7655. Result := True;
  7656. { Don't exit yet, as p wasn't changed and hp1, while
  7657. modified, is still intact and might be optimised by the
  7658. SETcc optimisation below }
  7659. end;
  7660. end;
  7661. end;
  7662. end;
  7663. if (taicpu(p).oper[0]^.typ = top_const) and
  7664. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7665. begin
  7666. if (taicpu(p).oper[0]^.val = 0) and
  7667. (taicpu(p).oper[1]^.typ = top_reg) then
  7668. begin
  7669. hp2 := p;
  7670. FirstMatch := True;
  7671. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7672. anything meaningful once it's converted to "test %reg,%reg";
  7673. additionally, some jumps will always (or never) branch, so
  7674. evaluate every jump immediately following the
  7675. comparison, optimising the conditions if possible.
  7676. Similarly with SETcc... those that are always set to 0 or 1
  7677. are changed to MOV instructions }
  7678. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7679. (
  7680. GetNextInstruction(hp2, hp1) and
  7681. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7682. ) do
  7683. begin
  7684. Prefetch(hp1.Next);
  7685. FirstMatch := False;
  7686. case taicpu(hp1).condition of
  7687. C_B, C_C, C_NAE, C_O:
  7688. { For B/NAE:
  7689. Will never branch since an unsigned integer can never be below zero
  7690. For C/O:
  7691. Result cannot overflow because 0 is being subtracted
  7692. }
  7693. begin
  7694. if taicpu(hp1).opcode = A_Jcc then
  7695. begin
  7696. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7697. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7698. RemoveInstruction(hp1);
  7699. { Since hp1 was deleted, hp2 must not be updated }
  7700. Continue;
  7701. end
  7702. else
  7703. begin
  7704. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7705. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7706. taicpu(hp1).opcode := A_MOV;
  7707. taicpu(hp1).ops := 2;
  7708. taicpu(hp1).condition := C_None;
  7709. taicpu(hp1).opsize := S_B;
  7710. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7711. taicpu(hp1).loadconst(0, 0);
  7712. end;
  7713. end;
  7714. C_BE, C_NA:
  7715. begin
  7716. { Will only branch if equal to zero }
  7717. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7718. taicpu(hp1).condition := C_E;
  7719. end;
  7720. C_A, C_NBE:
  7721. begin
  7722. { Will only branch if not equal to zero }
  7723. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7724. taicpu(hp1).condition := C_NE;
  7725. end;
  7726. C_AE, C_NB, C_NC, C_NO:
  7727. begin
  7728. { Will always branch }
  7729. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7730. if taicpu(hp1).opcode = A_Jcc then
  7731. begin
  7732. MakeUnconditional(taicpu(hp1));
  7733. { Any jumps/set that follow will now be dead code }
  7734. RemoveDeadCodeAfterJump(taicpu(hp1));
  7735. Break;
  7736. end
  7737. else
  7738. begin
  7739. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7740. taicpu(hp1).opcode := A_MOV;
  7741. taicpu(hp1).ops := 2;
  7742. taicpu(hp1).condition := C_None;
  7743. taicpu(hp1).opsize := S_B;
  7744. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7745. taicpu(hp1).loadconst(0, 1);
  7746. end;
  7747. end;
  7748. C_None:
  7749. InternalError(2020012201);
  7750. C_P, C_PE, C_NP, C_PO:
  7751. { We can't handle parity checks and they should never be generated
  7752. after a general-purpose CMP (it's used in some floating-point
  7753. comparisons that don't use CMP) }
  7754. InternalError(2020012202);
  7755. else
  7756. { Zero/Equality, Sign, their complements and all of the
  7757. signed comparisons do not need to be converted };
  7758. end;
  7759. hp2 := hp1;
  7760. end;
  7761. { Convert the instruction to a TEST }
  7762. taicpu(p).opcode := A_TEST;
  7763. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7764. Result := True;
  7765. Exit;
  7766. end
  7767. else
  7768. begin
  7769. TransferUsedRegs(TmpUsedRegs);
  7770. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7771. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7772. begin
  7773. if (taicpu(p).oper[0]^.val = 1) and
  7774. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7775. begin
  7776. { Convert; To:
  7777. cmp $1,r/m cmp $0,r/m
  7778. jl @lbl jle @lbl
  7779. (Also do inverted conditions)
  7780. }
  7781. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7782. taicpu(p).oper[0]^.val := 0;
  7783. if taicpu(hp1).condition in [C_L, C_NGE] then
  7784. taicpu(hp1).condition := C_LE
  7785. else
  7786. taicpu(hp1).condition := C_NLE;
  7787. { If the instruction is now "cmp $0,%reg", convert it to a
  7788. TEST (and effectively do the work of the "cmp $0,%reg" in
  7789. the block above)
  7790. }
  7791. if (taicpu(p).oper[1]^.typ = top_reg) then
  7792. begin
  7793. taicpu(p).opcode := A_TEST;
  7794. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7795. end;
  7796. Result := True;
  7797. Exit;
  7798. end
  7799. else if (taicpu(p).oper[1]^.typ = top_reg)
  7800. {$ifdef x86_64}
  7801. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7802. {$endif x86_64}
  7803. then
  7804. begin
  7805. { cmp register,$8000 neg register
  7806. je target --> jo target
  7807. .... only if register is deallocated before jump.}
  7808. case Taicpu(p).opsize of
  7809. S_B: v:=$80;
  7810. S_W: v:=$8000;
  7811. S_L: v:=qword($80000000);
  7812. else
  7813. internalerror(2013112905);
  7814. end;
  7815. if (taicpu(p).oper[0]^.val=v) and
  7816. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7817. begin
  7818. TransferUsedRegs(TmpUsedRegs);
  7819. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7820. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7821. begin
  7822. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7823. Taicpu(p).opcode:=A_NEG;
  7824. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7825. Taicpu(p).clearop(1);
  7826. Taicpu(p).ops:=1;
  7827. if Taicpu(hp1).condition=C_E then
  7828. Taicpu(hp1).condition:=C_O
  7829. else
  7830. Taicpu(hp1).condition:=C_NO;
  7831. Result:=true;
  7832. exit;
  7833. end;
  7834. end;
  7835. end;
  7836. end;
  7837. end;
  7838. end;
  7839. if TrySwapMovCmp(p, hp1) then
  7840. begin
  7841. Result := True;
  7842. Exit;
  7843. end;
  7844. end;
  7845. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7846. var
  7847. hp1: tai;
  7848. begin
  7849. {
  7850. remove the second (v)pxor from
  7851. pxor reg,reg
  7852. ...
  7853. pxor reg,reg
  7854. }
  7855. Result:=false;
  7856. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7857. MatchOpType(taicpu(p),top_reg,top_reg) and
  7858. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7859. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7860. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7861. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7862. begin
  7863. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7864. RemoveInstruction(hp1);
  7865. Result:=true;
  7866. Exit;
  7867. end
  7868. {
  7869. replace
  7870. pxor reg1,reg1
  7871. movapd/s reg1,reg2
  7872. dealloc reg1
  7873. by
  7874. pxor reg2,reg2
  7875. }
  7876. else if GetNextInstruction(p,hp1) and
  7877. { we mix single and double opperations here because we assume that the compiler
  7878. generates vmovapd only after double operations and vmovaps only after single operations }
  7879. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7880. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7881. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7882. (taicpu(p).oper[0]^.typ=top_reg) then
  7883. begin
  7884. TransferUsedRegs(TmpUsedRegs);
  7885. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7886. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7887. begin
  7888. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7889. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7890. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7891. RemoveInstruction(hp1);
  7892. result:=true;
  7893. end;
  7894. end;
  7895. end;
  7896. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7897. var
  7898. hp1: tai;
  7899. begin
  7900. {
  7901. remove the second (v)pxor from
  7902. (v)pxor reg,reg
  7903. ...
  7904. (v)pxor reg,reg
  7905. }
  7906. Result:=false;
  7907. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7908. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7909. begin
  7910. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7911. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7912. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7913. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7914. begin
  7915. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7916. RemoveInstruction(hp1);
  7917. Result:=true;
  7918. Exit;
  7919. end;
  7920. {$ifdef x86_64}
  7921. {
  7922. replace
  7923. vpxor reg1,reg1,reg1
  7924. vmov reg,mem
  7925. by
  7926. movq $0,mem
  7927. }
  7928. if GetNextInstruction(p,hp1) and
  7929. MatchInstruction(hp1,A_VMOVSD,[]) and
  7930. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7931. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7932. begin
  7933. TransferUsedRegs(TmpUsedRegs);
  7934. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7935. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7936. begin
  7937. taicpu(hp1).loadconst(0,0);
  7938. taicpu(hp1).opcode:=A_MOV;
  7939. taicpu(hp1).opsize:=S_Q;
  7940. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7941. RemoveCurrentP(p);
  7942. result:=true;
  7943. Exit;
  7944. end;
  7945. end;
  7946. {$endif x86_64}
  7947. end
  7948. {
  7949. replace
  7950. vpxor reg1,reg1,reg2
  7951. by
  7952. vpxor reg2,reg2,reg2
  7953. to avoid unncessary data dependencies
  7954. }
  7955. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7956. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7957. begin
  7958. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7959. { avoid unncessary data dependency }
  7960. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7961. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7962. result:=true;
  7963. exit;
  7964. end;
  7965. Result:=OptPass1VOP(p);
  7966. end;
  7967. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7968. var
  7969. hp1 : tai;
  7970. begin
  7971. result:=false;
  7972. { replace
  7973. IMul const,%mreg1,%mreg2
  7974. Mov %reg2,%mreg3
  7975. dealloc %mreg3
  7976. by
  7977. Imul const,%mreg1,%mreg23
  7978. }
  7979. if (taicpu(p).ops=3) and
  7980. GetNextInstruction(p,hp1) and
  7981. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7982. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7983. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7984. begin
  7985. TransferUsedRegs(TmpUsedRegs);
  7986. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7987. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7988. begin
  7989. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7990. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7991. RemoveInstruction(hp1);
  7992. result:=true;
  7993. end;
  7994. end;
  7995. end;
  7996. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7997. var
  7998. hp1 : tai;
  7999. begin
  8000. result:=false;
  8001. { replace
  8002. IMul %reg0,%reg1,%reg2
  8003. Mov %reg2,%reg3
  8004. dealloc %reg2
  8005. by
  8006. Imul %reg0,%reg1,%reg3
  8007. }
  8008. if GetNextInstruction(p,hp1) and
  8009. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8010. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8011. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8012. begin
  8013. TransferUsedRegs(TmpUsedRegs);
  8014. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8015. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8016. begin
  8017. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8018. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  8019. RemoveInstruction(hp1);
  8020. result:=true;
  8021. end;
  8022. end;
  8023. end;
  8024. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  8025. var
  8026. hp1: tai;
  8027. begin
  8028. Result:=false;
  8029. { get rid of
  8030. (v)cvtss2sd reg0,<reg1,>reg2
  8031. (v)cvtss2sd reg2,<reg2,>reg0
  8032. }
  8033. if GetNextInstruction(p,hp1) and
  8034. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  8035. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  8036. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  8037. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  8038. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  8039. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8040. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8041. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  8042. )
  8043. ) then
  8044. begin
  8045. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8046. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8047. begin
  8048. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8049. RemoveCurrentP(p);
  8050. RemoveInstruction(hp1);
  8051. end
  8052. else
  8053. begin
  8054. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8055. if taicpu(hp1).opcode=A_CVTSD2SS then
  8056. begin
  8057. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8058. taicpu(p).opcode:=A_MOVAPS;
  8059. end
  8060. else
  8061. begin
  8062. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8063. taicpu(p).opcode:=A_VMOVAPS;
  8064. end;
  8065. taicpu(p).ops:=2;
  8066. RemoveInstruction(hp1);
  8067. end;
  8068. Result:=true;
  8069. Exit;
  8070. end;
  8071. end;
  8072. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8073. var
  8074. hp1, hp2, hp3, hp4, hp5: tai;
  8075. ThisReg: TRegister;
  8076. begin
  8077. Result := False;
  8078. if not GetNextInstruction(p,hp1) then
  8079. Exit;
  8080. {
  8081. convert
  8082. j<c> .L1
  8083. mov 1,reg
  8084. jmp .L2
  8085. .L1
  8086. mov 0,reg
  8087. .L2
  8088. into
  8089. mov 0,reg
  8090. set<not(c)> reg
  8091. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8092. would destroy the flag contents
  8093. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8094. executed at the same time as a previous comparison.
  8095. set<not(c)> reg
  8096. movzx reg, reg
  8097. }
  8098. if MatchInstruction(hp1,A_MOV,[]) and
  8099. (taicpu(hp1).oper[0]^.typ = top_const) and
  8100. (
  8101. (
  8102. (taicpu(hp1).oper[1]^.typ = top_reg)
  8103. {$ifdef i386}
  8104. { Under i386, ESI, EDI, EBP and ESP
  8105. don't have an 8-bit representation }
  8106. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8107. {$endif i386}
  8108. ) or (
  8109. {$ifdef i386}
  8110. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8111. {$endif i386}
  8112. (taicpu(hp1).opsize = S_B)
  8113. )
  8114. ) and
  8115. GetNextInstruction(hp1,hp2) and
  8116. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8117. GetNextInstruction(hp2,hp3) and
  8118. FindLabel(tasmlabel(taicpu(p).oper[0]^.ref^.symbol), hp3) and
  8119. GetNextInstruction(hp3,hp4) and
  8120. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8121. (taicpu(hp4).oper[0]^.typ = top_const) and
  8122. (
  8123. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8124. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8125. ) and
  8126. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8127. GetNextInstruction(hp4,hp5) and
  8128. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol), hp5) then
  8129. begin
  8130. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8131. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8132. tai_label(hp3).labsym.DecRefs;
  8133. { If this isn't the only reference to the middle label, we can
  8134. still make a saving - only that the first jump and everything
  8135. that follows will remain. }
  8136. if (tai_label(hp3).labsym.getrefs = 0) then
  8137. begin
  8138. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8139. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8140. else
  8141. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8142. { remove jump, first label and second MOV (also catching any aligns) }
  8143. repeat
  8144. if not GetNextInstruction(hp2, hp3) then
  8145. InternalError(2021040810);
  8146. RemoveInstruction(hp2);
  8147. hp2 := hp3;
  8148. until hp2 = hp5;
  8149. { Don't decrement reference count before the removal loop
  8150. above, otherwise GetNextInstruction won't stop on the
  8151. the label }
  8152. tai_label(hp5).labsym.DecRefs;
  8153. end
  8154. else
  8155. begin
  8156. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8157. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8158. else
  8159. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8160. end;
  8161. taicpu(p).opcode:=A_SETcc;
  8162. taicpu(p).opsize:=S_B;
  8163. taicpu(p).is_jmp:=False;
  8164. if taicpu(hp1).opsize=S_B then
  8165. begin
  8166. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8167. if taicpu(hp1).oper[1]^.typ = top_reg then
  8168. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8169. RemoveInstruction(hp1);
  8170. end
  8171. else
  8172. begin
  8173. { Will be a register because the size can't be S_B otherwise }
  8174. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8175. taicpu(p).loadreg(0, ThisReg);
  8176. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8177. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8178. begin
  8179. case taicpu(hp1).opsize of
  8180. S_W:
  8181. taicpu(hp1).opsize := S_BW;
  8182. S_L:
  8183. taicpu(hp1).opsize := S_BL;
  8184. {$ifdef x86_64}
  8185. S_Q:
  8186. begin
  8187. taicpu(hp1).opsize := S_BL;
  8188. { Change the destination register to 32-bit }
  8189. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8190. end;
  8191. {$endif x86_64}
  8192. else
  8193. InternalError(2021040820);
  8194. end;
  8195. taicpu(hp1).opcode := A_MOVZX;
  8196. taicpu(hp1).loadreg(0, ThisReg);
  8197. end
  8198. else
  8199. begin
  8200. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8201. { hp1 is already a MOV instruction with the correct register }
  8202. taicpu(hp1).loadconst(0, 0);
  8203. { Inserting it right before p will guarantee that the flags are also tracked }
  8204. asml.Remove(hp1);
  8205. asml.InsertBefore(hp1, p);
  8206. end;
  8207. end;
  8208. Result:=true;
  8209. exit;
  8210. end
  8211. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8212. Result := TryJccStcClcOpt(p, hp1)
  8213. else if (hp1.typ = ait_label) then
  8214. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8215. end;
  8216. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8217. var
  8218. hp1, hp2, hp3: tai;
  8219. SourceRef, TargetRef: TReference;
  8220. CurrentReg: TRegister;
  8221. begin
  8222. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8223. if not UseAVX then
  8224. InternalError(2021100501);
  8225. Result := False;
  8226. { Look for the following to simplify:
  8227. vmovdqa/u x(mem1), %xmmreg
  8228. vmovdqa/u %xmmreg, y(mem2)
  8229. vmovdqa/u x+16(mem1), %xmmreg
  8230. vmovdqa/u %xmmreg, y+16(mem2)
  8231. Change to:
  8232. vmovdqa/u x(mem1), %ymmreg
  8233. vmovdqa/u %ymmreg, y(mem2)
  8234. vpxor %ymmreg, %ymmreg, %ymmreg
  8235. ( The VPXOR instruction is to zero the upper half, thus removing the
  8236. need to call the potentially expensive VZEROUPPER instruction. Other
  8237. peephole optimisations can remove VPXOR if it's unnecessary )
  8238. }
  8239. TransferUsedRegs(TmpUsedRegs);
  8240. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8241. { NOTE: In the optimisations below, if the references dictate that an
  8242. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8243. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8244. if (taicpu(p).opsize = S_XMM) and
  8245. MatchOpType(taicpu(p), top_ref, top_reg) and
  8246. GetNextInstruction(p, hp1) and
  8247. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8248. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8249. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8250. begin
  8251. SourceRef := taicpu(p).oper[0]^.ref^;
  8252. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8253. if GetNextInstruction(hp1, hp2) and
  8254. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8255. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8256. begin
  8257. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8258. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8259. Inc(SourceRef.offset, 16);
  8260. { Reuse the register in the first block move }
  8261. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8262. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8263. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8264. begin
  8265. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8266. Inc(TargetRef.offset, 16);
  8267. if GetNextInstruction(hp2, hp3) and
  8268. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8269. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8270. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8271. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8272. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8273. begin
  8274. { Update the register tracking to the new size }
  8275. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8276. { Remember that the offsets are 16 ahead }
  8277. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8278. if not (
  8279. ((SourceRef.offset mod 32) = 16) and
  8280. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8281. ) then
  8282. taicpu(p).opcode := A_VMOVDQU;
  8283. taicpu(p).opsize := S_YMM;
  8284. taicpu(p).oper[1]^.reg := CurrentReg;
  8285. if not (
  8286. ((TargetRef.offset mod 32) = 16) and
  8287. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8288. ) then
  8289. taicpu(hp1).opcode := A_VMOVDQU;
  8290. taicpu(hp1).opsize := S_YMM;
  8291. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8292. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8293. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8294. if (pi_uses_ymm in current_procinfo.flags) then
  8295. RemoveInstruction(hp2)
  8296. else
  8297. begin
  8298. taicpu(hp2).opcode := A_VPXOR;
  8299. taicpu(hp2).opsize := S_YMM;
  8300. taicpu(hp2).loadreg(0, CurrentReg);
  8301. taicpu(hp2).loadreg(1, CurrentReg);
  8302. taicpu(hp2).loadreg(2, CurrentReg);
  8303. taicpu(hp2).ops := 3;
  8304. end;
  8305. RemoveInstruction(hp3);
  8306. Result := True;
  8307. Exit;
  8308. end;
  8309. end
  8310. else
  8311. begin
  8312. { See if the next references are 16 less rather than 16 greater }
  8313. Dec(SourceRef.offset, 32); { -16 the other way }
  8314. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8315. begin
  8316. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8317. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8318. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8319. GetNextInstruction(hp2, hp3) and
  8320. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8321. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8322. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8323. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8324. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8325. begin
  8326. { Update the register tracking to the new size }
  8327. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8328. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8329. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8330. if not(
  8331. ((SourceRef.offset mod 32) = 0) and
  8332. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8333. ) then
  8334. taicpu(hp2).opcode := A_VMOVDQU;
  8335. taicpu(hp2).opsize := S_YMM;
  8336. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8337. if not (
  8338. ((TargetRef.offset mod 32) = 0) and
  8339. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8340. ) then
  8341. taicpu(hp3).opcode := A_VMOVDQU;
  8342. taicpu(hp3).opsize := S_YMM;
  8343. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8344. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8345. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8346. if (pi_uses_ymm in current_procinfo.flags) then
  8347. RemoveInstruction(hp1)
  8348. else
  8349. begin
  8350. taicpu(hp1).opcode := A_VPXOR;
  8351. taicpu(hp1).opsize := S_YMM;
  8352. taicpu(hp1).loadreg(0, CurrentReg);
  8353. taicpu(hp1).loadreg(1, CurrentReg);
  8354. taicpu(hp1).loadreg(2, CurrentReg);
  8355. taicpu(hp1).ops := 3;
  8356. Asml.Remove(hp1);
  8357. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8358. end;
  8359. RemoveCurrentP(p, hp2);
  8360. Result := True;
  8361. Exit;
  8362. end;
  8363. end;
  8364. end;
  8365. end;
  8366. end;
  8367. end;
  8368. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8369. var
  8370. hp2, hp3, first_assignment: tai;
  8371. IncCount, OperIdx: Integer;
  8372. OrigLabel: TAsmLabel;
  8373. begin
  8374. Count := 0;
  8375. Result := False;
  8376. first_assignment := nil;
  8377. if (LoopCount >= 20) then
  8378. begin
  8379. { Guard against infinite loops }
  8380. Exit;
  8381. end;
  8382. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8383. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8384. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8385. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8386. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8387. Exit;
  8388. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8389. {
  8390. change
  8391. jmp .L1
  8392. ...
  8393. .L1:
  8394. mov ##, ## ( multiple movs possible )
  8395. jmp/ret
  8396. into
  8397. mov ##, ##
  8398. jmp/ret
  8399. }
  8400. if not Assigned(hp1) then
  8401. begin
  8402. hp1 := GetLabelWithSym(OrigLabel);
  8403. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8404. Exit;
  8405. end;
  8406. hp2 := hp1;
  8407. while Assigned(hp2) do
  8408. begin
  8409. if Assigned(hp2) and (hp2.typ = ait_label) then
  8410. SkipLabels(hp2,hp2);
  8411. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8412. Break;
  8413. case taicpu(hp2).opcode of
  8414. A_MOVSD:
  8415. begin
  8416. if taicpu(hp2).ops = 0 then
  8417. { Wrong MOVSD }
  8418. Break;
  8419. Inc(Count);
  8420. if Count >= 5 then
  8421. { Too many to be worthwhile }
  8422. Break;
  8423. GetNextInstruction(hp2, hp2);
  8424. Continue;
  8425. end;
  8426. A_MOV,
  8427. A_MOVD,
  8428. A_MOVQ,
  8429. A_MOVSX,
  8430. {$ifdef x86_64}
  8431. A_MOVSXD,
  8432. {$endif x86_64}
  8433. A_MOVZX,
  8434. A_MOVAPS,
  8435. A_MOVUPS,
  8436. A_MOVSS,
  8437. A_MOVAPD,
  8438. A_MOVUPD,
  8439. A_MOVDQA,
  8440. A_MOVDQU,
  8441. A_VMOVSS,
  8442. A_VMOVAPS,
  8443. A_VMOVUPS,
  8444. A_VMOVSD,
  8445. A_VMOVAPD,
  8446. A_VMOVUPD,
  8447. A_VMOVDQA,
  8448. A_VMOVDQU:
  8449. begin
  8450. Inc(Count);
  8451. if Count >= 5 then
  8452. { Too many to be worthwhile }
  8453. Break;
  8454. GetNextInstruction(hp2, hp2);
  8455. Continue;
  8456. end;
  8457. A_JMP:
  8458. begin
  8459. { Guard against infinite loops }
  8460. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8461. Exit;
  8462. { Analyse this jump first in case it also duplicates assignments }
  8463. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8464. begin
  8465. { Something did change! }
  8466. Result := True;
  8467. Inc(Count, IncCount);
  8468. if Count >= 5 then
  8469. begin
  8470. { Too many to be worthwhile }
  8471. Exit;
  8472. end;
  8473. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8474. Break;
  8475. end;
  8476. Result := True;
  8477. Break;
  8478. end;
  8479. A_RET:
  8480. begin
  8481. Result := True;
  8482. Break;
  8483. end;
  8484. else
  8485. Break;
  8486. end;
  8487. end;
  8488. if Result then
  8489. begin
  8490. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8491. if Count = 0 then
  8492. begin
  8493. Result := False;
  8494. Exit;
  8495. end;
  8496. TransferUsedRegs(TmpUsedRegs);
  8497. hp3 := p;
  8498. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8499. while True do
  8500. begin
  8501. if Assigned(hp1) and (hp1.typ = ait_label) then
  8502. SkipLabels(hp1,hp1);
  8503. case hp1.typ of
  8504. ait_regalloc:
  8505. if tai_regalloc(hp1).ratype = ra_dealloc then
  8506. begin
  8507. { Duplicate the register deallocation... }
  8508. hp3:=tai(hp1.getcopy);
  8509. if first_assignment = nil then
  8510. first_assignment := hp3;
  8511. asml.InsertBefore(hp3, p);
  8512. { ... but also reallocate it after the jump }
  8513. hp3:=tai(hp1.getcopy);
  8514. tai_regalloc(hp3).ratype := ra_alloc;
  8515. asml.InsertAfter(hp3, p);
  8516. end;
  8517. ait_instruction:
  8518. case taicpu(hp1).opcode of
  8519. A_JMP:
  8520. begin
  8521. { Change the original jump to the new destination }
  8522. OrigLabel.decrefs;
  8523. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8524. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8525. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8526. if not Assigned(first_assignment) then
  8527. InternalError(2021040810)
  8528. else
  8529. p := first_assignment;
  8530. Exit;
  8531. end;
  8532. A_RET:
  8533. begin
  8534. { Now change the jump into a RET instruction }
  8535. ConvertJumpToRET(p, hp1);
  8536. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8537. if not Assigned(first_assignment) then
  8538. InternalError(2021040811)
  8539. else
  8540. p := first_assignment;
  8541. Exit;
  8542. end;
  8543. else
  8544. begin
  8545. { Duplicate the MOV instruction }
  8546. hp3:=tai(hp1.getcopy);
  8547. if first_assignment = nil then
  8548. first_assignment := hp3;
  8549. asml.InsertBefore(hp3, p);
  8550. { Make sure the compiler knows about any final registers written here }
  8551. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8552. with taicpu(hp3).oper[OperIdx]^ do
  8553. begin
  8554. case typ of
  8555. top_ref:
  8556. begin
  8557. if (ref^.base <> NR_NO) and
  8558. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8559. (
  8560. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8561. (
  8562. { Allow the frame pointer if it's not being used by the procedure as such }
  8563. Assigned(current_procinfo) and
  8564. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8565. )
  8566. )
  8567. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8568. then
  8569. begin
  8570. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8571. if not Assigned(first_assignment) then
  8572. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8573. end;
  8574. if (ref^.index <> NR_NO) and
  8575. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8576. (
  8577. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8578. (
  8579. { Allow the frame pointer if it's not being used by the procedure as such }
  8580. Assigned(current_procinfo) and
  8581. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8582. )
  8583. )
  8584. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8585. (ref^.index <> ref^.base) then
  8586. begin
  8587. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8588. if not Assigned(first_assignment) then
  8589. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8590. end;
  8591. end;
  8592. top_reg:
  8593. begin
  8594. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8595. if not Assigned(first_assignment) then
  8596. IncludeRegInUsedRegs(reg, UsedRegs);
  8597. end;
  8598. else
  8599. ;
  8600. end;
  8601. end;
  8602. end;
  8603. end;
  8604. else
  8605. InternalError(2021040720);
  8606. end;
  8607. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  8608. { Should have dropped out earlier }
  8609. InternalError(2021040710);
  8610. end;
  8611. end;
  8612. end;
  8613. const
  8614. WriteOp: array[0..3] of set of TInsChange = (
  8615. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8616. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8617. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8618. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8619. RegWriteFlags: array[0..7] of set of TInsChange = (
  8620. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8621. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8622. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8623. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8624. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8625. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8626. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8627. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8628. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8629. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8630. var
  8631. hp2: tai;
  8632. X: Integer;
  8633. begin
  8634. { If we have something like:
  8635. op ###,###
  8636. mov ###,###
  8637. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8638. interfere in regards to what they write to.
  8639. NOTE: p must be a 2-operand instruction
  8640. }
  8641. Result := False;
  8642. if (hp1.typ <> ait_instruction) or
  8643. taicpu(hp1).is_jmp or
  8644. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8645. Exit;
  8646. { NOP is a pipeline fence, likely marking the beginning of the function
  8647. epilogue, so drop out. Similarly, drop out if POP or RET are
  8648. encountered }
  8649. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8650. Exit;
  8651. if (taicpu(hp1).opcode = A_MOVSD) and
  8652. (taicpu(hp1).ops = 0) then
  8653. { Wrong MOVSD }
  8654. Exit;
  8655. { Check for writes to specific registers first }
  8656. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8657. for X := 0 to 7 do
  8658. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8659. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8660. Exit;
  8661. for X := 0 to taicpu(hp1).ops - 1 do
  8662. begin
  8663. { Check to see if this operand writes to something }
  8664. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8665. { And matches something in the CMP/TEST instruction }
  8666. (
  8667. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8668. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8669. (
  8670. { If it's a register, make sure the register written to doesn't
  8671. appear in the cmp instruction as part of a reference }
  8672. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8673. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8674. )
  8675. ) then
  8676. Exit;
  8677. end;
  8678. { Check p to make sure it doesn't write to something that affects hp1 }
  8679. { Check for writes to specific registers first }
  8680. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8681. for X := 0 to 7 do
  8682. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8683. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8684. Exit;
  8685. for X := 0 to taicpu(p).ops - 1 do
  8686. begin
  8687. { Check to see if this operand writes to something }
  8688. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8689. { And matches something in hp1 }
  8690. (taicpu(p).oper[X]^.typ = top_reg) and
  8691. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8692. Exit;
  8693. end;
  8694. { The instruction can be safely moved }
  8695. asml.Remove(hp1);
  8696. { Try to insert after the last instructions where the FLAGS register is not
  8697. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8698. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8699. asml.InsertBefore(hp1, hp2)
  8700. { Failing that, try to insert after the last instructions where the
  8701. FLAGS register is not yet in use }
  8702. else if GetLastInstruction(p, hp2) and
  8703. (
  8704. (hp2.typ <> ait_instruction) or
  8705. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8706. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8707. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8708. ) then
  8709. asml.InsertAfter(hp1, hp2)
  8710. else
  8711. { Note, if p.Previous is nil (even if it should logically never be the
  8712. case), FindRegAllocBackward immediately exits with False and so we
  8713. safely land here (we can't just pass p because FindRegAllocBackward
  8714. immediately exits on an instruction). [Kit] }
  8715. asml.InsertBefore(hp1, p);
  8716. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8717. { We can't trust UsedRegs because we're looking backwards, although we
  8718. know the registers are allocated after p at the very least, so manually
  8719. create tai_regalloc objects if needed }
  8720. for X := 0 to taicpu(hp1).ops - 1 do
  8721. case taicpu(hp1).oper[X]^.typ of
  8722. top_reg:
  8723. begin
  8724. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8725. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8726. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8727. end;
  8728. top_ref:
  8729. begin
  8730. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8731. begin
  8732. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8733. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8734. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8735. end;
  8736. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8737. begin
  8738. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8739. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8740. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8741. end;
  8742. end;
  8743. else
  8744. ;
  8745. end;
  8746. Result := True;
  8747. end;
  8748. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8749. var
  8750. hp2: tai;
  8751. X: Integer;
  8752. begin
  8753. { If we have something like:
  8754. cmp ###,%reg1
  8755. mov 0,%reg2
  8756. And no modified registers are shared, move the instruction to before
  8757. the comparison as this means it can be optimised without worrying
  8758. about the FLAGS register. (CMP/MOV is generated by
  8759. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8760. As long as the second instruction doesn't use the flags or one of the
  8761. registers used by CMP or TEST (also check any references that use the
  8762. registers), then it can be moved prior to the comparison.
  8763. }
  8764. Result := False;
  8765. if not TrySwapMovOp(p, hp1) then
  8766. Exit;
  8767. if taicpu(hp1).opcode = A_LEA then
  8768. { The flags will be overwritten by the CMP/TEST instruction }
  8769. ConvertLEA(taicpu(hp1));
  8770. Result := True;
  8771. { Can we move it one further back? }
  8772. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8773. { Check to see if CMP/TEST is a comparison against zero }
  8774. (
  8775. (
  8776. (taicpu(p).opcode = A_CMP) and
  8777. MatchOperand(taicpu(p).oper[0]^, 0)
  8778. ) or
  8779. (
  8780. (taicpu(p).opcode = A_TEST) and
  8781. (
  8782. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8783. MatchOperand(taicpu(p).oper[0]^, -1)
  8784. )
  8785. )
  8786. ) and
  8787. { These instructions set the zero flag if the result is zero }
  8788. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8789. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8790. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8791. TrySwapMovOp(hp2, hp1);
  8792. end;
  8793. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8794. var
  8795. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8796. JumpLabel: TAsmLabel;
  8797. TmpBool: Boolean;
  8798. begin
  8799. Result := False;
  8800. { Look for:
  8801. stc/clc
  8802. j(c) .L1
  8803. ...
  8804. .L1:
  8805. set(n)cb %reg
  8806. (flags deallocated)
  8807. j(c) .L2
  8808. Change to:
  8809. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8810. j(c) .L2
  8811. }
  8812. p_last := p;
  8813. while GetNextInstruction(p_last, hp1) and
  8814. (hp1.typ = ait_instruction) and
  8815. IsJumpToLabel(taicpu(hp1)) do
  8816. begin
  8817. if DoJumpOptimizations(hp1, TmpBool) then
  8818. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8819. Continue;
  8820. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8821. if not Assigned(JumpLabel) then
  8822. InternalError(2024012801);
  8823. { Optimise the J(c); stc/clc optimisation first since this will
  8824. get missed if the main optimisation takes place }
  8825. if (taicpu(hp1).opcode = A_JCC) then
  8826. begin
  8827. if GetNextInstruction(hp1, hp2) and
  8828. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8829. TryJccStcClcOpt(hp1, hp2) then
  8830. begin
  8831. Result := True;
  8832. Exit;
  8833. end;
  8834. hp2 := nil; { Suppress compiler warning }
  8835. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8836. { Make sure the flags aren't used again }
  8837. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8838. begin
  8839. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8840. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8841. begin
  8842. if (taicpu(p).opcode = A_STC) then
  8843. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8844. else
  8845. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8846. MakeUnconditional(taicpu(hp1));
  8847. { Move the jump to after the flag deallocations }
  8848. Asml.Remove(hp1);
  8849. Asml.InsertAfter(hp1, hp2);
  8850. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8851. Result := True;
  8852. Exit;
  8853. end
  8854. else
  8855. begin
  8856. if (taicpu(p).opcode = A_STC) then
  8857. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8858. else
  8859. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8860. { In this case, the jump is deterministic in that it will never be taken }
  8861. JumpLabel.DecRefs;
  8862. RemoveInstruction(hp1);
  8863. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8864. Result := True;
  8865. Exit;
  8866. end;
  8867. end;
  8868. end;
  8869. hp2 := nil; { Suppress compiler warning }
  8870. if
  8871. { Make sure the carry flag doesn't appear in the jump conditions }
  8872. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8873. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8874. GetNextInstruction(hp2, p_dist) and
  8875. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8876. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8877. begin
  8878. case taicpu(p_dist).opcode of
  8879. A_Jcc:
  8880. begin
  8881. if DoJumpOptimizations(p_dist, TmpBool) then
  8882. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8883. Continue;
  8884. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8885. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8886. begin
  8887. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8888. JumpLabel.decrefs;
  8889. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8890. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8891. Result := True;
  8892. Exit;
  8893. end
  8894. else if GetNextInstruction(p_dist, hp1_dist) and
  8895. (hp1_dist.typ = ait_label) then
  8896. begin
  8897. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8898. JumpLabel.decrefs;
  8899. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8900. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8901. Result := True;
  8902. Exit;
  8903. end;
  8904. end;
  8905. A_SETcc:
  8906. if { Make sure the flags aren't used again }
  8907. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8908. GetNextInstruction(hp2, hp1_dist) and
  8909. (hp1_dist.typ = ait_instruction) and
  8910. IsJumpToLabel(taicpu(hp1_dist)) and
  8911. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8912. { This works if hp1_dist or both are regular JMP instructions }
  8913. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  8914. (
  8915. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  8916. { Make sure the register isn't still in use, otherwise it
  8917. may get corrupted (fixes #40659) }
  8918. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  8919. ) then
  8920. begin
  8921. taicpu(p).allocate_oper(2);
  8922. taicpu(p).ops := 2;
  8923. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8924. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8925. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8926. taicpu(p).opcode := A_MOV;
  8927. taicpu(p).opsize := S_B;
  8928. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8929. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8930. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8931. JumpLabel.decrefs;
  8932. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8933. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8934. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  8935. (tai_regalloc(hp2).ratype = ra_alloc) then
  8936. begin
  8937. Asml.Remove(hp2);
  8938. Asml.InsertAfter(hp2, p);
  8939. end;
  8940. Result := True;
  8941. Exit;
  8942. end;
  8943. else
  8944. ;
  8945. end;
  8946. end;
  8947. p_last := hp1;
  8948. end;
  8949. end;
  8950. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8951. var
  8952. hp2, hp3: tai;
  8953. TempBool: Boolean;
  8954. begin
  8955. Result := False;
  8956. {
  8957. j(c) .L1
  8958. stc/clc
  8959. .L1:
  8960. jc/jnc .L2
  8961. (Flags deallocated)
  8962. Change to:
  8963. j)c) .L1
  8964. jmp .L2
  8965. .L1:
  8966. jc/jnc .L2
  8967. Then call DoJumpOptimizations to convert to:
  8968. j(nc) .L2
  8969. .L1: (may become a dead label)
  8970. jc/jnc .L2
  8971. }
  8972. if GetNextInstruction(hp1, hp2) and
  8973. (hp2.typ = ait_label) and
  8974. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8975. GetNextInstruction(hp2, hp3) and
  8976. MatchInstruction(hp3, A_Jcc, []) and
  8977. (
  8978. (
  8979. (taicpu(hp3).condition = C_C) and
  8980. (taicpu(hp1).opcode = A_STC)
  8981. ) or (
  8982. (taicpu(hp3).condition = C_NC) and
  8983. (taicpu(hp1).opcode = A_CLC)
  8984. )
  8985. ) and
  8986. { Make sure the flags aren't used again }
  8987. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  8988. begin
  8989. taicpu(hp1).allocate_oper(1);
  8990. taicpu(hp1).ops := 1;
  8991. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  8992. taicpu(hp1).opcode := A_JMP;
  8993. taicpu(hp1).is_jmp := True;
  8994. TempBool := True; { Prevent compiler warnings }
  8995. if DoJumpOptimizations(p, TempBool) then
  8996. Result := True
  8997. else
  8998. Include(OptsToCheck, aoc_ForceNewIteration);
  8999. end;
  9000. end;
  9001. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  9002. begin
  9003. { This generally only executes under -O3 and above }
  9004. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  9005. end;
  9006. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  9007. var
  9008. hp1, hp2: tai;
  9009. FoundComparison: Boolean;
  9010. begin
  9011. { Run the pass 1 optimisations as well, since they may have some effect
  9012. after the CMOV blocks are created in OptPass2Jcc }
  9013. Result := False;
  9014. { Result := OptPass1CMOVcc(p);
  9015. if Result then
  9016. Exit;}
  9017. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  9018. and make a slightly inefficent result on branching-type blocks, notably
  9019. when setting a function result then jumping to the function epilogue.
  9020. In this case, change:
  9021. cmov(c) %reg1,%reg2
  9022. j(c) @lbl
  9023. (%reg2 deallocated)
  9024. To:
  9025. mov %reg11,%reg2
  9026. j(c) @lbl
  9027. Note, we can't use GetNextInstructionUsingReg to find the conditional
  9028. jump because if it's not present, we may end up with a jump that's
  9029. completely unrelated.
  9030. }
  9031. hp1 := p;
  9032. while GetNextInstruction(hp1, hp1) and
  9033. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  9034. if (hp1.typ = ait_instruction) and
  9035. (taicpu(hp1).opcode = A_Jcc) and
  9036. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  9037. begin
  9038. TransferUsedRegs(TmpUsedRegs);
  9039. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  9040. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  9041. (
  9042. { See if we can find a more distant instruction that overwrites
  9043. the destination register }
  9044. (cs_opt_level3 in current_settings.optimizerswitches) and
  9045. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9046. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9047. ) then
  9048. begin
  9049. if (taicpu(p).oper[0]^.typ = top_reg) then
  9050. begin
  9051. { Search backwards to see if the source register is set to a
  9052. constant }
  9053. FoundComparison := False;
  9054. hp1 := p;
  9055. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9056. begin
  9057. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9058. begin
  9059. FoundComparison := True;
  9060. Continue;
  9061. end;
  9062. { Once we find the CMP, TEST or similar instruction, we
  9063. have to stop if we find anything other than a MOV }
  9064. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9065. Break;
  9066. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9067. { Destination register was modified }
  9068. Break;
  9069. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9070. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9071. begin
  9072. { Found a constant! }
  9073. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9074. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9075. { The source register is no longer in use }
  9076. RemoveInstruction(hp1);
  9077. Break;
  9078. end;
  9079. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9080. { Some other instruction has modified the source register }
  9081. Break;
  9082. end;
  9083. end;
  9084. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9085. taicpu(p).opcode := A_MOV;
  9086. taicpu(p).condition := C_None;
  9087. { Rely on the post peephole stage to put the MOV before the
  9088. CMP/TEST instruction that appears prior }
  9089. Result := True;
  9090. Exit;
  9091. end;
  9092. end;
  9093. end;
  9094. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9095. function IsXCHGAcceptable: Boolean; inline;
  9096. begin
  9097. { Always accept if optimising for size }
  9098. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9099. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9100. than 3, so it becomes a saving compared to three MOVs with two of
  9101. them able to execute simultaneously. [Kit] }
  9102. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9103. end;
  9104. var
  9105. NewRef: TReference;
  9106. hp1, hp2, hp3, hp4: Tai;
  9107. {$ifndef x86_64}
  9108. OperIdx: Integer;
  9109. {$endif x86_64}
  9110. NewInstr : Taicpu;
  9111. NewAligh : Tai_align;
  9112. DestLabel: TAsmLabel;
  9113. TempTracking: TAllUsedRegs;
  9114. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9115. var
  9116. NextInstr: tai;
  9117. begin
  9118. Result := False;
  9119. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9120. if not GetNextInstruction(InputInstr, NextInstr) or
  9121. (
  9122. { The FLAGS register isn't always tracked properly, so do not
  9123. perform this optimisation if a conditional statement follows }
  9124. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9125. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9126. ) then
  9127. begin
  9128. reference_reset(NewRef, 1, []);
  9129. NewRef.base := taicpu(p).oper[0]^.reg;
  9130. NewRef.scalefactor := 1;
  9131. if taicpu(InputInstr).opcode = A_ADD then
  9132. begin
  9133. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9134. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9135. end
  9136. else
  9137. begin
  9138. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9139. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9140. end;
  9141. taicpu(p).opcode := A_LEA;
  9142. taicpu(p).loadref(0, NewRef);
  9143. { For the sake of debugging, have the line info match the
  9144. arithmetic instruction rather than the MOV instruction }
  9145. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9146. RemoveInstruction(InputInstr);
  9147. Result := True;
  9148. end;
  9149. end;
  9150. begin
  9151. Result:=false;
  9152. { This optimisation adds an instruction, so only do it for speed }
  9153. if not (cs_opt_size in current_settings.optimizerswitches) and
  9154. MatchOpType(taicpu(p), top_const, top_reg) and
  9155. (taicpu(p).oper[0]^.val = 0) then
  9156. begin
  9157. { To avoid compiler warning }
  9158. DestLabel := nil;
  9159. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9160. InternalError(2021040750);
  9161. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9162. Exit;
  9163. case hp1.typ of
  9164. ait_label:
  9165. begin
  9166. { Change:
  9167. mov $0,%reg mov $0,%reg
  9168. @Lbl1: @Lbl1:
  9169. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9170. je @Lbl2 jne @Lbl2
  9171. To: To:
  9172. mov $0,%reg mov $0,%reg
  9173. jmp @Lbl2 jmp @Lbl3
  9174. (align) (align)
  9175. @Lbl1: @Lbl1:
  9176. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9177. je @Lbl2 je @Lbl2
  9178. @Lbl3: <-- Only if label exists
  9179. (Not if it's optimised for size)
  9180. }
  9181. if not GetNextInstruction(hp1, hp2) then
  9182. Exit;
  9183. if (hp2.typ = ait_instruction) and
  9184. (
  9185. { Register sizes must exactly match }
  9186. (
  9187. (taicpu(hp2).opcode = A_CMP) and
  9188. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9189. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9190. ) or (
  9191. (taicpu(hp2).opcode = A_TEST) and
  9192. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9193. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9194. )
  9195. ) and GetNextInstruction(hp2, hp3) and
  9196. (hp3.typ = ait_instruction) and
  9197. (taicpu(hp3).opcode = A_JCC) and
  9198. (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
  9199. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9200. begin
  9201. { Check condition of jump }
  9202. { Always true? }
  9203. if condition_in(C_E, taicpu(hp3).condition) then
  9204. begin
  9205. { Copy label symbol and obtain matching label entry for the
  9206. conditional jump, as this will be our destination}
  9207. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9208. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9209. Result := True;
  9210. end
  9211. { Always false? }
  9212. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9213. begin
  9214. { This is only worth it if there's a jump to take }
  9215. case hp2.typ of
  9216. ait_instruction:
  9217. begin
  9218. if taicpu(hp2).opcode = A_JMP then
  9219. begin
  9220. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9221. { An unconditional jump follows the conditional jump which will always be false,
  9222. so use this jump's destination for the new jump }
  9223. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9224. Result := True;
  9225. end
  9226. else if taicpu(hp2).opcode = A_JCC then
  9227. begin
  9228. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9229. if condition_in(C_E, taicpu(hp2).condition) then
  9230. begin
  9231. { A second conditional jump follows the conditional jump which will always be false,
  9232. while the second jump is always True, so use this jump's destination for the new jump }
  9233. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9234. Result := True;
  9235. end;
  9236. { Don't risk it if the jump isn't always true (Result remains False) }
  9237. end;
  9238. end;
  9239. else
  9240. { If anything else don't optimise };
  9241. end;
  9242. end;
  9243. if Result then
  9244. begin
  9245. { Just so we have something to insert as a paremeter}
  9246. reference_reset(NewRef, 1, []);
  9247. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9248. { Now actually load the correct parameter (this also
  9249. increases the reference count) }
  9250. NewInstr.loadsymbol(0, DestLabel, 0);
  9251. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9252. begin
  9253. { Get instruction before original label (may not be p under -O3) }
  9254. if not GetLastInstruction(hp1, hp2) then
  9255. { Shouldn't fail here }
  9256. InternalError(2021040701);
  9257. end
  9258. else
  9259. hp2 := p;
  9260. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9261. AsmL.InsertAfter(NewInstr, hp2);
  9262. { Add new alignment field }
  9263. (* AsmL.InsertAfter(
  9264. cai_align.create_max(
  9265. current_settings.alignment.jumpalign,
  9266. current_settings.alignment.jumpalignskipmax
  9267. ),
  9268. NewInstr
  9269. ); *)
  9270. end;
  9271. Exit;
  9272. end;
  9273. end;
  9274. else
  9275. ;
  9276. end;
  9277. end;
  9278. if not GetNextInstruction(p, hp1) then
  9279. Exit;
  9280. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9281. begin
  9282. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9283. begin
  9284. Result := True;
  9285. Exit;
  9286. end;
  9287. { This optimisation is only effective on a second run of Pass 2,
  9288. hence -O3 or above.
  9289. Change:
  9290. mov %reg1,%reg2
  9291. cmp/test (contains %reg1)
  9292. mov x, %reg1
  9293. (another mov or a j(c))
  9294. To:
  9295. mov %reg1,%reg2
  9296. mov x, %reg1
  9297. cmp (%reg1 replaced with %reg2)
  9298. (another mov or a j(c))
  9299. The requirement of an additional MOV or a jump ensures there
  9300. isn't performance loss, since a j(c) will permit macro-fusion
  9301. with the cmp instruction, while another MOV likely means it's
  9302. not all being executed in a single cycle due to parallelisation.
  9303. }
  9304. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9305. MatchOpType(taicpu(p), top_reg, top_reg) and
  9306. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9307. GetNextInstruction(hp1, hp2) and
  9308. MatchInstruction(hp2, A_MOV, []) and
  9309. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9310. { Registers don't have to be the same size in this case }
  9311. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9312. GetNextInstruction(hp2, hp3) and
  9313. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9314. { Make sure the operands in the camparison can be safely replaced }
  9315. (
  9316. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9317. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9318. ) and
  9319. (
  9320. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9321. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9322. ) then
  9323. begin
  9324. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9325. AsmL.Remove(hp2);
  9326. AsmL.InsertAfter(hp2, p);
  9327. Result := True;
  9328. Exit;
  9329. end;
  9330. end;
  9331. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9332. begin
  9333. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9334. further, but we can't just put this jump optimisation in pass 1
  9335. because it tends to perform worse when conditional jumps are
  9336. nearby (e.g. when converting CMOV instructions). [Kit] }
  9337. CopyUsedRegs(TempTracking);
  9338. UpdateUsedRegs(tai(p.Next));
  9339. if OptPass2JMP(hp1) then
  9340. begin
  9341. { Restore register state }
  9342. RestoreUsedRegs(TempTracking);
  9343. ReleaseUsedRegs(TempTracking);
  9344. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9345. OptPass1MOV(p);
  9346. Result := True;
  9347. Exit;
  9348. end;
  9349. { If OptPass2JMP returned False, no optimisations were done to
  9350. the jump and there are no further optimisations that can be done
  9351. to the MOV instruction on this pass other than FuncMov2Func }
  9352. { Restore register state }
  9353. RestoreUsedRegs(TempTracking);
  9354. ReleaseUsedRegs(TempTracking);
  9355. Result := FuncMov2Func(p, hp1);
  9356. Exit;
  9357. end;
  9358. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9359. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9360. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9361. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9362. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9363. begin
  9364. { Change:
  9365. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9366. addl/q $x,%reg2 subl/q $x,%reg2
  9367. To:
  9368. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9369. }
  9370. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9371. { be lazy, checking separately for sub would be slightly better }
  9372. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9373. begin
  9374. TransferUsedRegs(TmpUsedRegs);
  9375. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9376. if TryMovArith2Lea(hp1) then
  9377. begin
  9378. Result := True;
  9379. Exit;
  9380. end
  9381. end
  9382. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9383. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9384. { Same as above, but also adds or subtracts to %reg2 in between.
  9385. It's still valid as long as the flags aren't in use }
  9386. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9387. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9388. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9389. { be lazy, checking separately for sub would be slightly better }
  9390. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9391. begin
  9392. TransferUsedRegs(TmpUsedRegs);
  9393. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9394. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9395. if TryMovArith2Lea(hp2) then
  9396. begin
  9397. Result := True;
  9398. Exit;
  9399. end;
  9400. end;
  9401. end;
  9402. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9403. {$ifdef x86_64}
  9404. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9405. {$else x86_64}
  9406. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9407. {$endif x86_64}
  9408. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9409. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9410. { mov reg1, reg2 mov reg1, reg2
  9411. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9412. begin
  9413. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9414. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9415. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9416. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9417. TransferUsedRegs(TmpUsedRegs);
  9418. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9419. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9420. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9421. then
  9422. begin
  9423. RemoveCurrentP(p, hp1);
  9424. Result:=true;
  9425. end;
  9426. Exit;
  9427. end;
  9428. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9429. IsXCHGAcceptable and
  9430. { XCHG doesn't support 8-bit registers }
  9431. (taicpu(p).opsize <> S_B) and
  9432. MatchInstruction(hp1, A_MOV, []) and
  9433. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9434. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9435. GetNextInstruction(hp1, hp2) and
  9436. MatchInstruction(hp2, A_MOV, []) and
  9437. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9438. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9439. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9440. begin
  9441. { mov %reg1,%reg2
  9442. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9443. mov %reg2,%reg3
  9444. (%reg2 not used afterwards)
  9445. Note that xchg takes 3 cycles to execute, and generally mov's take
  9446. only one cycle apiece, but the first two mov's can be executed in
  9447. parallel, only taking 2 cycles overall. Older processors should
  9448. therefore only optimise for size. [Kit]
  9449. }
  9450. TransferUsedRegs(TmpUsedRegs);
  9451. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9452. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9453. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9454. begin
  9455. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9456. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9457. taicpu(hp1).opcode := A_XCHG;
  9458. RemoveCurrentP(p, hp1);
  9459. RemoveInstruction(hp2);
  9460. Result := True;
  9461. Exit;
  9462. end;
  9463. end;
  9464. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9465. MatchInstruction(hp1, A_SAR, []) then
  9466. begin
  9467. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9468. begin
  9469. { the use of %edx also covers the opsize being S_L }
  9470. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9471. begin
  9472. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9473. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9474. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9475. begin
  9476. { Change:
  9477. movl %eax,%edx
  9478. sarl $31,%edx
  9479. To:
  9480. cltd
  9481. }
  9482. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9483. RemoveInstruction(hp1);
  9484. taicpu(p).opcode := A_CDQ;
  9485. taicpu(p).opsize := S_NO;
  9486. taicpu(p).clearop(1);
  9487. taicpu(p).clearop(0);
  9488. taicpu(p).ops:=0;
  9489. Result := True;
  9490. Exit;
  9491. end
  9492. else if (cs_opt_size in current_settings.optimizerswitches) and
  9493. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9494. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9495. begin
  9496. { Change:
  9497. movl %edx,%eax
  9498. sarl $31,%edx
  9499. To:
  9500. movl %edx,%eax
  9501. cltd
  9502. Note that this creates a dependency between the two instructions,
  9503. so only perform if optimising for size.
  9504. }
  9505. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9506. taicpu(hp1).opcode := A_CDQ;
  9507. taicpu(hp1).opsize := S_NO;
  9508. taicpu(hp1).clearop(1);
  9509. taicpu(hp1).clearop(0);
  9510. taicpu(hp1).ops:=0;
  9511. Include(OptsToCheck, aoc_ForceNewIteration);
  9512. Exit;
  9513. end;
  9514. {$ifndef x86_64}
  9515. end
  9516. { Don't bother if CMOV is supported, because a more optimal
  9517. sequence would have been generated for the Abs() intrinsic }
  9518. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9519. { the use of %eax also covers the opsize being S_L }
  9520. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9521. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9522. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9523. GetNextInstruction(hp1, hp2) and
  9524. MatchInstruction(hp2, A_XOR, [S_L]) and
  9525. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9526. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9527. GetNextInstruction(hp2, hp3) and
  9528. MatchInstruction(hp3, A_SUB, [S_L]) and
  9529. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9530. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9531. begin
  9532. { Change:
  9533. movl %eax,%edx
  9534. sarl $31,%eax
  9535. xorl %eax,%edx
  9536. subl %eax,%edx
  9537. (Instruction that uses %edx)
  9538. (%eax deallocated)
  9539. (%edx deallocated)
  9540. To:
  9541. cltd
  9542. xorl %edx,%eax <-- Note the registers have swapped
  9543. subl %edx,%eax
  9544. (Instruction that uses %eax) <-- %eax rather than %edx
  9545. }
  9546. TransferUsedRegs(TmpUsedRegs);
  9547. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9548. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9549. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9550. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9551. begin
  9552. if GetNextInstruction(hp3, hp4) and
  9553. not RegModifiedByInstruction(NR_EDX, hp4) and
  9554. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9555. begin
  9556. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9557. taicpu(p).opcode := A_CDQ;
  9558. taicpu(p).clearop(1);
  9559. taicpu(p).clearop(0);
  9560. taicpu(p).ops:=0;
  9561. RemoveInstruction(hp1);
  9562. taicpu(hp2).loadreg(0, NR_EDX);
  9563. taicpu(hp2).loadreg(1, NR_EAX);
  9564. taicpu(hp3).loadreg(0, NR_EDX);
  9565. taicpu(hp3).loadreg(1, NR_EAX);
  9566. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9567. { Convert references in the following instruction (hp4) from %edx to %eax }
  9568. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9569. with taicpu(hp4).oper[OperIdx]^ do
  9570. case typ of
  9571. top_reg:
  9572. if getsupreg(reg) = RS_EDX then
  9573. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9574. top_ref:
  9575. begin
  9576. if getsupreg(reg) = RS_EDX then
  9577. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9578. if getsupreg(reg) = RS_EDX then
  9579. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9580. end;
  9581. else
  9582. ;
  9583. end;
  9584. Result := True;
  9585. Exit;
  9586. end;
  9587. end;
  9588. {$else x86_64}
  9589. end;
  9590. end
  9591. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9592. { the use of %rdx also covers the opsize being S_Q }
  9593. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9594. begin
  9595. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9596. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9597. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9598. begin
  9599. { Change:
  9600. movq %rax,%rdx
  9601. sarq $63,%rdx
  9602. To:
  9603. cqto
  9604. }
  9605. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9606. RemoveInstruction(hp1);
  9607. taicpu(p).opcode := A_CQO;
  9608. taicpu(p).opsize := S_NO;
  9609. taicpu(p).clearop(1);
  9610. taicpu(p).clearop(0);
  9611. taicpu(p).ops:=0;
  9612. Result := True;
  9613. Exit;
  9614. end
  9615. else if (cs_opt_size in current_settings.optimizerswitches) and
  9616. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9617. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9618. begin
  9619. { Change:
  9620. movq %rdx,%rax
  9621. sarq $63,%rdx
  9622. To:
  9623. movq %rdx,%rax
  9624. cqto
  9625. Note that this creates a dependency between the two instructions,
  9626. so only perform if optimising for size.
  9627. }
  9628. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9629. taicpu(hp1).opcode := A_CQO;
  9630. taicpu(hp1).opsize := S_NO;
  9631. taicpu(hp1).clearop(1);
  9632. taicpu(hp1).clearop(0);
  9633. taicpu(hp1).ops:=0;
  9634. Include(OptsToCheck, aoc_ForceNewIteration);
  9635. Exit;
  9636. {$endif x86_64}
  9637. end;
  9638. end;
  9639. end;
  9640. if MatchInstruction(hp1, A_MOV, []) and
  9641. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9642. { Though "GetNextInstruction" could be factored out, along with
  9643. the instructions that depend on hp2, it is an expensive call that
  9644. should be delayed for as long as possible, hence we do cheaper
  9645. checks first that are likely to be False. [Kit] }
  9646. begin
  9647. if (
  9648. (
  9649. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9650. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9651. (
  9652. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9653. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9654. )
  9655. ) or
  9656. (
  9657. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9658. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9659. (
  9660. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9661. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9662. )
  9663. )
  9664. ) and
  9665. GetNextInstruction(hp1, hp2) and
  9666. MatchInstruction(hp2, A_SAR, []) and
  9667. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9668. begin
  9669. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9670. begin
  9671. { Change:
  9672. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9673. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9674. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9675. To:
  9676. movl r/m,%eax <- Note the change in register
  9677. cltd
  9678. }
  9679. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9680. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9681. taicpu(p).loadreg(1, NR_EAX);
  9682. taicpu(hp1).opcode := A_CDQ;
  9683. taicpu(hp1).clearop(1);
  9684. taicpu(hp1).clearop(0);
  9685. taicpu(hp1).ops:=0;
  9686. RemoveInstruction(hp2);
  9687. Include(OptsToCheck, aoc_ForceNewIteration);
  9688. (*
  9689. {$ifdef x86_64}
  9690. end
  9691. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9692. { This code sequence does not get generated - however it might become useful
  9693. if and when 128-bit signed integer types make an appearance, so the code
  9694. is kept here for when it is eventually needed. [Kit] }
  9695. (
  9696. (
  9697. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9698. (
  9699. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9700. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9701. )
  9702. ) or
  9703. (
  9704. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9705. (
  9706. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9707. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9708. )
  9709. )
  9710. ) and
  9711. GetNextInstruction(hp1, hp2) and
  9712. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9713. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9714. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9715. begin
  9716. { Change:
  9717. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9718. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9719. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9720. To:
  9721. movq r/m,%rax <- Note the change in register
  9722. cqto
  9723. }
  9724. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9725. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9726. taicpu(p).loadreg(1, NR_RAX);
  9727. taicpu(hp1).opcode := A_CQO;
  9728. taicpu(hp1).clearop(1);
  9729. taicpu(hp1).clearop(0);
  9730. taicpu(hp1).ops:=0;
  9731. RemoveInstruction(hp2);
  9732. Include(OptsToCheck, aoc_ForceNewIteration);
  9733. {$endif x86_64}
  9734. *)
  9735. end;
  9736. end;
  9737. {$ifdef x86_64}
  9738. end;
  9739. if (taicpu(p).opsize = S_L) and
  9740. (taicpu(p).oper[1]^.typ = top_reg) and
  9741. (
  9742. MatchInstruction(hp1, A_MOV,[]) and
  9743. (taicpu(hp1).opsize = S_L) and
  9744. (taicpu(hp1).oper[1]^.typ = top_reg)
  9745. ) and (
  9746. GetNextInstruction(hp1, hp2) and
  9747. (tai(hp2).typ=ait_instruction) and
  9748. (taicpu(hp2).opsize = S_Q) and
  9749. (
  9750. (
  9751. MatchInstruction(hp2, A_ADD,[]) and
  9752. (taicpu(hp2).opsize = S_Q) and
  9753. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9754. (
  9755. (
  9756. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9757. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9758. ) or (
  9759. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9760. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9761. )
  9762. )
  9763. ) or (
  9764. MatchInstruction(hp2, A_LEA,[]) and
  9765. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9766. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9767. (
  9768. (
  9769. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9770. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9771. ) or (
  9772. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9773. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9774. )
  9775. ) and (
  9776. (
  9777. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9778. ) or (
  9779. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9780. )
  9781. )
  9782. )
  9783. )
  9784. ) and (
  9785. GetNextInstruction(hp2, hp3) and
  9786. MatchInstruction(hp3, A_SHR,[]) and
  9787. (taicpu(hp3).opsize = S_Q) and
  9788. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9789. (taicpu(hp3).oper[0]^.val = 1) and
  9790. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9791. ) then
  9792. begin
  9793. { Change movl x, reg1d movl x, reg1d
  9794. movl y, reg2d movl y, reg2d
  9795. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9796. shrq $1, reg1q shrq $1, reg1q
  9797. ( reg1d and reg2d can be switched around in the first two instructions )
  9798. To movl x, reg1d
  9799. addl y, reg1d
  9800. rcrl $1, reg1d
  9801. This corresponds to the common expression (x + y) shr 1, where
  9802. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9803. smaller code, but won't account for x + y causing an overflow). [Kit]
  9804. }
  9805. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9806. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9807. begin
  9808. { Change first MOV command to have the same register as the final output }
  9809. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9810. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  9811. Result := True;
  9812. end
  9813. else
  9814. begin
  9815. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9816. Include(OptsToCheck, aoc_ForceNewIteration);
  9817. end;
  9818. { Change second MOV command to an ADD command. This is easier than
  9819. converting the existing command because it means we don't have to
  9820. touch 'y', which might be a complicated reference, and also the
  9821. fact that the third command might either be ADD or LEA. [Kit] }
  9822. taicpu(hp1).opcode := A_ADD;
  9823. { Delete old ADD/LEA instruction }
  9824. RemoveInstruction(hp2);
  9825. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9826. taicpu(hp3).opcode := A_RCR;
  9827. taicpu(hp3).changeopsize(S_L);
  9828. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9829. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  9830. called, so FuncMov2Func below is safe to call }
  9831. {$endif x86_64}
  9832. end;
  9833. if FuncMov2Func(p, hp1) then
  9834. begin
  9835. Result := True;
  9836. Exit;
  9837. end;
  9838. end;
  9839. {$push}
  9840. {$q-}{$r-}
  9841. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9842. var
  9843. ThisReg: TRegister;
  9844. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9845. TargetSubReg: TSubRegister;
  9846. hp1, hp2: tai;
  9847. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9848. { Store list of found instructions so we don't have to call
  9849. GetNextInstructionUsingReg multiple times }
  9850. InstrList: array of taicpu;
  9851. InstrMax, Index: Integer;
  9852. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9853. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9854. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9855. WorkingValue: TCgInt;
  9856. PreMessage: string;
  9857. { Data flow analysis }
  9858. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9859. BitwiseOnly, OrXorUsed,
  9860. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9861. function CheckOverflowConditions: Boolean;
  9862. begin
  9863. Result := True;
  9864. if (TestValSignedMax > SignedUpperLimit) then
  9865. UpperSignedOverflow := True;
  9866. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9867. LowerSignedOverflow := True;
  9868. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9869. LowerUnsignedOverflow := True;
  9870. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9871. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9872. begin
  9873. { Absolute overflow }
  9874. Result := False;
  9875. Exit;
  9876. end;
  9877. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9878. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9879. ShiftDownOverflow := True;
  9880. if (TestValMin < 0) or (TestValMax < 0) then
  9881. begin
  9882. LowerUnsignedOverflow := True;
  9883. UpperUnsignedOverflow := True;
  9884. end;
  9885. end;
  9886. function AdjustInitialLoadAndSize: Boolean;
  9887. begin
  9888. Result := False;
  9889. if not p_removed then
  9890. begin
  9891. if TargetSize = MinSize then
  9892. begin
  9893. { Convert the input MOVZX to a MOV }
  9894. if (taicpu(p).oper[0]^.typ = top_reg) and
  9895. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9896. begin
  9897. { Or remove it completely! }
  9898. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9899. RemoveCurrentP(p);
  9900. p_removed := True;
  9901. end
  9902. else
  9903. begin
  9904. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9905. taicpu(p).opcode := A_MOV;
  9906. taicpu(p).oper[1]^.reg := ThisReg;
  9907. taicpu(p).opsize := TargetSize;
  9908. end;
  9909. Result := True;
  9910. end
  9911. else if TargetSize <> MaxSize then
  9912. begin
  9913. case MaxSize of
  9914. S_L:
  9915. if TargetSize = S_W then
  9916. begin
  9917. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9918. taicpu(p).opsize := S_BW;
  9919. taicpu(p).oper[1]^.reg := ThisReg;
  9920. Result := True;
  9921. end
  9922. else
  9923. InternalError(2020112341);
  9924. S_W:
  9925. if TargetSize = S_L then
  9926. begin
  9927. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9928. taicpu(p).opsize := S_BL;
  9929. taicpu(p).oper[1]^.reg := ThisReg;
  9930. Result := True;
  9931. end
  9932. else
  9933. InternalError(2020112342);
  9934. else
  9935. ;
  9936. end;
  9937. end
  9938. else if not hp1_removed and not RegInUse then
  9939. begin
  9940. { If we have something like:
  9941. movzbl (oper),%regd
  9942. add x, %regd
  9943. movzbl %regb, %regd
  9944. We can reduce the register size to the input of the final
  9945. movzbl instruction. Overflows won't have any effect.
  9946. }
  9947. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9948. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9949. begin
  9950. TargetSize := S_B;
  9951. setsubreg(ThisReg, R_SUBL);
  9952. Result := True;
  9953. end
  9954. else if (taicpu(p).opsize = S_WL) and
  9955. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9956. begin
  9957. TargetSize := S_W;
  9958. setsubreg(ThisReg, R_SUBW);
  9959. Result := True;
  9960. end;
  9961. if Result then
  9962. begin
  9963. { Convert the input MOVZX to a MOV }
  9964. if (taicpu(p).oper[0]^.typ = top_reg) and
  9965. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9966. begin
  9967. { Or remove it completely! }
  9968. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9969. RemoveCurrentP(p);
  9970. p_removed := True;
  9971. end
  9972. else
  9973. begin
  9974. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9975. taicpu(p).opcode := A_MOV;
  9976. taicpu(p).oper[1]^.reg := ThisReg;
  9977. taicpu(p).opsize := TargetSize;
  9978. end;
  9979. end;
  9980. end;
  9981. end;
  9982. end;
  9983. procedure AdjustFinalLoad;
  9984. begin
  9985. if not LowerUnsignedOverflow then
  9986. begin
  9987. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9988. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9989. begin
  9990. { Convert the output MOVZX to a MOV }
  9991. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9992. begin
  9993. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9994. if (MinSize = S_B) or
  9995. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9996. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9997. begin
  9998. { Remove it completely! }
  9999. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  10000. { Be careful; if p = hp1 and p was also removed, p
  10001. will become a dangling pointer }
  10002. if p = hp1 then
  10003. begin
  10004. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10005. p_removed := True;
  10006. end
  10007. else
  10008. RemoveInstruction(hp1);
  10009. hp1_removed := True;
  10010. end;
  10011. end
  10012. else
  10013. begin
  10014. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  10015. taicpu(hp1).opcode := A_MOV;
  10016. taicpu(hp1).oper[0]^.reg := ThisReg;
  10017. taicpu(hp1).opsize := TargetSize;
  10018. end;
  10019. end
  10020. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  10021. begin
  10022. { Need to change the size of the output }
  10023. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  10024. taicpu(hp1).oper[0]^.reg := ThisReg;
  10025. taicpu(hp1).opsize := S_BL;
  10026. end;
  10027. end;
  10028. end;
  10029. function CompressInstructions: Boolean;
  10030. var
  10031. LocalIndex: Integer;
  10032. begin
  10033. Result := False;
  10034. { The objective here is to try to find a combination that
  10035. removes one of the MOV/Z instructions. }
  10036. if (
  10037. (taicpu(p).oper[0]^.typ <> top_reg) or
  10038. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  10039. ) and
  10040. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10041. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10042. begin
  10043. { Make a preference to remove the second MOVZX instruction }
  10044. case taicpu(hp1).opsize of
  10045. S_BL, S_WL:
  10046. begin
  10047. TargetSize := S_L;
  10048. TargetSubReg := R_SUBD;
  10049. end;
  10050. S_BW:
  10051. begin
  10052. TargetSize := S_W;
  10053. TargetSubReg := R_SUBW;
  10054. end;
  10055. else
  10056. InternalError(2020112302);
  10057. end;
  10058. end
  10059. else
  10060. begin
  10061. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10062. begin
  10063. { Exceeded lower bound but not upper bound }
  10064. TargetSize := MaxSize;
  10065. end
  10066. else if not LowerUnsignedOverflow then
  10067. begin
  10068. { Size didn't exceed lower bound }
  10069. TargetSize := MinSize;
  10070. end
  10071. else
  10072. Exit;
  10073. end;
  10074. case TargetSize of
  10075. S_B:
  10076. TargetSubReg := R_SUBL;
  10077. S_W:
  10078. TargetSubReg := R_SUBW;
  10079. S_L:
  10080. TargetSubReg := R_SUBD;
  10081. else
  10082. InternalError(2020112350);
  10083. end;
  10084. { Update the register to its new size }
  10085. setsubreg(ThisReg, TargetSubReg);
  10086. RegInUse := False;
  10087. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10088. begin
  10089. { Check to see if the active register is used afterwards;
  10090. if not, we can change it and make a saving. }
  10091. TransferUsedRegs(TmpUsedRegs);
  10092. { The target register may be marked as in use to cross
  10093. a jump to a distant label, so exclude it }
  10094. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10095. hp2 := p;
  10096. repeat
  10097. { Explicitly check for the excluded register (don't include the first
  10098. instruction as it may be reading from here }
  10099. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10100. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10101. begin
  10102. RegInUse := True;
  10103. Break;
  10104. end;
  10105. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10106. if not GetNextInstruction(hp2, hp2) then
  10107. InternalError(2020112340);
  10108. until (hp2 = hp1);
  10109. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10110. { We might still be able to get away with this }
  10111. RegInUse := not
  10112. (
  10113. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10114. (hp2.typ = ait_instruction) and
  10115. (
  10116. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10117. instruction that doesn't actually contain ThisReg }
  10118. (cs_opt_level3 in current_settings.optimizerswitches) or
  10119. RegInInstruction(ThisReg, hp2)
  10120. ) and
  10121. RegLoadedWithNewValue(ThisReg, hp2)
  10122. );
  10123. if not RegInUse then
  10124. begin
  10125. { Force the register size to the same as this instruction so it can be removed}
  10126. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10127. begin
  10128. TargetSize := S_L;
  10129. TargetSubReg := R_SUBD;
  10130. end
  10131. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10132. begin
  10133. TargetSize := S_W;
  10134. TargetSubReg := R_SUBW;
  10135. end;
  10136. ThisReg := taicpu(hp1).oper[1]^.reg;
  10137. setsubreg(ThisReg, TargetSubReg);
  10138. RegChanged := True;
  10139. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10140. TransferUsedRegs(TmpUsedRegs);
  10141. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10142. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10143. if p = hp1 then
  10144. begin
  10145. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10146. p_removed := True;
  10147. end
  10148. else
  10149. RemoveInstruction(hp1);
  10150. hp1_removed := True;
  10151. { Instruction will become "mov %reg,%reg" }
  10152. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10153. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10154. begin
  10155. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10156. RemoveCurrentP(p);
  10157. p_removed := True;
  10158. end
  10159. else
  10160. taicpu(p).oper[1]^.reg := ThisReg;
  10161. Result := True;
  10162. end
  10163. else
  10164. begin
  10165. if TargetSize <> MaxSize then
  10166. begin
  10167. { Since the register is in use, we have to force it to
  10168. MaxSize otherwise part of it may become undefined later on }
  10169. TargetSize := MaxSize;
  10170. case TargetSize of
  10171. S_B:
  10172. TargetSubReg := R_SUBL;
  10173. S_W:
  10174. TargetSubReg := R_SUBW;
  10175. S_L:
  10176. TargetSubReg := R_SUBD;
  10177. else
  10178. InternalError(2020112351);
  10179. end;
  10180. setsubreg(ThisReg, TargetSubReg);
  10181. end;
  10182. AdjustFinalLoad;
  10183. end;
  10184. end
  10185. else
  10186. AdjustFinalLoad;
  10187. Result := AdjustInitialLoadAndSize or Result;
  10188. { Now go through every instruction we found and change the
  10189. size. If TargetSize = MaxSize, then almost no changes are
  10190. needed and Result can remain False if it hasn't been set
  10191. yet.
  10192. If RegChanged is True, then the register requires changing
  10193. and so the point about TargetSize = MaxSize doesn't apply. }
  10194. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10195. begin
  10196. for LocalIndex := 0 to InstrMax do
  10197. begin
  10198. { If p_removed is true, then the original MOV/Z was removed
  10199. and removing the AND instruction may not be safe if it
  10200. appears first }
  10201. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10202. InternalError(2020112310);
  10203. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10204. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10205. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10206. InstrList[LocalIndex].opsize := TargetSize;
  10207. end;
  10208. Result := True;
  10209. end;
  10210. end;
  10211. begin
  10212. Result := False;
  10213. p_removed := False;
  10214. hp1_removed := False;
  10215. ThisReg := taicpu(p).oper[1]^.reg;
  10216. { Check for:
  10217. movs/z ###,%ecx (or %cx or %rcx)
  10218. ...
  10219. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10220. (dealloc %ecx)
  10221. Change to:
  10222. mov ###,%cl (if ### = %cl, then remove completely)
  10223. ...
  10224. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10225. }
  10226. if (getsupreg(ThisReg) = RS_ECX) and
  10227. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10228. (hp1.typ = ait_instruction) and
  10229. (
  10230. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10231. instruction that doesn't actually contain ECX }
  10232. (cs_opt_level3 in current_settings.optimizerswitches) or
  10233. RegInInstruction(NR_ECX, hp1) or
  10234. (
  10235. { It's common for the shift/rotate's read/write register to be
  10236. initialised in between, so under -O2 and under, search ahead
  10237. one more instruction
  10238. }
  10239. GetNextInstruction(hp1, hp1) and
  10240. (hp1.typ = ait_instruction) and
  10241. RegInInstruction(NR_ECX, hp1)
  10242. )
  10243. ) and
  10244. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10245. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10246. begin
  10247. TransferUsedRegs(TmpUsedRegs);
  10248. hp2 := p;
  10249. repeat
  10250. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10251. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10252. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10253. begin
  10254. case taicpu(p).opsize of
  10255. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10256. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10257. begin
  10258. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10259. RemoveCurrentP(p);
  10260. end
  10261. else
  10262. begin
  10263. taicpu(p).opcode := A_MOV;
  10264. taicpu(p).opsize := S_B;
  10265. taicpu(p).oper[1]^.reg := NR_CL;
  10266. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10267. end;
  10268. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10269. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10270. begin
  10271. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10272. RemoveCurrentP(p);
  10273. end
  10274. else
  10275. begin
  10276. taicpu(p).opcode := A_MOV;
  10277. taicpu(p).opsize := S_W;
  10278. taicpu(p).oper[1]^.reg := NR_CX;
  10279. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10280. end;
  10281. {$ifdef x86_64}
  10282. S_LQ:
  10283. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10284. begin
  10285. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10286. RemoveCurrentP(p);
  10287. end
  10288. else
  10289. begin
  10290. taicpu(p).opcode := A_MOV;
  10291. taicpu(p).opsize := S_L;
  10292. taicpu(p).oper[1]^.reg := NR_ECX;
  10293. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10294. end;
  10295. {$endif x86_64}
  10296. else
  10297. InternalError(2021120401);
  10298. end;
  10299. Result := True;
  10300. Exit;
  10301. end;
  10302. end;
  10303. { This is anything but quick! }
  10304. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10305. Exit;
  10306. SetLength(InstrList, 0);
  10307. InstrMax := -1;
  10308. case taicpu(p).opsize of
  10309. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10310. begin
  10311. {$if defined(i386) or defined(i8086)}
  10312. { If the target size is 8-bit, make sure we can actually encode it }
  10313. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10314. Exit;
  10315. {$endif i386 or i8086}
  10316. LowerLimit := $FF;
  10317. SignedLowerLimit := $7F;
  10318. SignedLowerLimitBottom := -128;
  10319. MinSize := S_B;
  10320. if taicpu(p).opsize = S_BW then
  10321. begin
  10322. MaxSize := S_W;
  10323. UpperLimit := $FFFF;
  10324. SignedUpperLimit := $7FFF;
  10325. SignedUpperLimitBottom := -32768;
  10326. end
  10327. else
  10328. begin
  10329. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10330. MaxSize := S_L;
  10331. UpperLimit := $FFFFFFFF;
  10332. SignedUpperLimit := $7FFFFFFF;
  10333. SignedUpperLimitBottom := -2147483648;
  10334. end;
  10335. end;
  10336. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10337. begin
  10338. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10339. LowerLimit := $FFFF;
  10340. SignedLowerLimit := $7FFF;
  10341. SignedLowerLimitBottom := -32768;
  10342. UpperLimit := $FFFFFFFF;
  10343. SignedUpperLimit := $7FFFFFFF;
  10344. SignedUpperLimitBottom := -2147483648;
  10345. MinSize := S_W;
  10346. MaxSize := S_L;
  10347. end;
  10348. {$ifdef x86_64}
  10349. S_LQ:
  10350. begin
  10351. { Both the lower and upper limits are set to 32-bit. If a limit
  10352. is breached, then optimisation is impossible }
  10353. LowerLimit := $FFFFFFFF;
  10354. SignedLowerLimit := $7FFFFFFF;
  10355. SignedLowerLimitBottom := -2147483648;
  10356. UpperLimit := $FFFFFFFF;
  10357. SignedUpperLimit := $7FFFFFFF;
  10358. SignedUpperLimitBottom := -2147483648;
  10359. MinSize := S_L;
  10360. MaxSize := S_L;
  10361. end;
  10362. {$endif x86_64}
  10363. else
  10364. InternalError(2020112301);
  10365. end;
  10366. TestValMin := 0;
  10367. TestValMax := LowerLimit;
  10368. TestValSignedMax := SignedLowerLimit;
  10369. TryShiftDownLimit := LowerLimit;
  10370. TryShiftDown := S_NO;
  10371. ShiftDownOverflow := False;
  10372. RegChanged := False;
  10373. BitwiseOnly := True;
  10374. OrXorUsed := False;
  10375. UpperSignedOverflow := False;
  10376. LowerSignedOverflow := False;
  10377. UpperUnsignedOverflow := False;
  10378. LowerUnsignedOverflow := False;
  10379. hp1 := p;
  10380. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10381. (hp1.typ = ait_instruction) and
  10382. (
  10383. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10384. instruction that doesn't actually contain ThisReg }
  10385. (cs_opt_level3 in current_settings.optimizerswitches) or
  10386. { This allows this Movx optimisation to work through the SETcc instructions
  10387. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10388. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10389. skip over these SETcc instructions). }
  10390. (taicpu(hp1).opcode = A_SETcc) or
  10391. RegInInstruction(ThisReg, hp1)
  10392. ) do
  10393. begin
  10394. case taicpu(hp1).opcode of
  10395. A_INC,A_DEC:
  10396. begin
  10397. { Has to be an exact match on the register }
  10398. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10399. Break;
  10400. if taicpu(hp1).opcode = A_INC then
  10401. begin
  10402. Inc(TestValMin);
  10403. Inc(TestValMax);
  10404. Inc(TestValSignedMax);
  10405. end
  10406. else
  10407. begin
  10408. Dec(TestValMin);
  10409. Dec(TestValMax);
  10410. Dec(TestValSignedMax);
  10411. end;
  10412. end;
  10413. A_TEST, A_CMP:
  10414. begin
  10415. if (
  10416. { Too high a risk of non-linear behaviour that breaks DFA
  10417. here, unless it's cmp $0,%reg, which is equivalent to
  10418. test %reg,%reg }
  10419. OrXorUsed and
  10420. (taicpu(hp1).opcode = A_CMP) and
  10421. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10422. ) or
  10423. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10424. { Has to be an exact match on the register }
  10425. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10426. (
  10427. { Permit "test %reg,%reg" }
  10428. (taicpu(hp1).opcode = A_TEST) and
  10429. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10430. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10431. ) or
  10432. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10433. { Make sure the comparison value is not smaller than the
  10434. smallest allowed signed value for the minimum size (e.g.
  10435. -128 for 8-bit) }
  10436. not (
  10437. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10438. { Is it in the negative range? }
  10439. (
  10440. (taicpu(hp1).oper[0]^.val < 0) and
  10441. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10442. )
  10443. ) then
  10444. Break;
  10445. { Check to see if the active register is used afterwards }
  10446. TransferUsedRegs(TmpUsedRegs);
  10447. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10448. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10449. begin
  10450. { Make sure the comparison or any previous instructions
  10451. hasn't pushed the test values outside of the range of
  10452. MinSize }
  10453. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10454. begin
  10455. { Exceeded lower bound but not upper bound }
  10456. Exit;
  10457. end
  10458. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10459. begin
  10460. { Size didn't exceed lower bound }
  10461. TargetSize := MinSize;
  10462. end
  10463. else
  10464. Break;
  10465. case TargetSize of
  10466. S_B:
  10467. TargetSubReg := R_SUBL;
  10468. S_W:
  10469. TargetSubReg := R_SUBW;
  10470. S_L:
  10471. TargetSubReg := R_SUBD;
  10472. else
  10473. InternalError(2021051002);
  10474. end;
  10475. if TargetSize <> MaxSize then
  10476. begin
  10477. { Update the register to its new size }
  10478. setsubreg(ThisReg, TargetSubReg);
  10479. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10480. taicpu(hp1).oper[1]^.reg := ThisReg;
  10481. taicpu(hp1).opsize := TargetSize;
  10482. { Convert the input MOVZX to a MOV if necessary }
  10483. AdjustInitialLoadAndSize;
  10484. if (InstrMax >= 0) then
  10485. begin
  10486. for Index := 0 to InstrMax do
  10487. begin
  10488. { If p_removed is true, then the original MOV/Z was removed
  10489. and removing the AND instruction may not be safe if it
  10490. appears first }
  10491. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10492. InternalError(2020112311);
  10493. if InstrList[Index].oper[0]^.typ = top_reg then
  10494. InstrList[Index].oper[0]^.reg := ThisReg;
  10495. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10496. InstrList[Index].opsize := MinSize;
  10497. end;
  10498. end;
  10499. Result := True;
  10500. end;
  10501. Exit;
  10502. end;
  10503. end;
  10504. A_SETcc:
  10505. begin
  10506. { This allows this Movx optimisation to work through the SETcc instructions
  10507. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10508. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10509. skip over these SETcc instructions). }
  10510. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10511. { Of course, break out if the current register is used }
  10512. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10513. Break
  10514. else
  10515. { We must use Continue so the instruction doesn't get added
  10516. to InstrList }
  10517. Continue;
  10518. end;
  10519. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10520. begin
  10521. if
  10522. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10523. { Has to be an exact match on the register }
  10524. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10525. (
  10526. (
  10527. (taicpu(hp1).oper[0]^.typ = top_const) and
  10528. (
  10529. (
  10530. (taicpu(hp1).opcode = A_SHL) and
  10531. (
  10532. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10533. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10534. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10535. )
  10536. ) or (
  10537. (taicpu(hp1).opcode <> A_SHL) and
  10538. (
  10539. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10540. { Is it in the negative range? }
  10541. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10542. )
  10543. )
  10544. )
  10545. ) or (
  10546. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10547. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10548. )
  10549. ) then
  10550. Break;
  10551. { Only process OR and XOR if there are only bitwise operations,
  10552. since otherwise they can too easily fool the data flow
  10553. analysis (they can cause non-linear behaviour) }
  10554. case taicpu(hp1).opcode of
  10555. A_ADD:
  10556. begin
  10557. if OrXorUsed then
  10558. { Too high a risk of non-linear behaviour that breaks DFA here }
  10559. Break
  10560. else
  10561. BitwiseOnly := False;
  10562. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10563. begin
  10564. TestValMin := TestValMin * 2;
  10565. TestValMax := TestValMax * 2;
  10566. TestValSignedMax := TestValSignedMax * 2;
  10567. end
  10568. else
  10569. begin
  10570. WorkingValue := taicpu(hp1).oper[0]^.val;
  10571. TestValMin := TestValMin + WorkingValue;
  10572. TestValMax := TestValMax + WorkingValue;
  10573. TestValSignedMax := TestValSignedMax + WorkingValue;
  10574. end;
  10575. end;
  10576. A_SUB:
  10577. begin
  10578. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10579. begin
  10580. TestValMin := 0;
  10581. TestValMax := 0;
  10582. TestValSignedMax := 0;
  10583. end
  10584. else
  10585. begin
  10586. if OrXorUsed then
  10587. { Too high a risk of non-linear behaviour that breaks DFA here }
  10588. Break
  10589. else
  10590. BitwiseOnly := False;
  10591. WorkingValue := taicpu(hp1).oper[0]^.val;
  10592. TestValMin := TestValMin - WorkingValue;
  10593. TestValMax := TestValMax - WorkingValue;
  10594. TestValSignedMax := TestValSignedMax - WorkingValue;
  10595. end;
  10596. end;
  10597. A_AND:
  10598. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10599. begin
  10600. { we might be able to go smaller if AND appears first }
  10601. if InstrMax = -1 then
  10602. case MinSize of
  10603. S_B:
  10604. ;
  10605. S_W:
  10606. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10607. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10608. begin
  10609. TryShiftDown := S_B;
  10610. TryShiftDownLimit := $FF;
  10611. end;
  10612. S_L:
  10613. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10614. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10615. begin
  10616. TryShiftDown := S_B;
  10617. TryShiftDownLimit := $FF;
  10618. end
  10619. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10620. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10621. begin
  10622. TryShiftDown := S_W;
  10623. TryShiftDownLimit := $FFFF;
  10624. end;
  10625. else
  10626. InternalError(2020112320);
  10627. end;
  10628. WorkingValue := taicpu(hp1).oper[0]^.val;
  10629. TestValMin := TestValMin and WorkingValue;
  10630. TestValMax := TestValMax and WorkingValue;
  10631. TestValSignedMax := TestValSignedMax and WorkingValue;
  10632. end;
  10633. A_OR:
  10634. begin
  10635. if not BitwiseOnly then
  10636. Break;
  10637. OrXorUsed := True;
  10638. WorkingValue := taicpu(hp1).oper[0]^.val;
  10639. TestValMin := TestValMin or WorkingValue;
  10640. TestValMax := TestValMax or WorkingValue;
  10641. TestValSignedMax := TestValSignedMax or WorkingValue;
  10642. end;
  10643. A_XOR:
  10644. begin
  10645. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10646. begin
  10647. TestValMin := 0;
  10648. TestValMax := 0;
  10649. TestValSignedMax := 0;
  10650. end
  10651. else
  10652. begin
  10653. if not BitwiseOnly then
  10654. Break;
  10655. OrXorUsed := True;
  10656. WorkingValue := taicpu(hp1).oper[0]^.val;
  10657. TestValMin := TestValMin xor WorkingValue;
  10658. TestValMax := TestValMax xor WorkingValue;
  10659. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10660. end;
  10661. end;
  10662. A_SHL:
  10663. begin
  10664. BitwiseOnly := False;
  10665. WorkingValue := taicpu(hp1).oper[0]^.val;
  10666. TestValMin := TestValMin shl WorkingValue;
  10667. TestValMax := TestValMax shl WorkingValue;
  10668. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10669. end;
  10670. A_SHR,
  10671. { The first instruction was MOVZX, so the value won't be negative }
  10672. A_SAR:
  10673. begin
  10674. if InstrMax <> -1 then
  10675. BitwiseOnly := False
  10676. else
  10677. { we might be able to go smaller if SHR appears first }
  10678. case MinSize of
  10679. S_B:
  10680. ;
  10681. S_W:
  10682. if (taicpu(hp1).oper[0]^.val >= 8) then
  10683. begin
  10684. TryShiftDown := S_B;
  10685. TryShiftDownLimit := $FF;
  10686. TryShiftDownSignedLimit := $7F;
  10687. TryShiftDownSignedLimitLower := -128;
  10688. end;
  10689. S_L:
  10690. if (taicpu(hp1).oper[0]^.val >= 24) then
  10691. begin
  10692. TryShiftDown := S_B;
  10693. TryShiftDownLimit := $FF;
  10694. TryShiftDownSignedLimit := $7F;
  10695. TryShiftDownSignedLimitLower := -128;
  10696. end
  10697. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10698. begin
  10699. TryShiftDown := S_W;
  10700. TryShiftDownLimit := $FFFF;
  10701. TryShiftDownSignedLimit := $7FFF;
  10702. TryShiftDownSignedLimitLower := -32768;
  10703. end;
  10704. else
  10705. InternalError(2020112321);
  10706. end;
  10707. WorkingValue := taicpu(hp1).oper[0]^.val;
  10708. if taicpu(hp1).opcode = A_SAR then
  10709. begin
  10710. TestValMin := SarInt64(TestValMin, WorkingValue);
  10711. TestValMax := SarInt64(TestValMax, WorkingValue);
  10712. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10713. end
  10714. else
  10715. begin
  10716. TestValMin := TestValMin shr WorkingValue;
  10717. TestValMax := TestValMax shr WorkingValue;
  10718. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10719. end;
  10720. end;
  10721. else
  10722. InternalError(2020112303);
  10723. end;
  10724. end;
  10725. (*
  10726. A_IMUL:
  10727. case taicpu(hp1).ops of
  10728. 2:
  10729. begin
  10730. if not MatchOpType(hp1, top_reg, top_reg) or
  10731. { Has to be an exact match on the register }
  10732. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10733. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10734. Break;
  10735. TestValMin := TestValMin * TestValMin;
  10736. TestValMax := TestValMax * TestValMax;
  10737. TestValSignedMax := TestValSignedMax * TestValMax;
  10738. end;
  10739. 3:
  10740. begin
  10741. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10742. { Has to be an exact match on the register }
  10743. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10744. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10745. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10746. { Is it in the negative range? }
  10747. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10748. Break;
  10749. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10750. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10751. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10752. end;
  10753. else
  10754. Break;
  10755. end;
  10756. A_IDIV:
  10757. case taicpu(hp1).ops of
  10758. 3:
  10759. begin
  10760. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10761. { Has to be an exact match on the register }
  10762. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10763. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10764. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10765. { Is it in the negative range? }
  10766. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10767. Break;
  10768. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10769. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10770. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10771. end;
  10772. else
  10773. Break;
  10774. end;
  10775. *)
  10776. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10777. begin
  10778. { If there are no instructions in between, then we might be able to make a saving }
  10779. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10780. Break;
  10781. { We have something like:
  10782. movzbw %dl,%dx
  10783. ...
  10784. movswl %dx,%edx
  10785. Change the latter to a zero-extension then enter the
  10786. A_MOVZX case branch.
  10787. }
  10788. {$ifdef x86_64}
  10789. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10790. begin
  10791. { this becomes a zero extension from 32-bit to 64-bit, but
  10792. the upper 32 bits are already zero, so just delete the
  10793. instruction }
  10794. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10795. RemoveInstruction(hp1);
  10796. Result := True;
  10797. Exit;
  10798. end
  10799. else
  10800. {$endif x86_64}
  10801. begin
  10802. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10803. taicpu(hp1).opcode := A_MOVZX;
  10804. {$ifdef x86_64}
  10805. case taicpu(hp1).opsize of
  10806. S_BQ:
  10807. begin
  10808. taicpu(hp1).opsize := S_BL;
  10809. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10810. end;
  10811. S_WQ:
  10812. begin
  10813. taicpu(hp1).opsize := S_WL;
  10814. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10815. end;
  10816. S_LQ:
  10817. begin
  10818. taicpu(hp1).opcode := A_MOV;
  10819. taicpu(hp1).opsize := S_L;
  10820. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10821. { In this instance, we need to break out because the
  10822. instruction is no longer MOVZX or MOVSXD }
  10823. Result := True;
  10824. Exit;
  10825. end;
  10826. else
  10827. ;
  10828. end;
  10829. {$endif x86_64}
  10830. Result := CompressInstructions;
  10831. Exit;
  10832. end;
  10833. end;
  10834. A_MOVZX:
  10835. begin
  10836. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10837. Break;
  10838. if (InstrMax = -1) then
  10839. begin
  10840. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10841. begin
  10842. { Optimise around i40003 }
  10843. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10844. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10845. {$ifndef x86_64}
  10846. and (
  10847. (taicpu(p).oper[0]^.typ <> top_reg) or
  10848. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10849. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10850. )
  10851. {$endif not x86_64}
  10852. then
  10853. begin
  10854. if (taicpu(p).oper[0]^.typ = top_reg) then
  10855. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10856. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10857. taicpu(p).opsize := S_BL;
  10858. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10859. RemoveInstruction(hp1);
  10860. Result := True;
  10861. Exit;
  10862. end;
  10863. end
  10864. else
  10865. begin
  10866. { Will return false if the second parameter isn't ThisReg
  10867. (can happen on -O2 and under) }
  10868. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10869. begin
  10870. { The two MOVZX instructions are adjacent, so remove the first one }
  10871. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10872. RemoveCurrentP(p);
  10873. Result := True;
  10874. Exit;
  10875. end;
  10876. Break;
  10877. end;
  10878. end;
  10879. Result := CompressInstructions;
  10880. Exit;
  10881. end;
  10882. else
  10883. { This includes ADC, SBB and IDIV }
  10884. Break;
  10885. end;
  10886. if not CheckOverflowConditions then
  10887. Break;
  10888. { Contains highest index (so instruction count - 1) }
  10889. Inc(InstrMax);
  10890. if InstrMax > High(InstrList) then
  10891. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10892. InstrList[InstrMax] := taicpu(hp1);
  10893. end;
  10894. end;
  10895. {$pop}
  10896. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10897. var
  10898. hp1 : tai;
  10899. begin
  10900. Result:=false;
  10901. if (taicpu(p).ops >= 2) and
  10902. ((taicpu(p).oper[0]^.typ = top_const) or
  10903. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10904. (taicpu(p).oper[1]^.typ = top_reg) and
  10905. ((taicpu(p).ops = 2) or
  10906. ((taicpu(p).oper[2]^.typ = top_reg) and
  10907. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10908. GetLastInstruction(p,hp1) and
  10909. MatchInstruction(hp1,A_MOV,[]) and
  10910. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10911. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10912. begin
  10913. TransferUsedRegs(TmpUsedRegs);
  10914. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10915. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10916. { change
  10917. mov reg1,reg2
  10918. imul y,reg2 to imul y,reg1,reg2 }
  10919. begin
  10920. taicpu(p).ops := 3;
  10921. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10922. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10923. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10924. RemoveInstruction(hp1);
  10925. result:=true;
  10926. end;
  10927. end;
  10928. end;
  10929. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10930. var
  10931. ThisLabel: TAsmLabel;
  10932. begin
  10933. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10934. ThisLabel.decrefs;
  10935. taicpu(p).condition := C_None;
  10936. taicpu(p).opcode := A_RET;
  10937. taicpu(p).is_jmp := false;
  10938. taicpu(p).ops := taicpu(ret_p).ops;
  10939. case taicpu(ret_p).ops of
  10940. 0:
  10941. taicpu(p).clearop(0);
  10942. 1:
  10943. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10944. else
  10945. internalerror(2016041301);
  10946. end;
  10947. { If the original label is now dead, it might turn out that the label
  10948. immediately follows p. As a result, everything beyond it, which will
  10949. be just some final register configuration and a RET instruction, is
  10950. now dead code. [Kit] }
  10951. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10952. running RemoveDeadCodeAfterJump for each RET instruction, because
  10953. this optimisation rarely happens and most RETs appear at the end of
  10954. routines where there is nothing that can be stripped. [Kit] }
  10955. if not ThisLabel.is_used then
  10956. RemoveDeadCodeAfterJump(p);
  10957. end;
  10958. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10959. var
  10960. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10961. Unconditional, PotentialModified: Boolean;
  10962. OperPtr: POper;
  10963. NewRef: TReference;
  10964. InstrList: array of taicpu;
  10965. InstrMax, Index: Integer;
  10966. const
  10967. {$ifdef DEBUG_AOPTCPU}
  10968. SNoFlags: shortstring = ' so the flags aren''t modified';
  10969. {$else DEBUG_AOPTCPU}
  10970. SNoFlags = '';
  10971. {$endif DEBUG_AOPTCPU}
  10972. begin
  10973. Result:=false;
  10974. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10975. begin
  10976. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10977. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10978. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10979. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10980. GetNextInstruction(hp1, hp2) and
  10981. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10982. { Change from: To:
  10983. set(C) %reg j(~C) label
  10984. test %reg,%reg/cmp $0,%reg
  10985. je label
  10986. set(C) %reg j(C) label
  10987. test %reg,%reg/cmp $0,%reg
  10988. jne label
  10989. (Also do something similar with sete/setne instead of je/jne)
  10990. }
  10991. begin
  10992. { Before we do anything else, we need to check the instructions
  10993. in between SETcc and TEST to make sure they don't modify the
  10994. FLAGS register - if -O2 or under, there won't be any
  10995. instructions between SET and TEST }
  10996. TransferUsedRegs(TmpUsedRegs);
  10997. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10998. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10999. begin
  11000. next := p;
  11001. SetLength(InstrList, 0);
  11002. InstrMax := -1;
  11003. PotentialModified := False;
  11004. { Make a note of every instruction that modifies the FLAGS
  11005. register }
  11006. while GetNextInstruction(next, next) and (next <> hp1) do
  11007. begin
  11008. if next.typ <> ait_instruction then
  11009. { GetNextInstructionUsingReg should have returned False }
  11010. InternalError(2021051701);
  11011. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  11012. begin
  11013. case taicpu(next).opcode of
  11014. A_SETcc,
  11015. A_CMOVcc,
  11016. A_Jcc:
  11017. begin
  11018. if PotentialModified then
  11019. { Not safe because the flags were modified earlier }
  11020. Exit
  11021. else
  11022. { Condition is the same as the initial SETcc, so this is safe
  11023. (don't add to instruction list though) }
  11024. Continue;
  11025. end;
  11026. A_ADD:
  11027. begin
  11028. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11029. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11030. (taicpu(next).oper[1]^.typ <> top_reg) or
  11031. { Must write to a register }
  11032. (taicpu(next).oper[0]^.typ = top_ref) then
  11033. { Require a constant or a register }
  11034. Exit;
  11035. PotentialModified := True;
  11036. end;
  11037. A_SUB:
  11038. begin
  11039. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11040. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11041. (taicpu(next).oper[1]^.typ <> top_reg) or
  11042. { Must write to a register }
  11043. (taicpu(next).oper[0]^.typ <> top_const) or
  11044. (taicpu(next).oper[0]^.val = $80000000) then
  11045. { Can't subtract a register with LEA - also
  11046. check that the value isn't -2^31, as this
  11047. can't be negated }
  11048. Exit;
  11049. PotentialModified := True;
  11050. end;
  11051. A_SAL,
  11052. A_SHL:
  11053. begin
  11054. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11055. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11056. (taicpu(next).oper[1]^.typ <> top_reg) or
  11057. { Must write to a register }
  11058. (taicpu(next).oper[0]^.typ <> top_const) or
  11059. (taicpu(next).oper[0]^.val < 0) or
  11060. (taicpu(next).oper[0]^.val > 3) then
  11061. Exit;
  11062. PotentialModified := True;
  11063. end;
  11064. A_IMUL:
  11065. begin
  11066. if (taicpu(next).ops <> 3) or
  11067. (taicpu(next).oper[1]^.typ <> top_reg) or
  11068. { Must write to a register }
  11069. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11070. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11071. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11072. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11073. Exit
  11074. else
  11075. PotentialModified := True;
  11076. end;
  11077. else
  11078. { Don't know how to change this, so abort }
  11079. Exit;
  11080. end;
  11081. { Contains highest index (so instruction count - 1) }
  11082. Inc(InstrMax);
  11083. if InstrMax > High(InstrList) then
  11084. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11085. InstrList[InstrMax] := taicpu(next);
  11086. end;
  11087. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11088. end;
  11089. if not Assigned(next) or (next <> hp1) then
  11090. { It should be equal to hp1 }
  11091. InternalError(2021051702);
  11092. { Cycle through each instruction and check to see if we can
  11093. change them to versions that don't modify the flags }
  11094. if (InstrMax >= 0) then
  11095. begin
  11096. for Index := 0 to InstrMax do
  11097. case InstrList[Index].opcode of
  11098. A_ADD:
  11099. begin
  11100. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11101. InstrList[Index].opcode := A_LEA;
  11102. reference_reset(NewRef, 1, []);
  11103. NewRef.base := InstrList[Index].oper[1]^.reg;
  11104. if InstrList[Index].oper[0]^.typ = top_reg then
  11105. begin
  11106. NewRef.index := InstrList[Index].oper[0]^.reg;
  11107. NewRef.scalefactor := 1;
  11108. end
  11109. else
  11110. NewRef.offset := InstrList[Index].oper[0]^.val;
  11111. InstrList[Index].loadref(0, NewRef);
  11112. end;
  11113. A_SUB:
  11114. begin
  11115. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11116. InstrList[Index].opcode := A_LEA;
  11117. reference_reset(NewRef, 1, []);
  11118. NewRef.base := InstrList[Index].oper[1]^.reg;
  11119. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11120. InstrList[Index].loadref(0, NewRef);
  11121. end;
  11122. A_SHL,
  11123. A_SAL:
  11124. begin
  11125. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11126. InstrList[Index].opcode := A_LEA;
  11127. reference_reset(NewRef, 1, []);
  11128. NewRef.index := InstrList[Index].oper[1]^.reg;
  11129. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11130. InstrList[Index].loadref(0, NewRef);
  11131. end;
  11132. A_IMUL:
  11133. begin
  11134. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11135. InstrList[Index].opcode := A_LEA;
  11136. reference_reset(NewRef, 1, []);
  11137. NewRef.index := InstrList[Index].oper[1]^.reg;
  11138. case InstrList[Index].oper[0]^.val of
  11139. 2, 4, 8:
  11140. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11141. else {3, 5 and 9}
  11142. begin
  11143. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11144. NewRef.base := InstrList[Index].oper[1]^.reg;
  11145. end;
  11146. end;
  11147. InstrList[Index].loadref(0, NewRef);
  11148. end;
  11149. else
  11150. InternalError(2021051710);
  11151. end;
  11152. end;
  11153. { Mark the FLAGS register as used across this whole block }
  11154. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11155. end;
  11156. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11157. JumpC := taicpu(hp2).condition;
  11158. Unconditional := False;
  11159. if conditions_equal(JumpC, C_E) then
  11160. SetC := inverse_cond(taicpu(p).condition)
  11161. else if conditions_equal(JumpC, C_NE) then
  11162. SetC := taicpu(p).condition
  11163. else
  11164. { We've got something weird here (and inefficent) }
  11165. begin
  11166. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11167. SetC := C_NONE;
  11168. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11169. if condition_in(C_AE, JumpC) then
  11170. Unconditional := True
  11171. else
  11172. { Not sure what to do with this jump - drop out }
  11173. Exit;
  11174. end;
  11175. RemoveInstruction(hp1);
  11176. if Unconditional then
  11177. MakeUnconditional(taicpu(hp2))
  11178. else
  11179. begin
  11180. if SetC = C_NONE then
  11181. InternalError(2018061402);
  11182. taicpu(hp2).SetCondition(SetC);
  11183. end;
  11184. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11185. TmpUsedRegs }
  11186. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11187. begin
  11188. RemoveCurrentp(p, hp2);
  11189. if taicpu(hp2).opcode = A_SETcc then
  11190. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11191. else
  11192. begin
  11193. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11194. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11195. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11196. end;
  11197. end
  11198. else
  11199. if taicpu(hp2).opcode = A_SETcc then
  11200. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11201. else
  11202. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11203. Result := True;
  11204. end
  11205. else if
  11206. { Make sure the instructions are adjacent }
  11207. (
  11208. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11209. GetNextInstruction(p, hp1)
  11210. ) and
  11211. MatchInstruction(hp1, A_MOV, [S_B]) and
  11212. { Writing to memory is allowed }
  11213. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11214. begin
  11215. {
  11216. Watch out for sequences such as:
  11217. set(c)b %regb
  11218. movb %regb,(ref)
  11219. movb $0,1(ref)
  11220. movb $0,2(ref)
  11221. movb $0,3(ref)
  11222. Much more efficient to turn it into:
  11223. movl $0,%regl
  11224. set(c)b %regb
  11225. movl %regl,(ref)
  11226. Or:
  11227. set(c)b %regb
  11228. movzbl %regb,%regl
  11229. movl %regl,(ref)
  11230. }
  11231. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11232. GetNextInstruction(hp1, hp2) and
  11233. MatchInstruction(hp2, A_MOV, [S_B]) and
  11234. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11235. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11236. begin
  11237. { Don't do anything else except set Result to True }
  11238. end
  11239. else
  11240. begin
  11241. if taicpu(p).oper[0]^.typ = top_reg then
  11242. begin
  11243. TransferUsedRegs(TmpUsedRegs);
  11244. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11245. end;
  11246. { If it's not a register, it's a memory address }
  11247. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11248. begin
  11249. { Even if the register is still in use, we can minimise the
  11250. pipeline stall by changing the MOV into another SETcc. }
  11251. taicpu(hp1).opcode := A_SETcc;
  11252. taicpu(hp1).condition := taicpu(p).condition;
  11253. if taicpu(hp1).oper[1]^.typ = top_ref then
  11254. begin
  11255. { Swapping the operand pointers like this is probably a
  11256. bit naughty, but it is far faster than using loadoper
  11257. to transfer the reference from oper[1] to oper[0] if
  11258. you take into account the extra procedure calls and
  11259. the memory allocation and deallocation required }
  11260. OperPtr := taicpu(hp1).oper[1];
  11261. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11262. taicpu(hp1).oper[0] := OperPtr;
  11263. end
  11264. else
  11265. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11266. taicpu(hp1).clearop(1);
  11267. taicpu(hp1).ops := 1;
  11268. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11269. end
  11270. else
  11271. begin
  11272. if taicpu(hp1).oper[1]^.typ = top_reg then
  11273. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11274. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11275. RemoveInstruction(hp1);
  11276. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11277. end
  11278. end;
  11279. Result := True;
  11280. end;
  11281. end;
  11282. end;
  11283. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11284. var
  11285. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11286. TargetReg: TRegister;
  11287. condition, inverted_condition: TAsmCond;
  11288. FoundMOV: Boolean;
  11289. begin
  11290. Result := False;
  11291. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11292. create the most optimial instructions possible due to limited
  11293. register availability, and there are situations where two
  11294. complementary "simple" CMOV blocks are created which, after the fact
  11295. can be merged into a "double" block. For example:
  11296. movw $257,%ax
  11297. movw $2,%r8w
  11298. xorl r9d,%r9d
  11299. testw $16,18(%rcx)
  11300. cmovew %ax,%dx
  11301. cmovew %r8w,%bx
  11302. cmovel %r9d,%r14d
  11303. movw $1283,%ax
  11304. movw $4,%r8w
  11305. movl $9,%r9d
  11306. cmovnew %ax,%dx
  11307. cmovnew %r8w,%bx
  11308. cmovnel %r9d,%r14d
  11309. The CMOVNE instructions at the end can be removed, and the
  11310. destination registers copied into the MOV instructions directly
  11311. above them, before finally being moved to before the first CMOVE
  11312. instructions, to produce:
  11313. movw $257,%ax
  11314. movw $2,%r8w
  11315. xorl r9d,%r9d
  11316. testw $16,18(%rcx)
  11317. movw $1283,%dx
  11318. movw $4,%bx
  11319. movl $9,%r14d
  11320. cmovew %ax,%dx
  11321. cmovew %r8w,%bx
  11322. cmovel %r9d,%r14d
  11323. Which can then be later optimised to:
  11324. movw $257,%ax
  11325. movw $2,%r8w
  11326. xorl r9d,%r9d
  11327. movw $1283,%dx
  11328. movw $4,%bx
  11329. movl $9,%r14d
  11330. testw $16,18(%rcx)
  11331. cmovew %ax,%dx
  11332. cmovew %r8w,%bx
  11333. cmovel %r9d,%r14d
  11334. }
  11335. TargetReg := taicpu(hp1).oper[1]^.reg;
  11336. condition := taicpu(hp1).condition;
  11337. inverted_condition := inverse_cond(condition);
  11338. pFirstMov := nil;
  11339. pLastMov := nil;
  11340. pCMOV := nil;
  11341. if (p.typ = ait_instruction) then
  11342. pCond := p
  11343. else if not GetNextInstruction(p, pCond) then
  11344. InternalError(2024012501);
  11345. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11346. { We should get the CMP or TEST instructeion }
  11347. InternalError(2024012502);
  11348. if (
  11349. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11350. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11351. ) then
  11352. begin
  11353. { We have to tread carefully here, hence why we're not using
  11354. GetNextInstructionUsingReg... we can only accept MOV and other
  11355. CMOV instructions. Anything else and we must drop out}
  11356. hp2 := hp1;
  11357. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11358. begin
  11359. if (hp2.typ <> ait_instruction) then
  11360. Exit;
  11361. case taicpu(hp2).opcode of
  11362. A_MOV:
  11363. begin
  11364. if not Assigned(pFirstMov) then
  11365. pFirstMov := hp2;
  11366. pLastMOV := hp2;
  11367. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11368. { Something different - drop out }
  11369. Exit;
  11370. { Otherwise, leave it for now }
  11371. end;
  11372. A_CMOVcc:
  11373. begin
  11374. if taicpu(hp2).condition = inverted_condition then
  11375. begin
  11376. { We found what we're looking for }
  11377. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11378. begin
  11379. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11380. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11381. begin
  11382. pCMOV := hp2;
  11383. Break;
  11384. end
  11385. else
  11386. { Unsafe reference - drop out }
  11387. Exit;
  11388. end;
  11389. end
  11390. else if taicpu(hp2).condition <> condition then
  11391. { Something weird - drop out }
  11392. Exit;
  11393. end;
  11394. else
  11395. { Invalid }
  11396. Exit;
  11397. end;
  11398. end;
  11399. if not Assigned(pCMOV) then
  11400. { No complementary CMOV found }
  11401. Exit;
  11402. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11403. begin
  11404. { Don't need to do anything special or search for a matching MOV }
  11405. Asml.Remove(pCMOV);
  11406. if RegInInstruction(TargetReg, pCond) then
  11407. { Make sure we don't overwrite the register if it's being used in the condition }
  11408. Asml.InsertAfter(pCMOV, pCond)
  11409. else
  11410. Asml.InsertBefore(pCMOV, pCond);
  11411. taicpu(pCMOV).opcode := A_MOV;
  11412. taicpu(pCMOV).condition := C_None;
  11413. { Don't need to worry about allocating new registers in these cases }
  11414. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11415. Result := True;
  11416. Exit;
  11417. end
  11418. else
  11419. begin
  11420. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11421. FoundMOV := False;
  11422. { Search for the MOV that sets the target register }
  11423. hp2 := pFirstMov;
  11424. repeat
  11425. if (taicpu(hp2).opcode = A_MOV) and
  11426. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11427. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11428. begin
  11429. { Change the destination }
  11430. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11431. if not FoundMOV then
  11432. begin
  11433. FoundMOV := True;
  11434. { Make sure the register is allocated }
  11435. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11436. end;
  11437. hp1 := tai(hp2.Previous);
  11438. Asml.Remove(hp2);
  11439. if RegInInstruction(TargetReg, pCond) then
  11440. { Make sure we don't overwrite the register if it's being used in the condition }
  11441. Asml.InsertAfter(hp2, pCond)
  11442. else
  11443. Asml.InsertBefore(hp2, pCond);
  11444. if (hp2 = pLastMov) then
  11445. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11446. Break;
  11447. hp2 := hp1;
  11448. end;
  11449. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11450. if FoundMOV then
  11451. { Delete the CMOV }
  11452. RemoveInstruction(pCMOV)
  11453. else
  11454. begin
  11455. { If no MOV was found, we have to actually move and transmute the CMOV }
  11456. Asml.Remove(pCMOV);
  11457. if RegInInstruction(TargetReg, pCond) then
  11458. { Make sure we don't overwrite the register if it's being used in the condition }
  11459. Asml.InsertAfter(pCMOV, pCond)
  11460. else
  11461. Asml.InsertBefore(pCMOV, pCond);
  11462. taicpu(pCMOV).opcode := A_MOV;
  11463. taicpu(pCMOV).condition := C_None;
  11464. end;
  11465. Result := True;
  11466. Exit;
  11467. end;
  11468. end;
  11469. end;
  11470. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11471. var
  11472. hp1, hp2, pCond: tai;
  11473. begin
  11474. Result := False;
  11475. { Search ahead for CMOV instructions }
  11476. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11477. begin
  11478. hp1 := p;
  11479. hp2 := p;
  11480. pCond := nil; { To prevent compiler warnings }
  11481. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11482. DEFAULTFLAGS }
  11483. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11484. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11485. pCond := p;
  11486. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11487. begin
  11488. if (hp1.typ <> ait_instruction) then
  11489. { Break out on markers and labels etc. }
  11490. Break;
  11491. case taicpu(hp1).opcode of
  11492. A_MOV:
  11493. { Ignore regular MOVs unless they are obviously not related
  11494. to a CMOV block }
  11495. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11496. Break;
  11497. A_CMOVcc:
  11498. if TryCmpCMovOpts(pCond, hp1) then
  11499. begin
  11500. hp1 := hp2;
  11501. { p itself isn't changed, and we're still inside a
  11502. while loop to catch subsequent CMOVs, so just flag
  11503. a new iteration }
  11504. Include(OptsToCheck, aoc_ForceNewIteration);
  11505. Continue;
  11506. end;
  11507. else
  11508. { Drop out if we find anything else }
  11509. Break;
  11510. end;
  11511. hp2 := hp1;
  11512. end;
  11513. end;
  11514. end;
  11515. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11516. var
  11517. hp1, hp2, pCond: tai;
  11518. SourceReg, TargetReg: TRegister;
  11519. begin
  11520. Result := False;
  11521. { In some situations, we end up with an inefficient arrangement of
  11522. instructions in the form of:
  11523. or %reg1,%reg2
  11524. (%reg1 deallocated)
  11525. test %reg2,%reg2
  11526. mov x,%reg2
  11527. we may be able to swap and rearrange the registers to produce:
  11528. or %reg2,%reg1
  11529. mov x,%reg2
  11530. test %reg1,%reg1
  11531. (%reg1 deallocated)
  11532. }
  11533. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11534. (taicpu(p).oper[1]^.typ = top_reg) and
  11535. (
  11536. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11537. MatchOperand(taicpu(p).oper[0]^, -1)
  11538. ) and
  11539. GetNextInstruction(p, hp1) and
  11540. MatchInstruction(hp1, A_MOV, []) and
  11541. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11542. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11543. begin
  11544. TargetReg := taicpu(p).oper[1]^.reg;
  11545. { Now look backwards to find a simple commutative operation: ADD,
  11546. IMUL (2-register version), OR, AND or XOR - whose destination
  11547. register is the same as TEST }
  11548. hp2 := p;
  11549. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11550. if RegInInstruction(TargetReg, hp2) then
  11551. begin
  11552. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11553. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11554. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11555. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11556. begin
  11557. SourceReg := taicpu(hp2).oper[0]^.reg;
  11558. if
  11559. { Make sure the MOV doesn't use the other register }
  11560. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11561. { And make sure the source register is not used afterwards }
  11562. not RegInUsedRegs(SourceReg, UsedRegs) then
  11563. begin
  11564. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11565. taicpu(hp2).oper[0]^.reg := TargetReg;
  11566. taicpu(hp2).oper[1]^.reg := SourceReg;
  11567. if taicpu(p).oper[0]^.typ = top_reg then
  11568. taicpu(p).oper[0]^.reg := SourceReg;
  11569. taicpu(p).oper[1]^.reg := SourceReg;
  11570. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11571. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11572. Include(OptsToCheck, aoc_ForceNewIteration);
  11573. { We can still check the following optimisations since
  11574. the instruction is still a TEST }
  11575. end;
  11576. end;
  11577. Break;
  11578. end;
  11579. end;
  11580. { Search ahead3 for CMOV instructions }
  11581. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11582. begin
  11583. hp1 := p;
  11584. hp2 := p;
  11585. pCond := nil; { To prevent compiler warnings }
  11586. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11587. DEFAULTFLAGS }
  11588. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11589. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11590. pCond := p;
  11591. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11592. begin
  11593. if (hp1.typ <> ait_instruction) then
  11594. { Break out on markers and labels etc. }
  11595. Break;
  11596. case taicpu(hp1).opcode of
  11597. A_MOV:
  11598. { Ignore regular MOVs unless they are obviously not related
  11599. to a CMOV block }
  11600. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11601. Break;
  11602. A_CMOVcc:
  11603. if TryCmpCMovOpts(pCond, hp1) then
  11604. begin
  11605. hp1 := hp2;
  11606. { p itself isn't changed, and we're still inside a
  11607. while loop to catch subsequent CMOVs, so just flag
  11608. a new iteration }
  11609. Include(OptsToCheck, aoc_ForceNewIteration);
  11610. Continue;
  11611. end;
  11612. else
  11613. { Drop out if we find anything else }
  11614. Break;
  11615. end;
  11616. hp2 := hp1;
  11617. end;
  11618. end;
  11619. end;
  11620. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11621. var
  11622. hp1: tai;
  11623. Count: Integer;
  11624. OrigLabel: TAsmLabel;
  11625. begin
  11626. result := False;
  11627. { Sometimes, the optimisations below can permit this }
  11628. RemoveDeadCodeAfterJump(p);
  11629. 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
  11630. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11631. begin
  11632. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11633. { Also a side-effect of optimisations }
  11634. if CollapseZeroDistJump(p, OrigLabel) then
  11635. begin
  11636. Result := True;
  11637. Exit;
  11638. end;
  11639. hp1 := GetLabelWithSym(OrigLabel);
  11640. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11641. begin
  11642. if taicpu(hp1).opcode = A_RET then
  11643. begin
  11644. {
  11645. change
  11646. jmp .L1
  11647. ...
  11648. .L1:
  11649. ret
  11650. into
  11651. ret
  11652. }
  11653. begin
  11654. ConvertJumpToRET(p, hp1);
  11655. result:=true;
  11656. end;
  11657. end
  11658. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11659. not (cs_opt_size in current_settings.optimizerswitches) and
  11660. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11661. begin
  11662. Result := True;
  11663. Exit;
  11664. end;
  11665. end;
  11666. end;
  11667. end;
  11668. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11669. begin
  11670. Result := assigned(p) and
  11671. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11672. (taicpu(p).oper[1]^.typ = top_reg) and
  11673. (
  11674. (taicpu(p).oper[0]^.typ = top_reg) or
  11675. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11676. it is not expected that this can cause a seg. violation }
  11677. (
  11678. (taicpu(p).oper[0]^.typ = top_ref) and
  11679. { TODO: Can we detect which references become constants at this
  11680. stage so we don't have to do a blanket ban? }
  11681. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11682. (
  11683. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11684. (
  11685. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11686. not RefModified and
  11687. { If the reference also appears in the condition, then we know it's safe, otherwise
  11688. any kind of access violation would have occurred already }
  11689. Assigned(cond_p) and
  11690. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11691. (cond_p.typ = ait_instruction) and
  11692. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11693. { Just consider 2-operand comparison instructions for now to be safe }
  11694. (taicpu(cond_p).ops = 2) and
  11695. (
  11696. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11697. (
  11698. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11699. { Don't risk identical registers but different offsets, as we may have constructs
  11700. such as buffer streams with things like length fields that indicate whether
  11701. any more data follows. And there are probably some contrived examples where
  11702. writing to offsets behind the one being read also lead to access violations }
  11703. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11704. (
  11705. { Check that we're not modifying a register that appears in the reference }
  11706. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11707. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11708. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11709. )
  11710. )
  11711. )
  11712. )
  11713. )
  11714. )
  11715. );
  11716. end;
  11717. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11718. begin
  11719. { Update integer registers, ignoring deallocations }
  11720. repeat
  11721. while assigned(p) and
  11722. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11723. (p.typ = ait_label) or
  11724. ((p.typ = ait_marker) and
  11725. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11726. p := tai(p.next);
  11727. while assigned(p) and
  11728. (p.typ=ait_RegAlloc) Do
  11729. begin
  11730. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11731. begin
  11732. case tai_regalloc(p).ratype of
  11733. ra_alloc :
  11734. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11735. else
  11736. ;
  11737. end;
  11738. end;
  11739. p := tai(p.next);
  11740. end;
  11741. until not(assigned(p)) or
  11742. (not(p.typ in SkipInstr) and
  11743. not((p.typ = ait_label) and
  11744. labelCanBeSkipped(tai_label(p))));
  11745. end;
  11746. {$ifndef 8086}
  11747. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11748. begin
  11749. Result := False;
  11750. EndJump := nil;
  11751. BlockStop := nil;
  11752. while (BlockStart <> fOptimizer.BlockEnd) and
  11753. { stop on labels }
  11754. (BlockStart.typ <> ait_label) do
  11755. begin
  11756. { Keep track of all integer registers that are used }
  11757. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11758. if BlockStart.typ = ait_instruction then
  11759. begin
  11760. if (taicpu(BlockStart).opcode = A_JMP) then
  11761. begin
  11762. if not IsJumpToLabel(taicpu(BlockStart)) or
  11763. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11764. Exit;
  11765. EndJump := BlockStart;
  11766. Break;
  11767. end
  11768. { Check to see if we have a valid MOV instruction instead }
  11769. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11770. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11771. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11772. begin
  11773. Exit;
  11774. end
  11775. else
  11776. { This will be a valid MOV }
  11777. fAllocationRange := BlockStart;
  11778. end;
  11779. OneBeforeBlock := BlockStart;
  11780. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11781. end;
  11782. if (BlockStart = fOptimizer.BlockEnd) then
  11783. Exit;
  11784. BlockStop := BlockStart;
  11785. Result := True;
  11786. end;
  11787. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11788. var
  11789. hp1: tai;
  11790. RefModified: Boolean;
  11791. begin
  11792. Result := 0;
  11793. hp1 := BlockStart;
  11794. RefModified := False; { As long as the condition is inverted, this can be reset }
  11795. while assigned(hp1) and
  11796. (hp1 <> BlockStop) do
  11797. begin
  11798. case hp1.typ of
  11799. ait_instruction:
  11800. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11801. begin
  11802. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11803. begin
  11804. Inc(Result);
  11805. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11806. Assigned(fCondition) and
  11807. { Will have 2 operands }
  11808. (
  11809. (
  11810. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11811. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11812. ) or
  11813. (
  11814. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11815. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11816. )
  11817. ) then
  11818. { It is no longer safe to use the reference in the condition.
  11819. this prevents problems such as:
  11820. mov (%reg),%reg
  11821. mov (%reg),...
  11822. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11823. (fixes #40165)
  11824. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11825. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11826. }
  11827. RefModified := True;
  11828. end
  11829. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11830. { CMOV with constants grows the code size }
  11831. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11832. begin
  11833. { Register was reserved by TryCMOVConst and
  11834. stored on ConstRegs }
  11835. end
  11836. else
  11837. begin
  11838. Result := -1;
  11839. Exit;
  11840. end;
  11841. end
  11842. else
  11843. begin
  11844. Result := -1;
  11845. Exit;
  11846. end;
  11847. else
  11848. { Most likely an align };
  11849. end;
  11850. fOptimizer.GetNextInstruction(hp1, hp1);
  11851. end;
  11852. end;
  11853. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11854. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11855. (this is done as a separate stage because the double types are extensions of the branching type,
  11856. but we can't discount the conditional jump until the last step) }
  11857. procedure EvaluateBranchingType;
  11858. begin
  11859. Inc(CMOVScore);
  11860. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11861. { Too many instructions to be worthwhile }
  11862. fState := tsInvalid;
  11863. end;
  11864. var
  11865. hp1: tai;
  11866. Count: Integer;
  11867. begin
  11868. { Table of valid CMOV block types
  11869. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11870. ---------- --------- --------- --------- --------- ---------
  11871. tsSimple X Yes X X X
  11872. tsDetour = 1st X X X X
  11873. tsBranching <> Mid Yes X X X
  11874. tsDouble End-label Yes * Yes X Yes
  11875. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11876. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11877. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11878. * Only one reference allowed
  11879. }
  11880. hp1 := nil; { To prevent compiler warnings }
  11881. Optimizer.CopyUsedRegs(RegisterTracking);
  11882. fOptimizer := Optimizer;
  11883. fLabel := AFirstLabel;
  11884. CMOVScore := 0;
  11885. ConstCount := 0;
  11886. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11887. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11888. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11889. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11890. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11891. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11892. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11893. fInsertionPoint := p_initialjump;
  11894. fCondition := nil;
  11895. fInitialJump := p_initialjump;
  11896. fFirstMovBlock := p_initialmov;
  11897. fFirstMovBlockStop := nil;
  11898. fSecondJump := nil;
  11899. fSecondMovBlock := nil;
  11900. fSecondMovBlockStop := nil;
  11901. fMidLabel := nil;
  11902. fSecondJump := nil;
  11903. fSecondMovBlock := nil;
  11904. fEndLabel := nil;
  11905. fAllocationRange := nil;
  11906. { Assume it all goes horribly wrong! }
  11907. fState := tsInvalid;
  11908. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11909. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11910. MatchInstruction(fCondition, [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
  11911. begin
  11912. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11913. for Count := 0 to 1 do
  11914. with taicpu(fCondition).oper[Count]^ do
  11915. case typ of
  11916. top_reg:
  11917. if getregtype(reg) = R_INTREGISTER then
  11918. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11919. top_ref:
  11920. begin
  11921. if
  11922. {$ifdef x86_64}
  11923. (ref^.base <> NR_RIP) and
  11924. {$endif x86_64}
  11925. (ref^.base <> NR_NO) then
  11926. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11927. if (ref^.index <> NR_NO) then
  11928. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11929. end
  11930. else
  11931. ;
  11932. end;
  11933. { When inserting instructions before hp_prev, try to insert them
  11934. before the allocation of the FLAGS register }
  11935. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11936. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11937. { If not found, set it equal to the condition so it's something sensible }
  11938. fInsertionPoint := fCondition;
  11939. { When dealing with a comparison against zero, take note of the
  11940. instruction before it to see if we can move instructions further
  11941. back in order to benefit PostPeepholeOptTestOr.
  11942. }
  11943. if (
  11944. (
  11945. (taicpu(fCondition).opcode = A_CMP) and
  11946. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11947. ) or
  11948. (
  11949. (taicpu(fCondition).opcode = A_TEST) and
  11950. (
  11951. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11952. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11953. )
  11954. )
  11955. ) and
  11956. Optimizer.GetLastInstruction(fCondition, hp1) then
  11957. begin
  11958. { These instructions set the zero flag if the result is zero }
  11959. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11960. begin
  11961. fInsertionPoint := hp1;
  11962. { Also mark all the registers in this previous instruction
  11963. as 'in use', even if they've just been deallocated }
  11964. for Count := 0 to 1 do
  11965. with taicpu(hp1).oper[Count]^ do
  11966. case typ of
  11967. top_reg:
  11968. if getregtype(reg) = R_INTREGISTER then
  11969. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11970. top_ref:
  11971. begin
  11972. if
  11973. {$ifdef x86_64}
  11974. (ref^.base <> NR_RIP) and
  11975. {$endif x86_64}
  11976. (ref^.base <> NR_NO) then
  11977. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11978. if (ref^.index <> NR_NO) then
  11979. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11980. end
  11981. else
  11982. ;
  11983. end;
  11984. end;
  11985. end;
  11986. end
  11987. else
  11988. fCondition := nil;
  11989. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11990. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11991. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11992. { If not found, set it equal to p so it's something sensible }
  11993. fInsertionPoint := hp1;
  11994. hp1 := p_initialmov;
  11995. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  11996. Exit;
  11997. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  11998. if (hp1.typ <> ait_label) then { should be on a jump }
  11999. begin
  12000. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  12001. { Need a label afterwards }
  12002. Exit;
  12003. end
  12004. else
  12005. fMidLabel := hp1;
  12006. if tai_label(fMidLabel).labsym <> AFirstLabel then
  12007. { Not the correct label }
  12008. fMidLabel := nil;
  12009. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  12010. { If there's neither a 2nd jump nor correct label, then it's invalid
  12011. (see above table) }
  12012. Exit;
  12013. { Analyse the first block of MOVs more closely }
  12014. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  12015. if Assigned(fSecondJump) then
  12016. begin
  12017. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  12018. begin
  12019. fState := tsDetour
  12020. end
  12021. else
  12022. begin
  12023. { Need the correct mid-label for this one }
  12024. if not Assigned(fMidLabel) then
  12025. Exit;
  12026. fState := tsBranching;
  12027. end;
  12028. end
  12029. else
  12030. { No jump. but mid-label is present }
  12031. fState := tsSimple;
  12032. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  12033. begin
  12034. { Invalid or too many instructions to be worthwhile }
  12035. fState := tsInvalid;
  12036. Exit;
  12037. end;
  12038. { check further for
  12039. jCC xxx
  12040. <several movs 1>
  12041. jmp yyy
  12042. xxx:
  12043. <several movs 2>
  12044. yyy:
  12045. etc.
  12046. }
  12047. if (fState = tsBranching) and
  12048. { Estimate for required savings for extra jump }
  12049. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12050. { Only one reference is allowed for double blocks }
  12051. (AFirstLabel.getrefs = 1) then
  12052. begin
  12053. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12054. fSecondMovBlock := hp1;
  12055. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12056. begin
  12057. EvaluateBranchingType;
  12058. Exit;
  12059. end;
  12060. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12061. if (hp1.typ <> ait_label) then { should be on a jump }
  12062. begin
  12063. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12064. begin
  12065. { Need a label afterwards }
  12066. EvaluateBranchingType;
  12067. Exit;
  12068. end;
  12069. end
  12070. else
  12071. fEndLabel := hp1;
  12072. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12073. { Second jump doesn't go to the end }
  12074. fEndLabel := nil;
  12075. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12076. begin
  12077. { If there's neither a 3rd jump nor correct end label, then it's
  12078. not a invalid double block, but is a valid single branching
  12079. block (see above table) }
  12080. EvaluateBranchingType;
  12081. Exit;
  12082. end;
  12083. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12084. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12085. { Invalid or too many instructions to be worthwhile }
  12086. Exit;
  12087. Inc(CMOVScore, Count);
  12088. if Assigned(fThirdJump) then
  12089. begin
  12090. if not Assigned(fSecondJump) then
  12091. fState := tsDoubleSecondBranching
  12092. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12093. fState := tsDoubleBranchSame
  12094. else
  12095. fState := tsDoubleBranchDifferent;
  12096. end
  12097. else
  12098. fState := tsDouble;
  12099. end;
  12100. if fState = tsBranching then
  12101. EvaluateBranchingType;
  12102. end;
  12103. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12104. new register to store the constant }
  12105. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12106. var
  12107. RegSize: TSubRegister;
  12108. CurrentVal: TCGInt;
  12109. ANewReg: TRegister;
  12110. X: ShortInt;
  12111. begin
  12112. Result := False;
  12113. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12114. Exit;
  12115. if ConstCount >= MAX_CMOV_REGISTERS then
  12116. { Arrays are full }
  12117. Exit;
  12118. { Remember that CMOV can't encode 8-bit registers }
  12119. case taicpu(p).opsize of
  12120. S_W:
  12121. RegSize := R_SUBW;
  12122. S_L:
  12123. RegSize := R_SUBD;
  12124. {$ifdef x86_64}
  12125. S_Q:
  12126. RegSize := R_SUBQ;
  12127. {$endif x86_64}
  12128. else
  12129. InternalError(2021100401);
  12130. end;
  12131. { See if the value has already been reserved for another CMOV instruction }
  12132. CurrentVal := taicpu(p).oper[0]^.val;
  12133. for X := 0 to ConstCount - 1 do
  12134. if ConstVals[X] = CurrentVal then
  12135. begin
  12136. ConstRegs[ConstCount] := ConstRegs[X];
  12137. ConstSizes[ConstCount] := RegSize;
  12138. ConstVals[ConstCount] := CurrentVal;
  12139. Inc(ConstCount);
  12140. Inc(Count);
  12141. Result := True;
  12142. Exit;
  12143. end;
  12144. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12145. if ANewReg = NR_NO then
  12146. { No free registers }
  12147. Exit;
  12148. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12149. up vying for the same register }
  12150. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12151. ConstRegs[ConstCount] := ANewReg;
  12152. ConstSizes[ConstCount] := RegSize;
  12153. ConstVals[ConstCount] := CurrentVal;
  12154. Inc(ConstCount);
  12155. Inc(Count);
  12156. Result := True;
  12157. end;
  12158. destructor TCMOVTracking.Done;
  12159. begin
  12160. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12161. end;
  12162. procedure TCMOVTracking.Process(out new_p: tai);
  12163. var
  12164. Count, Writes: LongInt;
  12165. RegMatch: Boolean;
  12166. hp1, hp_new: tai;
  12167. inverted_condition, condition: TAsmCond;
  12168. begin
  12169. if (fState in [tsInvalid, tsProcessed]) then
  12170. InternalError(2023110701);
  12171. { Repurpose RegisterTracking to mark registers that we've defined }
  12172. RegisterTracking[R_INTREGISTER].Clear;
  12173. Count := 0;
  12174. Writes := 0;
  12175. condition := taicpu(fInitialJump).condition;
  12176. inverted_condition := inverse_cond(condition);
  12177. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12178. doesn't get CMOVs in this case }
  12179. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12180. begin
  12181. { Include the jump in the flag tracking }
  12182. if Assigned(fThirdJump) then
  12183. begin
  12184. if (fState = tsDoubleBranchSame) then
  12185. begin
  12186. { Will be an unconditional jump, so track to the instruction before it }
  12187. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12188. InternalError(2023110710);
  12189. end
  12190. else
  12191. hp1 := fThirdJump;
  12192. end
  12193. else
  12194. hp1 := fSecondMovBlockStop;
  12195. end
  12196. else
  12197. begin
  12198. { Include a conditional jump in the flag tracking }
  12199. if Assigned(fSecondJump) then
  12200. begin
  12201. if (fState = tsDetour) then
  12202. begin
  12203. { Will be an unconditional jump, so track to the instruction before it }
  12204. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12205. InternalError(2023110711);
  12206. end
  12207. else
  12208. hp1 := fSecondJump;
  12209. end
  12210. else
  12211. hp1 := fFirstMovBlockStop;
  12212. end;
  12213. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12214. { Process the second set of MOVs first, because if a destination
  12215. register is shared between the first and second MOV sets, it is more
  12216. efficient to turn the first one into a MOV instruction and place it
  12217. before the CMP if possible, but we won't know which registers are
  12218. shared until we've processed at least one list, so we might as well
  12219. make it the second one since that won't be modified again. }
  12220. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12221. begin
  12222. hp1 := fSecondMovBlock;
  12223. repeat
  12224. if not Assigned(hp1) then
  12225. InternalError(2018062902);
  12226. if (hp1.typ = ait_instruction) then
  12227. begin
  12228. { Extra safeguard }
  12229. if (taicpu(hp1).opcode <> A_MOV) then
  12230. InternalError(2018062903);
  12231. { Note: tsDoubleBranchDifferent is essentially identical to
  12232. tsBranching and the 2nd block is best left largely
  12233. untouched, but we need to evaluate which registers the MOVs
  12234. write to in order to track what would be complementary CMOV
  12235. pairs that can be further optimised. [Kit] }
  12236. if fState <> tsDoubleBranchDifferent then
  12237. begin
  12238. if taicpu(hp1).oper[0]^.typ = top_const then
  12239. begin
  12240. RegMatch := False;
  12241. for Count := 0 to ConstCount - 1 do
  12242. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12243. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12244. begin
  12245. RegMatch := True;
  12246. { If it's in RegisterTracking, then this register
  12247. is being used more than once and hence has
  12248. already had its value defined (it gets added to
  12249. UsedRegs through AllocRegBetween below) }
  12250. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12251. begin
  12252. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12253. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12254. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12255. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12256. ConstMovs[Count] := hp_new;
  12257. end
  12258. else
  12259. { We just need an instruction between hp_prev and hp1
  12260. where we know the register is marked as in use }
  12261. hp_new := fSecondMovBlock;
  12262. { Keep track of largest write for this register so it can be optimised later }
  12263. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12264. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12265. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12266. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12267. Break;
  12268. end;
  12269. if not RegMatch then
  12270. InternalError(2021100411);
  12271. end;
  12272. taicpu(hp1).opcode := A_CMOVcc;
  12273. taicpu(hp1).condition := condition;
  12274. end;
  12275. { Store these writes to search for duplicates later on }
  12276. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12277. Inc(Writes);
  12278. end;
  12279. fOptimizer.GetNextInstruction(hp1, hp1);
  12280. until (hp1 = fSecondMovBlockStop);
  12281. end;
  12282. { Now do the first set of MOVs }
  12283. hp1 := fFirstMovBlock;
  12284. repeat
  12285. if not Assigned(hp1) then
  12286. InternalError(2018062904);
  12287. if (hp1.typ = ait_instruction) then
  12288. begin
  12289. RegMatch := False;
  12290. { Extra safeguard }
  12291. if (taicpu(hp1).opcode <> A_MOV) then
  12292. InternalError(2018062905);
  12293. { Search through the RegWrites list to see if there are any
  12294. opposing CMOV pairs that write to the same register }
  12295. for Count := 0 to Writes - 1 do
  12296. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12297. begin
  12298. { We have a match. Keep this as a MOV }
  12299. { Move ahead in preparation }
  12300. fOptimizer.GetNextInstruction(hp1, hp1);
  12301. RegMatch := True;
  12302. Break;
  12303. end;
  12304. if RegMatch then
  12305. Continue;
  12306. if taicpu(hp1).oper[0]^.typ = top_const then
  12307. begin
  12308. for Count := 0 to ConstCount - 1 do
  12309. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12310. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12311. begin
  12312. RegMatch := True;
  12313. { If it's in RegisterTracking, then this register is
  12314. being used more than once and hence has already had
  12315. its value defined (it gets added to UsedRegs through
  12316. AllocRegBetween below) }
  12317. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12318. begin
  12319. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12320. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12321. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12322. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12323. ConstMovs[Count] := hp_new;
  12324. end
  12325. else
  12326. { We just need an instruction between hp_prev and hp1
  12327. where we know the register is marked as in use }
  12328. hp_new := fFirstMovBlock;
  12329. { Keep track of largest write for this register so it can be optimised later }
  12330. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12331. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12332. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12333. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12334. Break;
  12335. end;
  12336. if not RegMatch then
  12337. InternalError(2021100412);
  12338. end;
  12339. taicpu(hp1).opcode := A_CMOVcc;
  12340. taicpu(hp1).condition := inverted_condition;
  12341. if (fState = tsDoubleBranchDifferent) then
  12342. begin
  12343. { Store these writes to search for duplicates later on }
  12344. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12345. Inc(Writes);
  12346. end;
  12347. end;
  12348. fOptimizer.GetNextInstruction(hp1, hp1);
  12349. until (hp1 = fFirstMovBlockStop);
  12350. { Update initialisation MOVs to the smallest possible size }
  12351. for Count := 0 to ConstCount - 1 do
  12352. if Assigned(ConstMovs[Count]) then
  12353. begin
  12354. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12355. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12356. end;
  12357. case fState of
  12358. tsSimple:
  12359. begin
  12360. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12361. { No branch to delete }
  12362. end;
  12363. tsDetour:
  12364. begin
  12365. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12366. { Preserve jump }
  12367. end;
  12368. tsBranching, tsDoubleBranchDifferent:
  12369. begin
  12370. if (fState = tsBranching) then
  12371. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12372. else
  12373. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12374. taicpu(fSecondJump).opcode := A_JCC;
  12375. taicpu(fSecondJump).condition := inverted_condition;
  12376. end;
  12377. tsDouble, tsDoubleBranchSame:
  12378. begin
  12379. if (fState = tsDouble) then
  12380. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12381. else
  12382. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12383. { Delete second jump }
  12384. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12385. fOptimizer.RemoveInstruction(fSecondJump);
  12386. end;
  12387. tsDoubleSecondBranching:
  12388. begin
  12389. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12390. { Delete second jump, preserve third jump as conditional }
  12391. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12392. fOptimizer.RemoveInstruction(fSecondJump);
  12393. taicpu(fThirdJump).opcode := A_JCC;
  12394. taicpu(fThirdJump).condition := condition;
  12395. end;
  12396. else
  12397. InternalError(2023110720);
  12398. end;
  12399. { Now we can safely decrement the reference count }
  12400. tasmlabel(fLabel).decrefs;
  12401. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12402. { Remove the original jump }
  12403. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12404. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12405. fState := tsProcessed;
  12406. end;
  12407. {$endif 8086}
  12408. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12409. var
  12410. hp1,hp2: tai;
  12411. carryadd_opcode : TAsmOp;
  12412. symbol: TAsmSymbol;
  12413. increg, tmpreg: TRegister;
  12414. {$ifndef i8086}
  12415. CMOVTracking: PCMOVTracking;
  12416. hp3,hp4,hp5: tai;
  12417. {$endif i8086}
  12418. TempBool: Boolean;
  12419. begin
  12420. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12421. DoJumpOptimizations(p, TempBool) then
  12422. Exit(True);
  12423. result:=false;
  12424. if GetNextInstruction(p,hp1) then
  12425. begin
  12426. if (hp1.typ=ait_label) then
  12427. begin
  12428. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12429. Exit;
  12430. end
  12431. else if (hp1.typ<>ait_instruction) then
  12432. Exit;
  12433. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12434. if (
  12435. (
  12436. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12437. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12438. (Taicpu(hp1).oper[0]^.val=1)
  12439. ) or
  12440. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12441. ) and
  12442. GetNextInstruction(hp1,hp2) and
  12443. FindLabel(TAsmLabel(symbol), hp2) then
  12444. { jb @@1 cmc
  12445. inc/dec operand --> adc/sbb operand,0
  12446. @@1:
  12447. ... and ...
  12448. jnb @@1
  12449. inc/dec operand --> adc/sbb operand,0
  12450. @@1: }
  12451. begin
  12452. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12453. begin
  12454. case taicpu(hp1).opcode of
  12455. A_INC,
  12456. A_ADD:
  12457. carryadd_opcode:=A_ADC;
  12458. A_DEC,
  12459. A_SUB:
  12460. carryadd_opcode:=A_SBB;
  12461. else
  12462. InternalError(2021011001);
  12463. end;
  12464. Taicpu(p).clearop(0);
  12465. Taicpu(p).ops:=0;
  12466. Taicpu(p).is_jmp:=false;
  12467. Taicpu(p).opcode:=A_CMC;
  12468. Taicpu(p).condition:=C_NONE;
  12469. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12470. Taicpu(hp1).ops:=2;
  12471. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12472. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12473. else
  12474. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12475. Taicpu(hp1).loadconst(0,0);
  12476. Taicpu(hp1).opcode:=carryadd_opcode;
  12477. result:=true;
  12478. exit;
  12479. end
  12480. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12481. begin
  12482. case taicpu(hp1).opcode of
  12483. A_INC,
  12484. A_ADD:
  12485. carryadd_opcode:=A_ADC;
  12486. A_DEC,
  12487. A_SUB:
  12488. carryadd_opcode:=A_SBB;
  12489. else
  12490. InternalError(2021011002);
  12491. end;
  12492. Taicpu(hp1).ops:=2;
  12493. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12494. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12495. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12496. else
  12497. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12498. Taicpu(hp1).loadconst(0,0);
  12499. Taicpu(hp1).opcode:=carryadd_opcode;
  12500. RemoveCurrentP(p, hp1);
  12501. result:=true;
  12502. exit;
  12503. end
  12504. {
  12505. jcc @@1 setcc tmpreg
  12506. inc/dec/add/sub operand -> (movzx tmpreg)
  12507. @@1: add/sub tmpreg,operand
  12508. While this increases code size slightly, it makes the code much faster if the
  12509. jump is unpredictable
  12510. }
  12511. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12512. begin
  12513. { search for an available register which is volatile }
  12514. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12515. if increg <> NR_NO then
  12516. begin
  12517. { We don't need to check if tmpreg is in hp1 or not, because
  12518. it will be marked as in use at p (if not, this is
  12519. indictive of a compiler bug). }
  12520. TAsmLabel(symbol).decrefs;
  12521. Taicpu(p).clearop(0);
  12522. Taicpu(p).ops:=1;
  12523. Taicpu(p).is_jmp:=false;
  12524. Taicpu(p).opcode:=A_SETcc;
  12525. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12526. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12527. Taicpu(p).loadreg(0,increg);
  12528. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12529. begin
  12530. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12531. R_SUBW:
  12532. begin
  12533. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12534. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12535. end;
  12536. R_SUBD:
  12537. begin
  12538. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12539. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12540. end;
  12541. {$ifdef x86_64}
  12542. R_SUBQ:
  12543. begin
  12544. { MOVZX doesn't have a 64-bit variant, because
  12545. the 32-bit version implicitly zeroes the
  12546. upper 32-bits of the destination register }
  12547. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12548. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12549. setsubreg(tmpreg, R_SUBQ);
  12550. end;
  12551. {$endif x86_64}
  12552. else
  12553. Internalerror(2020030601);
  12554. end;
  12555. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12556. asml.InsertAfter(hp2,p);
  12557. end
  12558. else
  12559. tmpreg := increg;
  12560. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12561. begin
  12562. Taicpu(hp1).ops:=2;
  12563. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12564. end;
  12565. Taicpu(hp1).loadreg(0,tmpreg);
  12566. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12567. Result := True;
  12568. { p is no longer a Jcc instruction, so exit }
  12569. Exit;
  12570. end;
  12571. end;
  12572. end;
  12573. { Detect the following:
  12574. jmp<cond> @Lbl1
  12575. jmp @Lbl2
  12576. ...
  12577. @Lbl1:
  12578. ret
  12579. Change to:
  12580. jmp<inv_cond> @Lbl2
  12581. ret
  12582. }
  12583. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12584. begin
  12585. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12586. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12587. MatchInstruction(hp2,A_RET,[S_NO]) then
  12588. begin
  12589. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12590. { Change label address to that of the unconditional jump }
  12591. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12592. TAsmLabel(symbol).DecRefs;
  12593. taicpu(hp1).opcode := A_RET;
  12594. taicpu(hp1).is_jmp := false;
  12595. taicpu(hp1).ops := taicpu(hp2).ops;
  12596. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12597. case taicpu(hp2).ops of
  12598. 0:
  12599. taicpu(hp1).clearop(0);
  12600. 1:
  12601. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12602. else
  12603. internalerror(2016041302);
  12604. end;
  12605. end;
  12606. {$ifndef i8086}
  12607. end
  12608. {
  12609. convert
  12610. j<c> .L1
  12611. mov 1,reg
  12612. jmp .L2
  12613. .L1
  12614. mov 0,reg
  12615. .L2
  12616. into
  12617. mov 0,reg
  12618. set<not(c)> reg
  12619. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12620. would destroy the flag contents
  12621. }
  12622. else if MatchInstruction(hp1,A_MOV,[]) and
  12623. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12624. {$ifdef i386}
  12625. (
  12626. { Under i386, ESI, EDI, EBP and ESP
  12627. don't have an 8-bit representation }
  12628. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12629. ) and
  12630. {$endif i386}
  12631. (taicpu(hp1).oper[0]^.val=1) and
  12632. GetNextInstruction(hp1,hp2) and
  12633. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12634. GetNextInstruction(hp2,hp3) and
  12635. (hp3.typ=ait_label) and
  12636. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12637. (tai_label(hp3).labsym.getrefs=1) and
  12638. GetNextInstruction(hp3,hp4) and
  12639. MatchInstruction(hp4,A_MOV,[]) and
  12640. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12641. (taicpu(hp4).oper[0]^.val=0) and
  12642. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12643. GetNextInstruction(hp4,hp5) and
  12644. (hp5.typ=ait_label) and
  12645. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12646. (tai_label(hp5).labsym.getrefs=1) then
  12647. begin
  12648. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12649. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12650. { remove last label }
  12651. RemoveInstruction(hp5);
  12652. { remove second label }
  12653. RemoveInstruction(hp3);
  12654. { remove jmp }
  12655. RemoveInstruction(hp2);
  12656. if taicpu(hp1).opsize=S_B then
  12657. RemoveInstruction(hp1)
  12658. else
  12659. taicpu(hp1).loadconst(0,0);
  12660. taicpu(hp4).opcode:=A_SETcc;
  12661. taicpu(hp4).opsize:=S_B;
  12662. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12663. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12664. taicpu(hp4).opercnt:=1;
  12665. taicpu(hp4).ops:=1;
  12666. taicpu(hp4).freeop(1);
  12667. RemoveCurrentP(p);
  12668. Result:=true;
  12669. exit;
  12670. end
  12671. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12672. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12673. begin
  12674. { check for
  12675. jCC xxx
  12676. <several movs>
  12677. xxx:
  12678. Also spot:
  12679. Jcc xxx
  12680. <several movs>
  12681. jmp xxx
  12682. Change to:
  12683. <several cmovs with inverted condition>
  12684. jmp xxx (only for the 2nd case)
  12685. }
  12686. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12687. if CMOVTracking^.State <> tsInvalid then
  12688. begin
  12689. CMovTracking^.Process(p);
  12690. Result := True;
  12691. end;
  12692. CMOVTracking^.Done;
  12693. {$endif i8086}
  12694. end;
  12695. end;
  12696. end;
  12697. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12698. var
  12699. hp1,hp2,hp3: tai;
  12700. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12701. NewSize: TOpSize;
  12702. NewRegSize: TSubRegister;
  12703. Limit: TCgInt;
  12704. SwapOper: POper;
  12705. begin
  12706. result:=false;
  12707. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12708. GetNextInstruction(p,hp1) and
  12709. (hp1.typ = ait_instruction);
  12710. if reg_and_hp1_is_instr and
  12711. (
  12712. (taicpu(hp1).opcode <> A_LEA) or
  12713. { If the LEA instruction can be converted into an arithmetic instruction,
  12714. it may be possible to then fold it. }
  12715. (
  12716. { If the flags register is in use, don't change the instruction
  12717. to an ADD otherwise this will scramble the flags. [Kit] }
  12718. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12719. ConvertLEA(taicpu(hp1))
  12720. )
  12721. ) and
  12722. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12723. GetNextInstruction(hp1,hp2) and
  12724. MatchInstruction(hp2,A_MOV,[]) and
  12725. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12726. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12727. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12728. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12729. {$ifdef i386}
  12730. { not all registers have byte size sub registers on i386 }
  12731. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12732. {$endif i386}
  12733. (((taicpu(hp1).ops=2) and
  12734. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12735. ((taicpu(hp1).ops=1) and
  12736. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12737. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12738. begin
  12739. { change movsX/movzX reg/ref, reg2
  12740. add/sub/or/... reg3/$const, reg2
  12741. mov reg2 reg/ref
  12742. to add/sub/or/... reg3/$const, reg/ref }
  12743. { by example:
  12744. movswl %si,%eax movswl %si,%eax p
  12745. decl %eax addl %edx,%eax hp1
  12746. movw %ax,%si movw %ax,%si hp2
  12747. ->
  12748. movswl %si,%eax movswl %si,%eax p
  12749. decw %eax addw %edx,%eax hp1
  12750. movw %ax,%si movw %ax,%si hp2
  12751. }
  12752. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12753. {
  12754. ->
  12755. movswl %si,%eax movswl %si,%eax p
  12756. decw %si addw %dx,%si hp1
  12757. movw %ax,%si movw %ax,%si hp2
  12758. }
  12759. case taicpu(hp1).ops of
  12760. 1:
  12761. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12762. 2:
  12763. begin
  12764. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12765. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12766. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12767. end;
  12768. else
  12769. internalerror(2008042702);
  12770. end;
  12771. {
  12772. ->
  12773. decw %si addw %dx,%si p
  12774. }
  12775. DebugMsg(SPeepholeOptimization + 'var3',p);
  12776. RemoveCurrentP(p, hp1);
  12777. RemoveInstruction(hp2);
  12778. Result := True;
  12779. Exit;
  12780. end;
  12781. if reg_and_hp1_is_instr and
  12782. (taicpu(hp1).opcode = A_MOV) and
  12783. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12784. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12785. {$ifdef x86_64}
  12786. { check for implicit extension to 64 bit }
  12787. or
  12788. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12789. (taicpu(hp1).opsize=S_Q) and
  12790. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12791. )
  12792. {$endif x86_64}
  12793. )
  12794. then
  12795. begin
  12796. { change
  12797. movx %reg1,%reg2
  12798. mov %reg2,%reg3
  12799. dealloc %reg2
  12800. into
  12801. movx %reg,%reg3
  12802. }
  12803. TransferUsedRegs(TmpUsedRegs);
  12804. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12805. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12806. begin
  12807. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12808. {$ifdef x86_64}
  12809. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12810. (taicpu(hp1).opsize=S_Q) then
  12811. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12812. else
  12813. {$endif x86_64}
  12814. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12815. RemoveInstruction(hp1);
  12816. Result := True;
  12817. Exit;
  12818. end;
  12819. end;
  12820. if reg_and_hp1_is_instr and
  12821. ((taicpu(hp1).opcode=A_MOV) or
  12822. (taicpu(hp1).opcode=A_ADD) or
  12823. (taicpu(hp1).opcode=A_SUB) or
  12824. (taicpu(hp1).opcode=A_CMP) or
  12825. (taicpu(hp1).opcode=A_OR) or
  12826. (taicpu(hp1).opcode=A_XOR) or
  12827. (taicpu(hp1).opcode=A_AND)
  12828. ) and
  12829. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12830. begin
  12831. AndTest := (taicpu(hp1).opcode=A_AND) and
  12832. GetNextInstruction(hp1, hp2) and
  12833. (hp2.typ = ait_instruction) and
  12834. (
  12835. (
  12836. (taicpu(hp2).opcode=A_TEST) and
  12837. (
  12838. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12839. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12840. (
  12841. { If the AND and TEST instructions share a constant, this is also valid }
  12842. (taicpu(hp1).oper[0]^.typ = top_const) and
  12843. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12844. )
  12845. ) and
  12846. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12847. ) or
  12848. (
  12849. (taicpu(hp2).opcode=A_CMP) and
  12850. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12851. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12852. )
  12853. );
  12854. { change
  12855. movx (oper),%reg2
  12856. and $x,%reg2
  12857. test %reg2,%reg2
  12858. dealloc %reg2
  12859. into
  12860. op %reg1,%reg3
  12861. if the second op accesses only the bits stored in reg1
  12862. }
  12863. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12864. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12865. (taicpu(hp1).oper[0]^.typ = top_const) and
  12866. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12867. AndTest then
  12868. begin
  12869. { Check if the AND constant is in range }
  12870. case taicpu(p).opsize of
  12871. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12872. begin
  12873. NewSize := S_B;
  12874. Limit := $FF;
  12875. end;
  12876. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12877. begin
  12878. NewSize := S_W;
  12879. Limit := $FFFF;
  12880. end;
  12881. {$ifdef x86_64}
  12882. S_LQ:
  12883. begin
  12884. NewSize := S_L;
  12885. Limit := $FFFFFFFF;
  12886. end;
  12887. {$endif x86_64}
  12888. else
  12889. InternalError(2021120303);
  12890. end;
  12891. if (
  12892. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12893. { Check for negative operands }
  12894. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12895. ) and
  12896. GetNextInstruction(hp2,hp3) and
  12897. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12898. (taicpu(hp3).condition in [C_E,C_NE]) then
  12899. begin
  12900. TransferUsedRegs(TmpUsedRegs);
  12901. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12902. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12903. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12904. begin
  12905. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12906. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12907. taicpu(hp1).opcode := A_TEST;
  12908. taicpu(hp1).opsize := NewSize;
  12909. RemoveInstruction(hp2);
  12910. RemoveCurrentP(p, hp1);
  12911. Result:=true;
  12912. exit;
  12913. end;
  12914. end;
  12915. end;
  12916. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12917. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12918. (taicpu(hp1).opsize=S_B)) or
  12919. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12920. (taicpu(hp1).opsize=S_W))
  12921. {$ifdef x86_64}
  12922. or ((taicpu(p).opsize=S_LQ) and
  12923. (taicpu(hp1).opsize=S_L))
  12924. {$endif x86_64}
  12925. ) and
  12926. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12927. begin
  12928. { change
  12929. movx %reg1,%reg2
  12930. op %reg2,%reg3
  12931. dealloc %reg2
  12932. into
  12933. op %reg1,%reg3
  12934. if the second op accesses only the bits stored in reg1
  12935. }
  12936. TransferUsedRegs(TmpUsedRegs);
  12937. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12938. if AndTest then
  12939. begin
  12940. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12941. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12942. end
  12943. else
  12944. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12945. if not RegUsed then
  12946. begin
  12947. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12948. if taicpu(p).oper[0]^.typ=top_reg then
  12949. begin
  12950. case taicpu(hp1).opsize of
  12951. S_B:
  12952. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12953. S_W:
  12954. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12955. S_L:
  12956. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12957. else
  12958. Internalerror(2020102301);
  12959. end;
  12960. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12961. end
  12962. else
  12963. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12964. RemoveCurrentP(p);
  12965. if AndTest then
  12966. RemoveInstruction(hp2);
  12967. result:=true;
  12968. exit;
  12969. end;
  12970. end
  12971. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12972. (
  12973. { Bitwise operations only }
  12974. (taicpu(hp1).opcode=A_AND) or
  12975. (taicpu(hp1).opcode=A_TEST) or
  12976. (
  12977. (taicpu(hp1).oper[0]^.typ = top_const) and
  12978. (
  12979. (taicpu(hp1).opcode=A_OR) or
  12980. (taicpu(hp1).opcode=A_XOR)
  12981. )
  12982. )
  12983. ) and
  12984. (
  12985. (taicpu(hp1).oper[0]^.typ = top_const) or
  12986. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12987. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12988. ) then
  12989. begin
  12990. { change
  12991. movx %reg2,%reg2
  12992. op const,%reg2
  12993. into
  12994. op const,%reg2 (smaller version)
  12995. movx %reg2,%reg2
  12996. also change
  12997. movx %reg1,%reg2
  12998. and/test (oper),%reg2
  12999. dealloc %reg2
  13000. into
  13001. and/test (oper),%reg1
  13002. }
  13003. case taicpu(p).opsize of
  13004. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13005. begin
  13006. NewSize := S_B;
  13007. NewRegSize := R_SUBL;
  13008. Limit := $FF;
  13009. end;
  13010. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13011. begin
  13012. NewSize := S_W;
  13013. NewRegSize := R_SUBW;
  13014. Limit := $FFFF;
  13015. end;
  13016. {$ifdef x86_64}
  13017. S_LQ:
  13018. begin
  13019. NewSize := S_L;
  13020. NewRegSize := R_SUBD;
  13021. Limit := $FFFFFFFF;
  13022. end;
  13023. {$endif x86_64}
  13024. else
  13025. Internalerror(2021120302);
  13026. end;
  13027. TransferUsedRegs(TmpUsedRegs);
  13028. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13029. if AndTest then
  13030. begin
  13031. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13032. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13033. end
  13034. else
  13035. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13036. if
  13037. (
  13038. (taicpu(p).opcode = A_MOVZX) and
  13039. (
  13040. (taicpu(hp1).opcode=A_AND) or
  13041. (taicpu(hp1).opcode=A_TEST)
  13042. ) and
  13043. not (
  13044. { If both are references, then the final instruction will have
  13045. both operands as references, which is not allowed }
  13046. (taicpu(p).oper[0]^.typ = top_ref) and
  13047. (taicpu(hp1).oper[0]^.typ = top_ref)
  13048. ) and
  13049. not RegUsed
  13050. ) or
  13051. (
  13052. (
  13053. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13054. not RegUsed
  13055. ) and
  13056. (taicpu(p).oper[0]^.typ = top_reg) and
  13057. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13058. (taicpu(hp1).oper[0]^.typ = top_const) and
  13059. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13060. ) then
  13061. begin
  13062. {$if defined(i386) or defined(i8086)}
  13063. { If the target size is 8-bit, make sure we can actually encode it }
  13064. 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
  13065. Exit;
  13066. {$endif i386 or i8086}
  13067. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13068. taicpu(hp1).opsize := NewSize;
  13069. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13070. if AndTest then
  13071. begin
  13072. RemoveInstruction(hp2);
  13073. if not RegUsed then
  13074. begin
  13075. taicpu(hp1).opcode := A_TEST;
  13076. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13077. begin
  13078. { Make sure the reference is the second operand }
  13079. SwapOper := taicpu(hp1).oper[0];
  13080. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13081. taicpu(hp1).oper[1] := SwapOper;
  13082. end;
  13083. end;
  13084. end;
  13085. case taicpu(hp1).oper[0]^.typ of
  13086. top_reg:
  13087. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13088. top_const:
  13089. { For the AND/TEST case }
  13090. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13091. else
  13092. ;
  13093. end;
  13094. if RegUsed then
  13095. begin
  13096. AsmL.Remove(p);
  13097. AsmL.InsertAfter(p, hp1);
  13098. p := hp1;
  13099. end
  13100. else
  13101. RemoveCurrentP(p, hp1);
  13102. result:=true;
  13103. exit;
  13104. end;
  13105. end;
  13106. end;
  13107. if reg_and_hp1_is_instr and
  13108. (taicpu(p).oper[0]^.typ = top_reg) and
  13109. (
  13110. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13111. ) and
  13112. (taicpu(hp1).oper[0]^.typ = top_const) and
  13113. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13114. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13115. { Minimum shift value allowed is the bit difference between the sizes }
  13116. (taicpu(hp1).oper[0]^.val >=
  13117. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13118. 8 * (
  13119. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13120. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13121. )
  13122. ) then
  13123. begin
  13124. { For:
  13125. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13126. shl/sal ##, %reg1
  13127. Remove the movsx/movzx instruction if the shift overwrites the
  13128. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13129. }
  13130. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13131. RemoveCurrentP(p, hp1);
  13132. Result := True;
  13133. Exit;
  13134. end
  13135. else if reg_and_hp1_is_instr and
  13136. (taicpu(p).oper[0]^.typ = top_reg) and
  13137. (
  13138. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13139. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13140. ) and
  13141. (taicpu(hp1).oper[0]^.typ = top_const) and
  13142. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13143. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13144. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13145. (taicpu(hp1).oper[0]^.val <
  13146. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13147. 8 * (
  13148. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13149. )
  13150. ) then
  13151. begin
  13152. { For:
  13153. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13154. sar ##, %reg1 shr ##, %reg1
  13155. Move the shift to before the movx instruction if the shift value
  13156. is not too large.
  13157. }
  13158. asml.Remove(hp1);
  13159. asml.InsertBefore(hp1, p);
  13160. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13161. case taicpu(p).opsize of
  13162. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13163. taicpu(hp1).opsize := S_B;
  13164. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13165. taicpu(hp1).opsize := S_W;
  13166. {$ifdef x86_64}
  13167. S_LQ:
  13168. taicpu(hp1).opsize := S_L;
  13169. {$endif}
  13170. else
  13171. InternalError(2020112401);
  13172. end;
  13173. if (taicpu(hp1).opcode = A_SHR) then
  13174. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13175. else
  13176. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13177. Result := True;
  13178. end;
  13179. if reg_and_hp1_is_instr and
  13180. (taicpu(p).oper[0]^.typ = top_reg) and
  13181. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13182. (
  13183. (taicpu(hp1).opcode = taicpu(p).opcode)
  13184. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13185. {$ifdef x86_64}
  13186. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13187. {$endif x86_64}
  13188. ) then
  13189. begin
  13190. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13191. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13192. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13193. begin
  13194. {
  13195. For example:
  13196. movzbw %al,%ax
  13197. movzwl %ax,%eax
  13198. Compress into:
  13199. movzbl %al,%eax
  13200. }
  13201. RegUsed := False;
  13202. case taicpu(p).opsize of
  13203. S_BW:
  13204. case taicpu(hp1).opsize of
  13205. S_WL:
  13206. begin
  13207. taicpu(p).opsize := S_BL;
  13208. RegUsed := True;
  13209. end;
  13210. {$ifdef x86_64}
  13211. S_WQ:
  13212. begin
  13213. if taicpu(p).opcode = A_MOVZX then
  13214. begin
  13215. taicpu(p).opsize := S_BL;
  13216. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13217. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13218. end
  13219. else
  13220. taicpu(p).opsize := S_BQ;
  13221. RegUsed := True;
  13222. end;
  13223. {$endif x86_64}
  13224. else
  13225. ;
  13226. end;
  13227. {$ifdef x86_64}
  13228. S_BL:
  13229. case taicpu(hp1).opsize of
  13230. S_LQ:
  13231. begin
  13232. if taicpu(p).opcode = A_MOVZX then
  13233. begin
  13234. taicpu(p).opsize := S_BL;
  13235. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13236. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13237. end
  13238. else
  13239. taicpu(p).opsize := S_BQ;
  13240. RegUsed := True;
  13241. end;
  13242. else
  13243. ;
  13244. end;
  13245. S_WL:
  13246. case taicpu(hp1).opsize of
  13247. S_LQ:
  13248. begin
  13249. if taicpu(p).opcode = A_MOVZX then
  13250. begin
  13251. taicpu(p).opsize := S_WL;
  13252. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13253. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13254. end
  13255. else
  13256. taicpu(p).opsize := S_WQ;
  13257. RegUsed := True;
  13258. end;
  13259. else
  13260. ;
  13261. end;
  13262. {$endif x86_64}
  13263. else
  13264. ;
  13265. end;
  13266. if RegUsed then
  13267. begin
  13268. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13269. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13270. RemoveInstruction(hp1);
  13271. Result := True;
  13272. Exit;
  13273. end;
  13274. end;
  13275. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13276. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13277. GetNextInstruction(hp1, hp2) and
  13278. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13279. (
  13280. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13281. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13282. {$ifdef x86_64}
  13283. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13284. {$endif x86_64}
  13285. ) and
  13286. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13287. (
  13288. (
  13289. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13290. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13291. ) or
  13292. (
  13293. { Only allow the operands in reverse order for TEST instructions }
  13294. (taicpu(hp2).opcode = A_TEST) and
  13295. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13296. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13297. )
  13298. ) then
  13299. begin
  13300. {
  13301. For example:
  13302. movzbl %al,%eax
  13303. movzbl (ref),%edx
  13304. andl %edx,%eax
  13305. (%edx deallocated)
  13306. Change to:
  13307. andb (ref),%al
  13308. movzbl %al,%eax
  13309. Rules are:
  13310. - First two instructions have the same opcode and opsize
  13311. - First instruction's operands are the same super-register
  13312. - Second instruction operates on a different register
  13313. - Third instruction is AND, OR, XOR or TEST
  13314. - Third instruction's operands are the destination registers of the first two instructions
  13315. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13316. - Second instruction's destination register is deallocated afterwards
  13317. }
  13318. TransferUsedRegs(TmpUsedRegs);
  13319. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13320. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13321. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13322. begin
  13323. case taicpu(p).opsize of
  13324. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13325. NewSize := S_B;
  13326. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13327. NewSize := S_W;
  13328. {$ifdef x86_64}
  13329. S_LQ:
  13330. NewSize := S_L;
  13331. {$endif x86_64}
  13332. else
  13333. InternalError(2021120301);
  13334. end;
  13335. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13336. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13337. taicpu(hp2).opsize := NewSize;
  13338. RemoveInstruction(hp1);
  13339. { With TEST, it's best to keep the MOVX instruction at the top }
  13340. if (taicpu(hp2).opcode <> A_TEST) then
  13341. begin
  13342. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13343. asml.Remove(p);
  13344. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13345. asml.InsertAfter(p, hp2);
  13346. p := hp2;
  13347. end
  13348. else
  13349. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13350. Result := True;
  13351. Exit;
  13352. end;
  13353. end;
  13354. end;
  13355. if taicpu(p).opcode=A_MOVZX then
  13356. begin
  13357. { removes superfluous And's after movzx's }
  13358. if reg_and_hp1_is_instr and
  13359. (taicpu(hp1).opcode = A_AND) and
  13360. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13361. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13362. {$ifdef x86_64}
  13363. { check for implicit extension to 64 bit }
  13364. or
  13365. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13366. (taicpu(hp1).opsize=S_Q) and
  13367. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13368. )
  13369. {$endif x86_64}
  13370. )
  13371. then
  13372. begin
  13373. case taicpu(p).opsize Of
  13374. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13375. if (taicpu(hp1).oper[0]^.val = $ff) then
  13376. begin
  13377. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13378. RemoveInstruction(hp1);
  13379. Result:=true;
  13380. exit;
  13381. end;
  13382. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13383. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13384. begin
  13385. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13386. RemoveInstruction(hp1);
  13387. Result:=true;
  13388. exit;
  13389. end;
  13390. {$ifdef x86_64}
  13391. S_LQ:
  13392. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13393. begin
  13394. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13395. RemoveInstruction(hp1);
  13396. Result:=true;
  13397. exit;
  13398. end;
  13399. {$endif x86_64}
  13400. else
  13401. ;
  13402. end;
  13403. { we cannot get rid of the and, but can we get rid of the movz ?}
  13404. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13405. begin
  13406. case taicpu(p).opsize Of
  13407. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13408. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13409. begin
  13410. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13411. RemoveCurrentP(p,hp1);
  13412. Result:=true;
  13413. exit;
  13414. end;
  13415. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13416. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13417. begin
  13418. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13419. RemoveCurrentP(p,hp1);
  13420. Result:=true;
  13421. exit;
  13422. end;
  13423. {$ifdef x86_64}
  13424. S_LQ:
  13425. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13426. begin
  13427. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13428. RemoveCurrentP(p,hp1);
  13429. Result:=true;
  13430. exit;
  13431. end;
  13432. {$endif x86_64}
  13433. else
  13434. ;
  13435. end;
  13436. end;
  13437. end;
  13438. { changes some movzx constructs to faster synonyms (all examples
  13439. are given with eax/ax, but are also valid for other registers)}
  13440. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13441. begin
  13442. case taicpu(p).opsize of
  13443. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13444. (the machine code is equivalent to movzbl %al,%eax), but the
  13445. code generator still generates that assembler instruction and
  13446. it is silently converted. This should probably be checked.
  13447. [Kit] }
  13448. S_BW:
  13449. begin
  13450. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13451. (
  13452. not IsMOVZXAcceptable
  13453. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13454. or (
  13455. (cs_opt_size in current_settings.optimizerswitches) and
  13456. (taicpu(p).oper[1]^.reg = NR_AX)
  13457. )
  13458. ) then
  13459. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13460. begin
  13461. DebugMsg(SPeepholeOptimization + 'var7',p);
  13462. taicpu(p).opcode := A_AND;
  13463. taicpu(p).changeopsize(S_W);
  13464. taicpu(p).loadConst(0,$ff);
  13465. Result := True;
  13466. end
  13467. else if not IsMOVZXAcceptable and
  13468. GetNextInstruction(p, hp1) and
  13469. (tai(hp1).typ = ait_instruction) and
  13470. (taicpu(hp1).opcode = A_AND) and
  13471. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13472. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13473. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13474. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13475. begin
  13476. DebugMsg(SPeepholeOptimization + 'var8',p);
  13477. taicpu(p).opcode := A_MOV;
  13478. taicpu(p).changeopsize(S_W);
  13479. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13480. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13481. Result := True;
  13482. end;
  13483. end;
  13484. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13485. S_BL:
  13486. if not IsMOVZXAcceptable then
  13487. begin
  13488. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13489. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13490. begin
  13491. DebugMsg(SPeepholeOptimization + 'var9',p);
  13492. taicpu(p).opcode := A_AND;
  13493. taicpu(p).changeopsize(S_L);
  13494. taicpu(p).loadConst(0,$ff);
  13495. Result := True;
  13496. end
  13497. else if GetNextInstruction(p, hp1) and
  13498. (tai(hp1).typ = ait_instruction) and
  13499. (taicpu(hp1).opcode = A_AND) and
  13500. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13501. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13502. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13503. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13504. begin
  13505. DebugMsg(SPeepholeOptimization + 'var10',p);
  13506. taicpu(p).opcode := A_MOV;
  13507. taicpu(p).changeopsize(S_L);
  13508. { do not use R_SUBWHOLE
  13509. as movl %rdx,%eax
  13510. is invalid in assembler PM }
  13511. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13512. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13513. Result := True;
  13514. end;
  13515. end;
  13516. {$endif i8086}
  13517. S_WL:
  13518. if not IsMOVZXAcceptable then
  13519. begin
  13520. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13521. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13522. begin
  13523. DebugMsg(SPeepholeOptimization + 'var11',p);
  13524. taicpu(p).opcode := A_AND;
  13525. taicpu(p).changeopsize(S_L);
  13526. taicpu(p).loadConst(0,$ffff);
  13527. Result := True;
  13528. end
  13529. else if GetNextInstruction(p, hp1) and
  13530. (tai(hp1).typ = ait_instruction) and
  13531. (taicpu(hp1).opcode = A_AND) and
  13532. (taicpu(hp1).oper[0]^.typ = top_const) and
  13533. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13534. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13535. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13536. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13537. begin
  13538. DebugMsg(SPeepholeOptimization + 'var12',p);
  13539. taicpu(p).opcode := A_MOV;
  13540. taicpu(p).changeopsize(S_L);
  13541. { do not use R_SUBWHOLE
  13542. as movl %rdx,%eax
  13543. is invalid in assembler PM }
  13544. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13545. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13546. Result := True;
  13547. end;
  13548. end;
  13549. else
  13550. InternalError(2017050705);
  13551. end;
  13552. end
  13553. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13554. begin
  13555. if GetNextInstruction(p, hp1) and
  13556. (tai(hp1).typ = ait_instruction) and
  13557. (taicpu(hp1).opcode = A_AND) and
  13558. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13559. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13560. begin
  13561. case taicpu(p).opsize Of
  13562. S_BL:
  13563. if (taicpu(hp1).opsize <> S_L) or
  13564. (taicpu(hp1).oper[0]^.val > $FF) then
  13565. begin
  13566. DebugMsg(SPeepholeOptimization + 'var13',p);
  13567. taicpu(hp1).changeopsize(S_L);
  13568. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13569. Include(OptsToCheck, aoc_ForceNewIteration);
  13570. end;
  13571. S_WL:
  13572. if (taicpu(hp1).opsize <> S_L) or
  13573. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13574. begin
  13575. DebugMsg(SPeepholeOptimization + 'var14',p);
  13576. taicpu(hp1).changeopsize(S_L);
  13577. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13578. Include(OptsToCheck, aoc_ForceNewIteration);
  13579. end;
  13580. S_BW:
  13581. if (taicpu(hp1).opsize <> S_W) or
  13582. (taicpu(hp1).oper[0]^.val > $FF) then
  13583. begin
  13584. DebugMsg(SPeepholeOptimization + 'var15',p);
  13585. taicpu(hp1).changeopsize(S_W);
  13586. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13587. Include(OptsToCheck, aoc_ForceNewIteration);
  13588. end;
  13589. else
  13590. Internalerror(2017050704)
  13591. end;
  13592. end;
  13593. end;
  13594. end;
  13595. end;
  13596. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13597. var
  13598. hp1, hp2 : tai;
  13599. MaskLength : Cardinal;
  13600. MaskedBits : TCgInt;
  13601. ActiveReg : TRegister;
  13602. begin
  13603. Result:=false;
  13604. { There are no optimisations for reference targets }
  13605. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13606. Exit;
  13607. while GetNextInstruction(p, hp1) and
  13608. (hp1.typ = ait_instruction) do
  13609. begin
  13610. if (taicpu(p).oper[0]^.typ = top_const) then
  13611. begin
  13612. case taicpu(hp1).opcode of
  13613. A_AND:
  13614. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13615. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13616. { the second register must contain the first one, so compare their subreg types }
  13617. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13618. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13619. { change
  13620. and const1, reg
  13621. and const2, reg
  13622. to
  13623. and (const1 and const2), reg
  13624. }
  13625. begin
  13626. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13627. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13628. RemoveCurrentP(p, hp1);
  13629. Result:=true;
  13630. exit;
  13631. end;
  13632. A_CMP:
  13633. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13634. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13635. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13636. { Just check that the condition on the next instruction is compatible }
  13637. GetNextInstruction(hp1, hp2) and
  13638. (hp2.typ = ait_instruction) and
  13639. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13640. then
  13641. { change
  13642. and 2^n, reg
  13643. cmp 2^n, reg
  13644. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13645. to
  13646. and 2^n, reg
  13647. test reg, reg
  13648. j(~c) / set(~c) / cmov(~c)
  13649. }
  13650. begin
  13651. { Keep TEST instruction in, rather than remove it, because
  13652. it may trigger other optimisations such as MovAndTest2Test }
  13653. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13654. taicpu(hp1).opcode := A_TEST;
  13655. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13656. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13657. Result := True;
  13658. Exit;
  13659. end
  13660. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13661. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13662. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13663. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13664. { change
  13665. and $ff/$ff/$ffff, reg
  13666. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13667. dealloc reg
  13668. to
  13669. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13670. }
  13671. begin
  13672. TransferUsedRegs(TmpUsedRegs);
  13673. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13674. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13675. begin
  13676. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13677. case taicpu(p).oper[0]^.val of
  13678. $ff:
  13679. begin
  13680. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13681. taicpu(hp1).opsize:=S_B;
  13682. end;
  13683. $ffff:
  13684. begin
  13685. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13686. taicpu(hp1).opsize:=S_W;
  13687. end;
  13688. $ffffffff:
  13689. begin
  13690. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13691. taicpu(hp1).opsize:=S_L;
  13692. end;
  13693. else
  13694. Internalerror(2023030401);
  13695. end;
  13696. RemoveCurrentP(p);
  13697. Result := True;
  13698. Exit;
  13699. end;
  13700. end;
  13701. A_MOVZX:
  13702. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13703. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13704. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13705. (
  13706. (
  13707. (taicpu(p).opsize=S_W) and
  13708. (taicpu(hp1).opsize=S_BW)
  13709. ) or
  13710. (
  13711. (taicpu(p).opsize=S_L) and
  13712. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13713. )
  13714. {$ifdef x86_64}
  13715. or
  13716. (
  13717. (taicpu(p).opsize=S_Q) and
  13718. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13719. )
  13720. {$endif x86_64}
  13721. ) then
  13722. begin
  13723. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13724. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13725. ) or
  13726. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13727. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13728. then
  13729. begin
  13730. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13731. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13732. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13733. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13734. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13735. }
  13736. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13737. RemoveInstruction(hp1);
  13738. { See if there are other optimisations possible }
  13739. Continue;
  13740. end;
  13741. end;
  13742. A_SHL:
  13743. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13744. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13745. begin
  13746. {$ifopt R+}
  13747. {$define RANGE_WAS_ON}
  13748. {$R-}
  13749. {$endif}
  13750. { get length of potential and mask }
  13751. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13752. { really a mask? }
  13753. {$ifdef RANGE_WAS_ON}
  13754. {$R+}
  13755. {$endif}
  13756. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13757. { unmasked part shifted out? }
  13758. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13759. begin
  13760. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13761. RemoveCurrentP(p, hp1);
  13762. Result:=true;
  13763. exit;
  13764. end;
  13765. end;
  13766. A_SHR:
  13767. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13768. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13769. (taicpu(hp1).oper[0]^.val <= 63) then
  13770. begin
  13771. { Does SHR combined with the AND cover all the bits?
  13772. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13773. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13774. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13775. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13776. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13777. begin
  13778. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13779. RemoveCurrentP(p, hp1);
  13780. Result := True;
  13781. Exit;
  13782. end;
  13783. end;
  13784. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13785. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13786. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13787. begin
  13788. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13789. (
  13790. (
  13791. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13792. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13793. ) or (
  13794. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13795. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13796. {$ifdef x86_64}
  13797. ) or (
  13798. (taicpu(hp1).opsize = S_LQ) and
  13799. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13800. {$endif x86_64}
  13801. )
  13802. ) then
  13803. begin
  13804. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13805. begin
  13806. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13807. RemoveInstruction(hp1);
  13808. { See if there are other optimisations possible }
  13809. Continue;
  13810. end;
  13811. { The super-registers are the same though.
  13812. Note that this change by itself doesn't improve
  13813. code speed, but it opens up other optimisations. }
  13814. {$ifdef x86_64}
  13815. { Convert 64-bit register to 32-bit }
  13816. case taicpu(hp1).opsize of
  13817. S_BQ:
  13818. begin
  13819. taicpu(hp1).opsize := S_BL;
  13820. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13821. end;
  13822. S_WQ:
  13823. begin
  13824. taicpu(hp1).opsize := S_WL;
  13825. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13826. end
  13827. else
  13828. ;
  13829. end;
  13830. {$endif x86_64}
  13831. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13832. taicpu(hp1).opcode := A_MOVZX;
  13833. { See if there are other optimisations possible }
  13834. Continue;
  13835. end;
  13836. end;
  13837. else
  13838. ;
  13839. end;
  13840. end
  13841. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13842. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13843. begin
  13844. {$ifdef x86_64}
  13845. if (taicpu(p).opsize = S_Q) then
  13846. begin
  13847. { Never necessary }
  13848. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13849. RemoveCurrentP(p, hp1);
  13850. Result := True;
  13851. Exit;
  13852. end;
  13853. {$endif x86_64}
  13854. { Forward check to determine necessity of and %reg,%reg }
  13855. TransferUsedRegs(TmpUsedRegs);
  13856. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13857. { Saves on a bunch of dereferences }
  13858. ActiveReg := taicpu(p).oper[1]^.reg;
  13859. case taicpu(hp1).opcode of
  13860. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13861. if (
  13862. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13863. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13864. ) and
  13865. (
  13866. (taicpu(hp1).opcode <> A_MOV) or
  13867. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13868. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13869. ) and
  13870. not (
  13871. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13872. (taicpu(hp1).opcode = A_MOV) and
  13873. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13874. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13875. ) and
  13876. (
  13877. (
  13878. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13879. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13880. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13881. ) or
  13882. (
  13883. {$ifdef x86_64}
  13884. (
  13885. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13886. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13887. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13888. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13889. ) and
  13890. {$endif x86_64}
  13891. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13892. )
  13893. ) then
  13894. begin
  13895. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13896. RemoveCurrentP(p, hp1);
  13897. Result := True;
  13898. Exit;
  13899. end;
  13900. A_ADD,
  13901. A_AND,
  13902. A_BSF,
  13903. A_BSR,
  13904. A_BTC,
  13905. A_BTR,
  13906. A_BTS,
  13907. A_OR,
  13908. A_SUB,
  13909. A_XOR:
  13910. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13911. if (
  13912. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13913. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13914. ) and
  13915. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13916. begin
  13917. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13918. RemoveCurrentP(p, hp1);
  13919. Result := True;
  13920. Exit;
  13921. end;
  13922. A_CMP,
  13923. A_TEST:
  13924. if (
  13925. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13926. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13927. ) and
  13928. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13929. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13930. begin
  13931. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13932. RemoveCurrentP(p, hp1);
  13933. Result := True;
  13934. Exit;
  13935. end;
  13936. A_BSWAP,
  13937. A_NEG,
  13938. A_NOT:
  13939. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13940. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13941. begin
  13942. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13943. RemoveCurrentP(p, hp1);
  13944. Result := True;
  13945. Exit;
  13946. end;
  13947. else
  13948. ;
  13949. end;
  13950. end;
  13951. if (taicpu(hp1).is_jmp) and
  13952. (taicpu(hp1).opcode<>A_JMP) and
  13953. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13954. begin
  13955. { change
  13956. and x, reg
  13957. jxx
  13958. to
  13959. test x, reg
  13960. jxx
  13961. if reg is deallocated before the
  13962. jump, but only if it's a conditional jump (PFV)
  13963. }
  13964. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13965. taicpu(p).opcode := A_TEST;
  13966. Exit;
  13967. end;
  13968. Break;
  13969. end;
  13970. { Lone AND tests }
  13971. if (taicpu(p).oper[0]^.typ = top_const) then
  13972. begin
  13973. {
  13974. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13975. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13976. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13977. }
  13978. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13979. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13980. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13981. begin
  13982. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13983. if taicpu(p).opsize = S_L then
  13984. begin
  13985. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13986. Result := True;
  13987. end;
  13988. end;
  13989. end;
  13990. { Backward check to determine necessity of and %reg,%reg }
  13991. if (taicpu(p).oper[0]^.typ = top_reg) and
  13992. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13993. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13994. GetLastInstruction(p, hp2) and
  13995. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  13996. { Check size of adjacent instruction to determine if the AND is
  13997. effectively a null operation }
  13998. (
  13999. (taicpu(p).opsize = taicpu(hp2).opsize) or
  14000. { Note: Don't include S_Q }
  14001. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  14002. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  14003. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  14004. ) then
  14005. begin
  14006. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  14007. { If GetNextInstruction returned False, hp1 will be nil }
  14008. RemoveCurrentP(p, hp1);
  14009. Result := True;
  14010. Exit;
  14011. end;
  14012. end;
  14013. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  14014. var
  14015. hp1, hp2: tai;
  14016. NewRef: TReference;
  14017. Distance: Cardinal;
  14018. TempTracking: TAllUsedRegs;
  14019. { This entire nested function is used in an if-statement below, but we
  14020. want to avoid all the used reg transfers and GetNextInstruction calls
  14021. until we really have to check }
  14022. function MemRegisterNotUsedLater: Boolean; inline;
  14023. var
  14024. hp2: tai;
  14025. begin
  14026. TransferUsedRegs(TmpUsedRegs);
  14027. hp2 := p;
  14028. repeat
  14029. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14030. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14031. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  14032. end;
  14033. begin
  14034. Result := False;
  14035. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14036. (taicpu(p).oper[1]^.typ = top_reg) then
  14037. begin
  14038. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14039. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14040. (hp1.typ <> ait_instruction) or
  14041. not
  14042. (
  14043. (cs_opt_level3 in current_settings.optimizerswitches) or
  14044. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14045. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14046. ) then
  14047. Exit;
  14048. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14049. addq $x, %rax
  14050. movq %rax, %rdx
  14051. sarq $63, %rdx
  14052. (%rax still in use)
  14053. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14054. leaq $x(%rax),%rdx
  14055. addq $x, %rax
  14056. sarq $63, %rdx
  14057. ...which is okay since it breaks the dependency chain between
  14058. addq and movq, but if OptPass2MOV is called first:
  14059. addq $x, %rax
  14060. cqto
  14061. ...which is better in all ways, taking only 2 cycles to execute
  14062. and much smaller in code size.
  14063. }
  14064. { The extra register tracking is quite strenuous }
  14065. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14066. MatchInstruction(hp1, A_MOV, []) then
  14067. begin
  14068. { Update the register tracking to the MOV instruction }
  14069. CopyUsedRegs(TempTracking);
  14070. hp2 := p;
  14071. repeat
  14072. UpdateUsedRegs(tai(hp2.Next));
  14073. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14074. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14075. OptPass2ADD get called again }
  14076. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14077. begin
  14078. { Reset the tracking to the current instruction }
  14079. RestoreUsedRegs(TempTracking);
  14080. ReleaseUsedRegs(TempTracking);
  14081. Result := True;
  14082. Exit;
  14083. end;
  14084. { Reset the tracking to the current instruction }
  14085. RestoreUsedRegs(TempTracking);
  14086. ReleaseUsedRegs(TempTracking);
  14087. { If OptPass2MOV returned True, we don't need to set Result to
  14088. True if hp1 didn't change because the ADD instruction didn't
  14089. get modified and we'll be evaluating hp1 again when the
  14090. peephole optimizer reaches it }
  14091. end;
  14092. { Change:
  14093. add %reg2,%reg1
  14094. (%reg2 not modified in between)
  14095. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14096. To:
  14097. mov/s/z #(%reg1,%reg2),%reg1
  14098. }
  14099. if (taicpu(p).oper[0]^.typ = top_reg) and
  14100. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14101. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14102. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14103. (
  14104. (
  14105. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14106. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14107. { r/esp cannot be an index }
  14108. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14109. ) or (
  14110. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14111. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14112. )
  14113. ) and (
  14114. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14115. (
  14116. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14117. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14118. MemRegisterNotUsedLater
  14119. )
  14120. ) then
  14121. begin
  14122. if (
  14123. { Instructions are guaranteed to be adjacent on -O2 and under }
  14124. (cs_opt_level3 in current_settings.optimizerswitches) and
  14125. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14126. ) then
  14127. begin
  14128. { If the other register is used in between, move the MOV
  14129. instruction to right after the ADD instruction so a
  14130. saving can still be made }
  14131. Asml.Remove(hp1);
  14132. Asml.InsertAfter(hp1, p);
  14133. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14134. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14135. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14136. RemoveCurrentp(p, hp1);
  14137. end
  14138. else
  14139. begin
  14140. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14141. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14142. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14143. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14144. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14145. { hp1 may not be the immediate next instruction under -O3 }
  14146. RemoveCurrentp(p)
  14147. else
  14148. RemoveCurrentp(p, hp1);
  14149. end;
  14150. Result := True;
  14151. Exit;
  14152. end;
  14153. { Change:
  14154. addl/q $x,%reg1
  14155. movl/q %reg1,%reg2
  14156. To:
  14157. leal/q $x(%reg1),%reg2
  14158. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14159. Breaks the dependency chain.
  14160. }
  14161. if (taicpu(p).oper[0]^.typ = top_const) and
  14162. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14163. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14164. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14165. (
  14166. { Instructions are guaranteed to be adjacent on -O2 and under }
  14167. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14168. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14169. ) then
  14170. begin
  14171. TransferUsedRegs(TmpUsedRegs);
  14172. hp2 := p;
  14173. repeat
  14174. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14175. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14176. if (
  14177. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14178. not (cs_opt_size in current_settings.optimizerswitches) or
  14179. (
  14180. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14181. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14182. )
  14183. ) then
  14184. begin
  14185. { Change the MOV instruction to a LEA instruction, and update the
  14186. first operand }
  14187. reference_reset(NewRef, 1, []);
  14188. NewRef.base := taicpu(p).oper[1]^.reg;
  14189. NewRef.scalefactor := 1;
  14190. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14191. taicpu(hp1).opcode := A_LEA;
  14192. taicpu(hp1).loadref(0, NewRef);
  14193. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14194. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14195. begin
  14196. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14197. { Move what is now the LEA instruction to before the ADD instruction }
  14198. Asml.Remove(hp1);
  14199. Asml.InsertBefore(hp1, p);
  14200. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14201. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14202. p := hp1;
  14203. end
  14204. else
  14205. begin
  14206. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14207. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14208. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14209. { hp1 may not be the immediate next instruction under -O3 }
  14210. RemoveCurrentp(p)
  14211. else
  14212. RemoveCurrentp(p, hp1);
  14213. end;
  14214. Result := True;
  14215. end;
  14216. end;
  14217. end;
  14218. end;
  14219. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14220. var
  14221. SubReg: TSubRegister;
  14222. hp1, hp2: tai;
  14223. CallJmp: Boolean;
  14224. begin
  14225. Result := False;
  14226. CallJmp := False;
  14227. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14228. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14229. with taicpu(p).oper[0]^.ref^ do
  14230. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14231. if (offset = 0) then
  14232. begin
  14233. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14234. begin
  14235. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14236. taicpu(p).opcode := A_ADD;
  14237. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14238. Result := True;
  14239. end
  14240. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14241. begin
  14242. if (base <> NR_NO) then
  14243. begin
  14244. if (scalefactor <= 1) then
  14245. begin
  14246. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14247. taicpu(p).opcode := A_ADD;
  14248. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14249. Result := True;
  14250. end;
  14251. end
  14252. else
  14253. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14254. if (scalefactor in [2, 4, 8]) then
  14255. begin
  14256. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14257. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14258. taicpu(p).opcode := A_SHL;
  14259. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14260. Result := True;
  14261. end;
  14262. end;
  14263. end
  14264. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14265. lot of latency, so break off the offset if %reg3 is used soon
  14266. afterwards }
  14267. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14268. { If 3-component addresses don't have additional latency, don't
  14269. perform this optimisation }
  14270. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14271. GetNextInstruction(p, hp1) and
  14272. (hp1.typ = ait_instruction) and
  14273. (
  14274. (
  14275. { Permit jumps and calls since they have a larger degree of overhead }
  14276. (
  14277. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14278. (
  14279. { ... unless the register specifies the location }
  14280. (taicpu(hp1).ops > 0) and
  14281. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14282. )
  14283. ) and
  14284. (
  14285. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14286. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14287. )
  14288. )
  14289. or
  14290. (
  14291. { Check up to two instructions ahead }
  14292. GetNextInstruction(hp1, hp2) and
  14293. (hp2.typ = ait_instruction) and
  14294. (
  14295. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14296. (
  14297. { Same as above }
  14298. (taicpu(hp2).ops > 0) and
  14299. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14300. )
  14301. ) and
  14302. (
  14303. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14304. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14305. )
  14306. )
  14307. ) then
  14308. begin
  14309. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14310. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14311. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14312. offset := 0;
  14313. if Assigned(symbol) or Assigned(relsymbol) then
  14314. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14315. else
  14316. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14317. { Inserting before the next instruction rather than after the
  14318. current instruction gives more accurate register tracking }
  14319. asml.InsertBefore(hp2, hp1);
  14320. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14321. Result := True;
  14322. end;
  14323. end;
  14324. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14325. var
  14326. hp1, hp2: tai;
  14327. NewRef: TReference;
  14328. Distance: Cardinal;
  14329. TempTracking: TAllUsedRegs;
  14330. begin
  14331. Result := False;
  14332. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14333. MatchOpType(taicpu(p),top_const,top_reg) then
  14334. begin
  14335. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14336. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14337. (hp1.typ <> ait_instruction) or
  14338. not
  14339. (
  14340. (cs_opt_level3 in current_settings.optimizerswitches) or
  14341. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14342. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14343. ) then
  14344. Exit;
  14345. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14346. subq $x, %rax
  14347. movq %rax, %rdx
  14348. sarq $63, %rdx
  14349. (%rax still in use)
  14350. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14351. leaq $-x(%rax),%rdx
  14352. movq $x, %rax
  14353. sarq $63, %rdx
  14354. ...which is okay since it breaks the dependency chain between
  14355. subq and movq, but if OptPass2MOV is called first:
  14356. subq $x, %rax
  14357. cqto
  14358. ...which is better in all ways, taking only 2 cycles to execute
  14359. and much smaller in code size.
  14360. }
  14361. { The extra register tracking is quite strenuous }
  14362. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14363. MatchInstruction(hp1, A_MOV, []) then
  14364. begin
  14365. { Update the register tracking to the MOV instruction }
  14366. CopyUsedRegs(TempTracking);
  14367. hp2 := p;
  14368. repeat
  14369. UpdateUsedRegs(tai(hp2.Next));
  14370. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14371. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14372. OptPass2SUB get called again }
  14373. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14374. begin
  14375. { Reset the tracking to the current instruction }
  14376. RestoreUsedRegs(TempTracking);
  14377. ReleaseUsedRegs(TempTracking);
  14378. Result := True;
  14379. Exit;
  14380. end;
  14381. { Reset the tracking to the current instruction }
  14382. RestoreUsedRegs(TempTracking);
  14383. ReleaseUsedRegs(TempTracking);
  14384. { If OptPass2MOV returned True, we don't need to set Result to
  14385. True if hp1 didn't change because the SUB instruction didn't
  14386. get modified and we'll be evaluating hp1 again when the
  14387. peephole optimizer reaches it }
  14388. end;
  14389. { Change:
  14390. subl/q $x,%reg1
  14391. movl/q %reg1,%reg2
  14392. To:
  14393. leal/q $-x(%reg1),%reg2
  14394. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14395. Breaks the dependency chain and potentially permits the removal of
  14396. a CMP instruction if one follows.
  14397. }
  14398. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14399. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14400. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14401. (
  14402. { Instructions are guaranteed to be adjacent on -O2 and under }
  14403. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14404. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14405. ) then
  14406. begin
  14407. TransferUsedRegs(TmpUsedRegs);
  14408. hp2 := p;
  14409. repeat
  14410. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14411. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14412. if (
  14413. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14414. not (cs_opt_size in current_settings.optimizerswitches) or
  14415. (
  14416. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14417. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14418. )
  14419. ) then
  14420. begin
  14421. { Change the MOV instruction to a LEA instruction, and update the
  14422. first operand }
  14423. reference_reset(NewRef, 1, []);
  14424. NewRef.base := taicpu(p).oper[1]^.reg;
  14425. NewRef.scalefactor := 1;
  14426. NewRef.offset := -taicpu(p).oper[0]^.val;
  14427. taicpu(hp1).opcode := A_LEA;
  14428. taicpu(hp1).loadref(0, NewRef);
  14429. TransferUsedRegs(TmpUsedRegs);
  14430. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14431. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14432. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14433. begin
  14434. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14435. { Move what is now the LEA instruction to before the SUB instruction }
  14436. Asml.Remove(hp1);
  14437. Asml.InsertBefore(hp1, p);
  14438. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14439. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14440. p := hp1;
  14441. end
  14442. else
  14443. begin
  14444. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14445. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14446. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14447. { hp1 may not be the immediate next instruction under -O3 }
  14448. RemoveCurrentp(p)
  14449. else
  14450. RemoveCurrentp(p, hp1);
  14451. end;
  14452. Result := True;
  14453. end;
  14454. end;
  14455. end;
  14456. end;
  14457. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14458. begin
  14459. { we can skip all instructions not messing with the stack pointer }
  14460. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14461. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14462. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14463. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14464. ({(taicpu(hp1).ops=0) or }
  14465. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14466. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14467. ) and }
  14468. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14469. )
  14470. ) do
  14471. GetNextInstruction(hp1,hp1);
  14472. Result:=assigned(hp1);
  14473. end;
  14474. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14475. var
  14476. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14477. begin
  14478. Result:=false;
  14479. hp5:=nil;
  14480. hp6:=nil;
  14481. hp7:=nil;
  14482. hp8:=nil;
  14483. { replace
  14484. leal(q) x(<stackpointer>),<stackpointer>
  14485. <optional .seh_stackalloc ...>
  14486. <optional .seh_endprologue ...>
  14487. call procname
  14488. <optional NOP>
  14489. leal(q) -x(<stackpointer>),<stackpointer>
  14490. <optional VZEROUPPER>
  14491. ret
  14492. by
  14493. jmp procname
  14494. but do it only on level 4 because it destroys stack back traces
  14495. }
  14496. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14497. MatchOpType(taicpu(p),top_ref,top_reg) and
  14498. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14499. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14500. { the -8, -24, -40 are not required, but bail out early if possible,
  14501. higher values are unlikely }
  14502. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14503. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14504. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14505. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14506. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14507. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14508. GetNextInstruction(p, hp1) and
  14509. { Take a copy of hp1 }
  14510. SetAndTest(hp1, hp4) and
  14511. { trick to skip label }
  14512. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14513. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14514. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14515. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14516. SkipSimpleInstructions(hp1) and
  14517. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14518. GetNextInstruction(hp1, hp2) and
  14519. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14520. { skip nop instruction on win64 }
  14521. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14522. SetAndTest(hp2,hp6) and
  14523. GetNextInstruction(hp2,hp2) and
  14524. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14525. ) and
  14526. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14527. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14528. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14529. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14530. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14531. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14532. { Segment register will be NR_NO }
  14533. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14534. GetNextInstruction(hp2, hp3) and
  14535. { trick to skip label }
  14536. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14537. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14538. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14539. SetAndTest(hp3,hp5) and
  14540. GetNextInstruction(hp3,hp3) and
  14541. MatchInstruction(hp3,A_RET,[S_NO])
  14542. )
  14543. ) and
  14544. (taicpu(hp3).ops=0) then
  14545. begin
  14546. taicpu(hp1).opcode := A_JMP;
  14547. taicpu(hp1).is_jmp := true;
  14548. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14549. { search for the stackalloc directive and remove it }
  14550. hp7:=tai(p.next);
  14551. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14552. begin
  14553. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14554. begin
  14555. { sanity check }
  14556. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14557. Internalerror(2024012201);
  14558. hp8:=tai(hp7.next);
  14559. RemoveInstruction(tai(hp7));
  14560. hp7:=hp8;
  14561. break;
  14562. end
  14563. else
  14564. hp7:=tai(hp7.next);
  14565. end;
  14566. RemoveCurrentP(p, hp4);
  14567. RemoveInstruction(hp2);
  14568. RemoveInstruction(hp3);
  14569. { if there is a vzeroupper instruction then move it before the jmp }
  14570. if Assigned(hp5) then
  14571. begin
  14572. AsmL.Remove(hp5);
  14573. ASmL.InsertBefore(hp5,hp1)
  14574. end;
  14575. { remove nop on win64 }
  14576. if Assigned(hp6) then
  14577. RemoveInstruction(hp6);
  14578. Result:=true;
  14579. end;
  14580. end;
  14581. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14582. {$ifdef x86_64}
  14583. var
  14584. hp1, hp2, hp3, hp4, hp5: tai;
  14585. {$endif x86_64}
  14586. begin
  14587. Result:=false;
  14588. {$ifdef x86_64}
  14589. hp5:=nil;
  14590. { replace
  14591. push %rax
  14592. call procname
  14593. pop %rcx
  14594. ret
  14595. by
  14596. jmp procname
  14597. but do it only on level 4 because it destroys stack back traces
  14598. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14599. for all supported calling conventions
  14600. }
  14601. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14602. MatchOpType(taicpu(p),top_reg) and
  14603. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14604. GetNextInstruction(p, hp1) and
  14605. { Take a copy of hp1 }
  14606. SetAndTest(hp1, hp4) and
  14607. { trick to skip label }
  14608. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14609. SkipSimpleInstructions(hp1) and
  14610. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14611. GetNextInstruction(hp1, hp2) and
  14612. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14613. MatchOpType(taicpu(hp2),top_reg) and
  14614. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14615. GetNextInstruction(hp2, hp3) and
  14616. { trick to skip label }
  14617. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14618. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14619. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14620. SetAndTest(hp3,hp5) and
  14621. GetNextInstruction(hp3,hp3) and
  14622. MatchInstruction(hp3,A_RET,[S_NO])
  14623. )
  14624. ) and
  14625. (taicpu(hp3).ops=0) then
  14626. begin
  14627. taicpu(hp1).opcode := A_JMP;
  14628. taicpu(hp1).is_jmp := true;
  14629. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14630. RemoveCurrentP(p, hp4);
  14631. RemoveInstruction(hp2);
  14632. RemoveInstruction(hp3);
  14633. if Assigned(hp5) then
  14634. begin
  14635. AsmL.Remove(hp5);
  14636. ASmL.InsertBefore(hp5,hp1)
  14637. end;
  14638. Result:=true;
  14639. end;
  14640. {$endif x86_64}
  14641. end;
  14642. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14643. var
  14644. Value, RegName: string;
  14645. hp1: tai;
  14646. begin
  14647. Result:=false;
  14648. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14649. begin
  14650. case taicpu(p).oper[0]^.val of
  14651. 0:
  14652. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14653. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14654. (
  14655. { See if we can still convert the instruction }
  14656. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14657. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14658. ) then
  14659. begin
  14660. { change "mov $0,%reg" into "xor %reg,%reg" }
  14661. taicpu(p).opcode := A_XOR;
  14662. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14663. Result := True;
  14664. {$ifdef x86_64}
  14665. end
  14666. else if (taicpu(p).opsize = S_Q) then
  14667. begin
  14668. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14669. { The actual optimization }
  14670. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14671. taicpu(p).changeopsize(S_L);
  14672. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14673. Result := True;
  14674. end;
  14675. $1..$FFFFFFFF:
  14676. begin
  14677. { Code size reduction by J. Gareth "Kit" Moreton }
  14678. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14679. case taicpu(p).opsize of
  14680. S_Q:
  14681. begin
  14682. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14683. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14684. { The actual optimization }
  14685. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14686. taicpu(p).changeopsize(S_L);
  14687. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14688. Result := True;
  14689. end;
  14690. else
  14691. { Do nothing };
  14692. end;
  14693. {$endif x86_64}
  14694. end;
  14695. -1:
  14696. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14697. if (cs_opt_size in current_settings.optimizerswitches) and
  14698. (taicpu(p).opsize <> S_B) and
  14699. (
  14700. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14701. (
  14702. { See if we can still convert the instruction }
  14703. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14704. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14705. )
  14706. ) then
  14707. begin
  14708. { change "mov $-1,%reg" into "or $-1,%reg" }
  14709. { NOTES:
  14710. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14711. - This operation creates a false dependency on the register, so only do it when optimising for size
  14712. - 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
  14713. }
  14714. taicpu(p).opcode := A_OR;
  14715. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14716. Result := True;
  14717. end;
  14718. else
  14719. { Do nothing };
  14720. end;
  14721. end;
  14722. end;
  14723. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14724. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14725. begin
  14726. Result := False;
  14727. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14728. Exit;
  14729. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14730. so don't bother optimising }
  14731. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14732. Exit;
  14733. if (taicpu(p).oper[0]^.typ <> top_const) or
  14734. { If the value can fit into an 8-bit signed integer, a smaller
  14735. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14736. falls within this range }
  14737. (
  14738. (taicpu(p).oper[0]^.val > -128) and
  14739. (taicpu(p).oper[0]^.val <= 127)
  14740. ) then
  14741. Exit;
  14742. { If we're optimising for size, this is acceptable }
  14743. if (cs_opt_size in current_settings.optimizerswitches) then
  14744. Exit(True);
  14745. if (taicpu(p).oper[1]^.typ = top_reg) and
  14746. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14747. Exit(True);
  14748. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14749. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14750. Exit(True);
  14751. end;
  14752. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14753. var
  14754. hp1: tai;
  14755. Value: TCGInt;
  14756. begin
  14757. Result := False;
  14758. if MatchOpType(taicpu(p), top_const, top_reg) then
  14759. begin
  14760. { Detect:
  14761. andw x, %ax (0 <= x < $8000)
  14762. ...
  14763. movzwl %ax,%eax
  14764. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14765. }
  14766. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14767. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14768. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14769. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14770. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14771. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14772. begin
  14773. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14774. taicpu(hp1).opcode := A_CWDE;
  14775. taicpu(hp1).clearop(0);
  14776. taicpu(hp1).clearop(1);
  14777. taicpu(hp1).ops := 0;
  14778. { A change was made, but not with p, so don't set Result, but
  14779. notify the compiler that a change was made }
  14780. Include(OptsToCheck, aoc_ForceNewIteration);
  14781. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14782. end;
  14783. end;
  14784. { If "not x" is a power of 2 (popcnt = 1), change:
  14785. and $x, %reg/ref
  14786. To:
  14787. btr lb(x), %reg/ref
  14788. }
  14789. if IsBTXAcceptable(p) and
  14790. (
  14791. { Make sure a TEST doesn't follow that plays with the register }
  14792. not GetNextInstruction(p, hp1) or
  14793. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14794. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14795. ) then
  14796. begin
  14797. {$push}{$R-}{$Q-}
  14798. { Value is a sign-extended 32-bit integer - just correct it
  14799. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14800. checks to see if this operand is an immediate. }
  14801. Value := not taicpu(p).oper[0]^.val;
  14802. {$pop}
  14803. {$ifdef x86_64}
  14804. if taicpu(p).opsize = S_L then
  14805. {$endif x86_64}
  14806. Value := Value and $FFFFFFFF;
  14807. if (PopCnt(QWord(Value)) = 1) then
  14808. begin
  14809. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14810. taicpu(p).opcode := A_BTR;
  14811. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14812. Result := True;
  14813. Exit;
  14814. end;
  14815. end;
  14816. end;
  14817. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14818. begin
  14819. Result := False;
  14820. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14821. Exit;
  14822. { Convert:
  14823. movswl %ax,%eax -> cwtl
  14824. movslq %eax,%rax -> cdqe
  14825. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14826. refer to the same opcode and depends only on the assembler's
  14827. current operand-size attribute. [Kit]
  14828. }
  14829. with taicpu(p) do
  14830. case opsize of
  14831. S_WL:
  14832. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14833. begin
  14834. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14835. opcode := A_CWDE;
  14836. clearop(0);
  14837. clearop(1);
  14838. ops := 0;
  14839. Result := True;
  14840. end;
  14841. {$ifdef x86_64}
  14842. S_LQ:
  14843. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14844. begin
  14845. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14846. opcode := A_CDQE;
  14847. clearop(0);
  14848. clearop(1);
  14849. ops := 0;
  14850. Result := True;
  14851. end;
  14852. {$endif x86_64}
  14853. else
  14854. ;
  14855. end;
  14856. end;
  14857. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14858. var
  14859. hp1, hp2: tai;
  14860. IdentityMask, Shift: TCGInt;
  14861. LimitSize: Topsize;
  14862. DoNotMerge: Boolean;
  14863. begin
  14864. Result := False;
  14865. { All these optimisations work on "shr const,%reg" }
  14866. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14867. Exit;
  14868. DoNotMerge := False;
  14869. Shift := taicpu(p).oper[0]^.val;
  14870. LimitSize := taicpu(p).opsize;
  14871. hp1 := p;
  14872. repeat
  14873. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14874. Break;
  14875. { Detect:
  14876. shr x, %reg
  14877. and y, %reg
  14878. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14879. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14880. }
  14881. case taicpu(hp1).opcode of
  14882. A_AND:
  14883. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14884. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14885. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14886. begin
  14887. { Make sure the FLAGS register isn't in use }
  14888. TransferUsedRegs(TmpUsedRegs);
  14889. hp2 := p;
  14890. repeat
  14891. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14892. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14893. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14894. begin
  14895. { Generate the identity mask }
  14896. case taicpu(p).opsize of
  14897. S_B:
  14898. IdentityMask := $FF shr Shift;
  14899. S_W:
  14900. IdentityMask := $FFFF shr Shift;
  14901. S_L:
  14902. IdentityMask := $FFFFFFFF shr Shift;
  14903. {$ifdef x86_64}
  14904. S_Q:
  14905. { We need to force the operands to be unsigned 64-bit
  14906. integers otherwise the wrong value is generated }
  14907. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14908. {$endif x86_64}
  14909. else
  14910. InternalError(2022081501);
  14911. end;
  14912. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14913. begin
  14914. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14915. { All the possible 1 bits are covered, so we can remove the AND }
  14916. hp2 := tai(hp1.Previous);
  14917. RemoveInstruction(hp1);
  14918. { p wasn't actually changed, so don't set Result to True,
  14919. but a change was nonetheless made elsewhere }
  14920. Include(OptsToCheck, aoc_ForceNewIteration);
  14921. { Do another pass in case other AND or MOVZX instructions
  14922. follow }
  14923. hp1 := hp2;
  14924. Continue;
  14925. end;
  14926. end;
  14927. end;
  14928. A_TEST, A_CMP, A_Jcc:
  14929. { Skip over conditional jumps and relevant comparisons }
  14930. Continue;
  14931. A_MOVZX:
  14932. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14933. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14934. begin
  14935. { Since the original register is being read as is, subsequent
  14936. SHRs must not be merged at this point }
  14937. DoNotMerge := True;
  14938. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14939. begin
  14940. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14941. begin
  14942. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14943. { All the possible 1 bits are covered, so we can remove the AND }
  14944. hp2 := tai(hp1.Previous);
  14945. RemoveInstruction(hp1);
  14946. hp1 := hp2;
  14947. end
  14948. else { Different register target }
  14949. begin
  14950. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14951. taicpu(hp1).opcode := A_MOV;
  14952. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14953. case taicpu(hp1).opsize of
  14954. S_BW:
  14955. taicpu(hp1).opsize := S_W;
  14956. S_BL, S_WL:
  14957. taicpu(hp1).opsize := S_L;
  14958. else
  14959. InternalError(2022081503);
  14960. end;
  14961. end;
  14962. end
  14963. else if (Shift > 0) and
  14964. (taicpu(p).opsize = S_W) and
  14965. (taicpu(hp1).opsize = S_WL) and
  14966. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14967. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14968. begin
  14969. { Detect:
  14970. shr x, %ax (x > 0)
  14971. ...
  14972. movzwl %ax,%eax
  14973. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14974. }
  14975. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14976. taicpu(hp1).opcode := A_CWDE;
  14977. taicpu(hp1).clearop(0);
  14978. taicpu(hp1).clearop(1);
  14979. taicpu(hp1).ops := 0;
  14980. end;
  14981. { Move onto the next instruction }
  14982. Continue;
  14983. end;
  14984. A_SHL, A_SAL, A_SHR:
  14985. if (taicpu(hp1).opsize <= LimitSize) and
  14986. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14987. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14988. begin
  14989. { Make sure the sizes don't exceed the register size limit
  14990. (measured by the shift value falling below the limit) }
  14991. if taicpu(hp1).opsize < LimitSize then
  14992. LimitSize := taicpu(hp1).opsize;
  14993. if taicpu(hp1).opcode = A_SHR then
  14994. Inc(Shift, taicpu(hp1).oper[0]^.val)
  14995. else
  14996. begin
  14997. Dec(Shift, taicpu(hp1).oper[0]^.val);
  14998. DoNotMerge := True;
  14999. end;
  15000. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  15001. Break;
  15002. { Since we've established that the combined shift is within
  15003. limits, we can actually combine the adjacent SHR
  15004. instructions even if they're different sizes }
  15005. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  15006. begin
  15007. hp2 := tai(hp1.Previous);
  15008. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  15009. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  15010. RemoveInstruction(hp1);
  15011. hp1 := hp2;
  15012. end;
  15013. { Move onto the next instruction }
  15014. Continue;
  15015. end;
  15016. else
  15017. ;
  15018. end;
  15019. Break;
  15020. until False;
  15021. { Detect the following (looking backwards):
  15022. shr %cl,%reg
  15023. shr x, %reg
  15024. Swap the two SHR instructions to minimise a pipeline stall.
  15025. }
  15026. if GetLastInstruction(p, hp1) and
  15027. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  15028. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  15029. { First operand will be %cl }
  15030. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  15031. { Just to be sure }
  15032. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  15033. begin
  15034. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  15035. { Moving the entries this way ensures the register tracking remains correct }
  15036. Asml.Remove(p);
  15037. Asml.InsertBefore(p, hp1);
  15038. p := hp1;
  15039. { Don't set Result to True because the current instruction is now
  15040. "shr %cl,%reg" and there's nothing more we can do with it }
  15041. end;
  15042. end;
  15043. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15044. var
  15045. hp1, hp2: tai;
  15046. Opposite, SecondOpposite: TAsmOp;
  15047. NewCond: TAsmCond;
  15048. begin
  15049. Result := False;
  15050. { Change:
  15051. add/sub 128,(dest)
  15052. To:
  15053. sub/add -128,(dest)
  15054. This generaally takes fewer bytes to encode because -128 can be stored
  15055. in a signed byte, whereas +128 cannot.
  15056. }
  15057. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15058. begin
  15059. if taicpu(p).opcode = A_ADD then
  15060. Opposite := A_SUB
  15061. else
  15062. Opposite := A_ADD;
  15063. { Be careful if the flags are in use, because the CF flag inverts
  15064. when changing from ADD to SUB and vice versa }
  15065. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15066. GetNextInstruction(p, hp1) then
  15067. begin
  15068. TransferUsedRegs(TmpUsedRegs);
  15069. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15070. hp2 := hp1;
  15071. { Scan ahead to check if everything's safe }
  15072. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15073. begin
  15074. if (hp1.typ <> ait_instruction) then
  15075. { Probably unsafe since the flags are still in use }
  15076. Exit;
  15077. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15078. { Stop searching at an unconditional jump }
  15079. Break;
  15080. if not
  15081. (
  15082. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15083. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15084. ) and
  15085. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15086. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15087. Exit;
  15088. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15089. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15090. { Move to the next instruction }
  15091. GetNextInstruction(hp1, hp1);
  15092. end;
  15093. while Assigned(hp2) and (hp2 <> hp1) do
  15094. begin
  15095. NewCond := C_None;
  15096. case taicpu(hp2).condition of
  15097. C_A, C_NBE:
  15098. NewCond := C_BE;
  15099. C_B, C_C, C_NAE:
  15100. NewCond := C_AE;
  15101. C_AE, C_NB, C_NC:
  15102. NewCond := C_B;
  15103. C_BE, C_NA:
  15104. NewCond := C_A;
  15105. else
  15106. { No change needed };
  15107. end;
  15108. if NewCond <> C_None then
  15109. begin
  15110. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15111. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15112. taicpu(hp2).condition := NewCond;
  15113. end
  15114. else
  15115. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15116. begin
  15117. { Because of the flipping of the carry bit, to ensure
  15118. the operation remains equivalent, ADC becomes SBB
  15119. and vice versa, and the constant is not-inverted.
  15120. If multiple ADCs or SBBs appear in a row, each one
  15121. changed causes the carry bit to invert, so they all
  15122. need to be flipped }
  15123. if taicpu(hp2).opcode = A_ADC then
  15124. SecondOpposite := A_SBB
  15125. else
  15126. SecondOpposite := A_ADC;
  15127. if taicpu(hp2).oper[0]^.typ <> top_const then
  15128. { Should have broken out of this optimisation already }
  15129. InternalError(2021112901);
  15130. 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]^) + ' -> ' +
  15131. 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);
  15132. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15133. taicpu(hp2).opcode := SecondOpposite;
  15134. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15135. end;
  15136. { Move to the next instruction }
  15137. GetNextInstruction(hp2, hp2);
  15138. end;
  15139. if (hp2 <> hp1) then
  15140. InternalError(2021111501);
  15141. end;
  15142. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15143. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15144. taicpu(p).opcode := Opposite;
  15145. taicpu(p).oper[0]^.val := -128;
  15146. { No further optimisations can be made on this instruction, so move
  15147. onto the next one to save time }
  15148. p := tai(p.Next);
  15149. UpdateUsedRegs(p);
  15150. Result := True;
  15151. Exit;
  15152. end;
  15153. { Detect:
  15154. add/sub %reg2,(dest)
  15155. add/sub x, (dest)
  15156. (dest can be a register or a reference)
  15157. Swap the instructions to minimise a pipeline stall. This reverses the
  15158. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15159. optimisations could be made.
  15160. }
  15161. if (taicpu(p).oper[0]^.typ = top_reg) and
  15162. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15163. (
  15164. (
  15165. (taicpu(p).oper[1]^.typ = top_reg) and
  15166. { We can try searching further ahead if we're writing to a register }
  15167. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15168. ) or
  15169. (
  15170. (taicpu(p).oper[1]^.typ = top_ref) and
  15171. GetNextInstruction(p, hp1)
  15172. )
  15173. ) and
  15174. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15175. (taicpu(hp1).oper[0]^.typ = top_const) and
  15176. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15177. begin
  15178. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15179. TransferUsedRegs(TmpUsedRegs);
  15180. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15181. hp2 := p;
  15182. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15183. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15184. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15185. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15186. begin
  15187. asml.remove(hp1);
  15188. asml.InsertBefore(hp1, p);
  15189. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15190. Result := True;
  15191. end;
  15192. end;
  15193. end;
  15194. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15195. var
  15196. hp1: tai;
  15197. begin
  15198. Result:=false;
  15199. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15200. while GetNextInstruction(p, hp1) and
  15201. TrySwapMovCmp(p, hp1) do
  15202. begin
  15203. if MatchInstruction(hp1, A_MOV, []) then
  15204. begin
  15205. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15206. begin
  15207. { A little hacky, but since CMP doesn't read the flags, only
  15208. modify them, it's safe if they get scrambled by MOV -> XOR }
  15209. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15210. Result := PostPeepholeOptMov(hp1);
  15211. {$ifdef x86_64}
  15212. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15213. { Used to shrink instruction size }
  15214. PostPeepholeOptXor(hp1);
  15215. {$endif x86_64}
  15216. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15217. end
  15218. else
  15219. begin
  15220. Result := PostPeepholeOptMov(hp1);
  15221. {$ifdef x86_64}
  15222. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15223. { Used to shrink instruction size }
  15224. PostPeepholeOptXor(hp1);
  15225. {$endif x86_64}
  15226. end;
  15227. end;
  15228. { Enabling this flag is actually a null operation, but it marks
  15229. the code as 'modified' during this pass }
  15230. Include(OptsToCheck, aoc_ForceNewIteration);
  15231. end;
  15232. { change "cmp $0, %reg" to "test %reg, %reg" }
  15233. if MatchOpType(taicpu(p),top_const,top_reg) and
  15234. (taicpu(p).oper[0]^.val = 0) then
  15235. begin
  15236. taicpu(p).opcode := A_TEST;
  15237. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15238. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15239. Result:=true;
  15240. end;
  15241. end;
  15242. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15243. var
  15244. IsTestConstX, IsValid : Boolean;
  15245. hp1,hp2 : tai;
  15246. begin
  15247. Result:=false;
  15248. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15249. if (taicpu(p).opcode = A_TEST) then
  15250. while GetNextInstruction(p, hp1) and
  15251. TrySwapMovCmp(p, hp1) do
  15252. begin
  15253. if MatchInstruction(hp1, A_MOV, []) then
  15254. begin
  15255. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15256. begin
  15257. { A little hacky, but since TEST doesn't read the flags, only
  15258. modify them, it's safe if they get scrambled by MOV -> XOR }
  15259. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15260. Result := PostPeepholeOptMov(hp1);
  15261. {$ifdef x86_64}
  15262. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15263. { Used to shrink instruction size }
  15264. PostPeepholeOptXor(hp1);
  15265. {$endif x86_64}
  15266. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15267. end
  15268. else
  15269. begin
  15270. Result := PostPeepholeOptMov(hp1);
  15271. {$ifdef x86_64}
  15272. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15273. { Used to shrink instruction size }
  15274. PostPeepholeOptXor(hp1);
  15275. {$endif x86_64}
  15276. end;
  15277. end;
  15278. { Enabling this flag is actually a null operation, but it marks
  15279. the code as 'modified' during this pass }
  15280. Include(OptsToCheck, aoc_ForceNewIteration);
  15281. end;
  15282. { If x is a power of 2 (popcnt = 1), change:
  15283. or $x, %reg/ref
  15284. To:
  15285. bts lb(x), %reg/ref
  15286. }
  15287. if (taicpu(p).opcode = A_OR) and
  15288. IsBTXAcceptable(p) and
  15289. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15290. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15291. (
  15292. { Don't optimise if a test instruction follows }
  15293. not GetNextInstruction(p, hp1) or
  15294. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15295. ) then
  15296. begin
  15297. DebugMsg(SPeepholeOptimization + 'Changed OR $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BTS $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Or2Bts)', p);
  15298. taicpu(p).opcode := A_BTS;
  15299. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15300. Result := True;
  15301. Exit;
  15302. end;
  15303. { If x is a power of 2 (popcnt = 1), change:
  15304. test $x, %reg/ref
  15305. je / sete / cmove (or jne / setne)
  15306. To:
  15307. bt lb(x), %reg/ref
  15308. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15309. }
  15310. if (taicpu(p).opcode = A_TEST) and
  15311. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15312. (taicpu(p).oper[0]^.typ = top_const) and
  15313. (
  15314. (cs_opt_size in current_settings.optimizerswitches) or
  15315. (
  15316. (taicpu(p).oper[1]^.typ = top_reg) and
  15317. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15318. ) or
  15319. (
  15320. (taicpu(p).oper[1]^.typ <> top_reg) and
  15321. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15322. )
  15323. ) and
  15324. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15325. { For sizes less than S_L, the byte size is equal or larger with BT,
  15326. so don't bother optimising }
  15327. (taicpu(p).opsize >= S_L) then
  15328. begin
  15329. IsValid := True;
  15330. { Check the next set of instructions, watching the FLAGS register
  15331. and the conditions used }
  15332. TransferUsedRegs(TmpUsedRegs);
  15333. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15334. hp1 := p;
  15335. hp2 := nil;
  15336. while GetNextInstruction(hp1, hp1) do
  15337. begin
  15338. if not Assigned(hp2) then
  15339. { The first instruction after TEST }
  15340. hp2 := hp1;
  15341. if (hp1.typ <> ait_instruction) then
  15342. begin
  15343. { If the flags are no longer in use, everything is fine }
  15344. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15345. IsValid := False;
  15346. Break;
  15347. end;
  15348. case taicpu(hp1).condition of
  15349. C_None:
  15350. begin
  15351. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15352. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15353. { Something is not quite normal, so play safe and don't change }
  15354. IsValid := False;
  15355. Break;
  15356. end;
  15357. C_E, C_Z, C_NE, C_NZ:
  15358. { This is fine };
  15359. else
  15360. begin
  15361. { Unsupported condition }
  15362. IsValid := False;
  15363. Break;
  15364. end;
  15365. end;
  15366. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15367. end;
  15368. if IsValid then
  15369. begin
  15370. while hp2 <> hp1 do
  15371. begin
  15372. case taicpu(hp2).condition of
  15373. C_Z, C_E:
  15374. taicpu(hp2).condition := C_NC;
  15375. C_NZ, C_NE:
  15376. taicpu(hp2).condition := C_C;
  15377. else
  15378. { Should not get this by this point }
  15379. InternalError(2022110701);
  15380. end;
  15381. GetNextInstruction(hp2, hp2);
  15382. end;
  15383. DebugMsg(SPeepholeOptimization + 'Changed TEST $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BT $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Test2Bt)', p);
  15384. taicpu(p).opcode := A_BT;
  15385. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15386. Result := True;
  15387. Exit;
  15388. end;
  15389. end;
  15390. { removes the line marked with (x) from the sequence
  15391. and/or/xor/add/sub/... $x, %y
  15392. test/or %y, %y | test $-1, %y (x)
  15393. j(n)z _Label
  15394. as the first instruction already adjusts the ZF
  15395. %y operand may also be a reference }
  15396. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15397. MatchOperand(taicpu(p).oper[0]^,-1);
  15398. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15399. GetLastInstruction(p, hp1) and
  15400. (tai(hp1).typ = ait_instruction) and
  15401. GetNextInstruction(p,hp2) and
  15402. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15403. case taicpu(hp1).opcode Of
  15404. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15405. { These two instructions set the zero flag if the result is zero }
  15406. A_POPCNT, A_LZCNT:
  15407. begin
  15408. if (
  15409. { With POPCNT, an input of zero will set the zero flag
  15410. because the population count of zero is zero }
  15411. (taicpu(hp1).opcode = A_POPCNT) and
  15412. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15413. (
  15414. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15415. { Faster than going through the second half of the 'or'
  15416. condition below }
  15417. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15418. )
  15419. ) or (
  15420. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15421. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15422. { and in case of carry for A(E)/B(E)/C/NC }
  15423. (
  15424. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15425. (
  15426. (taicpu(hp1).opcode <> A_ADD) and
  15427. (taicpu(hp1).opcode <> A_SUB) and
  15428. (taicpu(hp1).opcode <> A_LZCNT)
  15429. )
  15430. )
  15431. ) then
  15432. begin
  15433. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15434. RemoveCurrentP(p, hp2);
  15435. Result:=true;
  15436. Exit;
  15437. end;
  15438. end;
  15439. A_SHL, A_SAL, A_SHR, A_SAR:
  15440. begin
  15441. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15442. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15443. { therefore, it's only safe to do this optimization for }
  15444. { shifts by a (nonzero) constant }
  15445. (taicpu(hp1).oper[0]^.typ = top_const) and
  15446. (taicpu(hp1).oper[0]^.val <> 0) and
  15447. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15448. { and in case of carry for A(E)/B(E)/C/NC }
  15449. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15450. begin
  15451. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15452. RemoveCurrentP(p, hp2);
  15453. Result:=true;
  15454. Exit;
  15455. end;
  15456. end;
  15457. A_DEC, A_INC, A_NEG:
  15458. begin
  15459. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15460. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15461. { and in case of carry for A(E)/B(E)/C/NC }
  15462. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15463. begin
  15464. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15465. RemoveCurrentP(p, hp2);
  15466. Result:=true;
  15467. Exit;
  15468. end;
  15469. end;
  15470. A_ANDN, A_BZHI:
  15471. begin
  15472. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15473. { Only the zero and sign flags are consistent with what the result is }
  15474. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15475. begin
  15476. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15477. RemoveCurrentP(p, hp2);
  15478. Result:=true;
  15479. Exit;
  15480. end;
  15481. end;
  15482. A_BEXTR:
  15483. begin
  15484. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15485. { Only the zero flag is set }
  15486. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15487. begin
  15488. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15489. RemoveCurrentP(p, hp2);
  15490. Result:=true;
  15491. Exit;
  15492. end;
  15493. end;
  15494. else
  15495. ;
  15496. end; { case }
  15497. { change "test $-1,%reg" into "test %reg,%reg" }
  15498. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15499. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15500. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15501. if MatchInstruction(p, A_OR, []) and
  15502. { Can only match if they're both registers }
  15503. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15504. begin
  15505. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15506. taicpu(p).opcode := A_TEST;
  15507. { No need to set Result to True, as we've done all the optimisations we can }
  15508. end;
  15509. end;
  15510. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15511. var
  15512. hp1,hp3 : tai;
  15513. {$ifndef x86_64}
  15514. hp2 : taicpu;
  15515. {$endif x86_64}
  15516. begin
  15517. Result:=false;
  15518. hp3:=nil;
  15519. {$ifndef x86_64}
  15520. { don't do this on modern CPUs, this really hurts them due to
  15521. broken call/ret pairing }
  15522. if (current_settings.optimizecputype < cpu_Pentium2) and
  15523. not(cs_create_pic in current_settings.moduleswitches) and
  15524. GetNextInstruction(p, hp1) and
  15525. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15526. MatchOpType(taicpu(hp1),top_ref) and
  15527. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15528. begin
  15529. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15530. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15531. InsertLLItem(p.previous, p, hp2);
  15532. taicpu(p).opcode := A_JMP;
  15533. taicpu(p).is_jmp := true;
  15534. RemoveInstruction(hp1);
  15535. Result:=true;
  15536. end
  15537. else
  15538. {$endif x86_64}
  15539. { replace
  15540. call procname
  15541. ret
  15542. by
  15543. jmp procname
  15544. but do it only on level 4 because it destroys stack back traces
  15545. else if the subroutine is marked as no return, remove the ret
  15546. }
  15547. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15548. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15549. GetNextInstruction(p, hp1) and
  15550. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15551. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15552. SetAndTest(hp1,hp3) and
  15553. GetNextInstruction(hp1,hp1) and
  15554. MatchInstruction(hp1,A_RET,[S_NO])
  15555. )
  15556. ) and
  15557. (taicpu(hp1).ops=0) then
  15558. begin
  15559. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15560. { we might destroy stack alignment here if we do not do a call }
  15561. (target_info.stackalign<=sizeof(SizeUInt)) then
  15562. begin
  15563. taicpu(p).opcode := A_JMP;
  15564. taicpu(p).is_jmp := true;
  15565. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15566. end
  15567. else
  15568. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15569. RemoveInstruction(hp1);
  15570. if Assigned(hp3) then
  15571. begin
  15572. AsmL.Remove(hp3);
  15573. AsmL.InsertBefore(hp3,p)
  15574. end;
  15575. Result:=true;
  15576. end;
  15577. end;
  15578. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15579. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15580. begin
  15581. case OpSize of
  15582. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15583. Result := (Val <= $FF) and (Val >= -128);
  15584. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15585. Result := (Val <= $FFFF) and (Val >= -32768);
  15586. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15587. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15588. else
  15589. Result := True;
  15590. end;
  15591. end;
  15592. var
  15593. hp1, hp2 : tai;
  15594. SizeChange: Boolean;
  15595. PreMessage: string;
  15596. begin
  15597. Result := False;
  15598. if (taicpu(p).oper[0]^.typ = top_reg) and
  15599. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15600. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15601. begin
  15602. { Change (using movzbl %al,%eax as an example):
  15603. movzbl %al, %eax movzbl %al, %eax
  15604. cmpl x, %eax testl %eax,%eax
  15605. To:
  15606. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15607. movzbl %al, %eax movzbl %al, %eax
  15608. Smaller instruction and minimises pipeline stall as the CPU
  15609. doesn't have to wait for the register to get zero-extended. [Kit]
  15610. Also allow if the smaller of the two registers is being checked,
  15611. as this still removes the false dependency.
  15612. }
  15613. if
  15614. (
  15615. (
  15616. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15617. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15618. ) or (
  15619. { If MatchOperand returns True, they must both be registers }
  15620. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15621. )
  15622. ) and
  15623. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15624. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15625. begin
  15626. 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);
  15627. asml.Remove(hp1);
  15628. asml.InsertBefore(hp1, p);
  15629. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15630. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15631. begin
  15632. taicpu(hp1).opcode := A_TEST;
  15633. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15634. end;
  15635. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15636. case taicpu(p).opsize of
  15637. S_BW, S_BL:
  15638. begin
  15639. SizeChange := taicpu(hp1).opsize <> S_B;
  15640. taicpu(hp1).changeopsize(S_B);
  15641. end;
  15642. S_WL:
  15643. begin
  15644. SizeChange := taicpu(hp1).opsize <> S_W;
  15645. taicpu(hp1).changeopsize(S_W);
  15646. end
  15647. else
  15648. InternalError(2020112701);
  15649. end;
  15650. UpdateUsedRegs(tai(p.Next));
  15651. { Check if the register is used aferwards - if not, we can
  15652. remove the movzx instruction completely }
  15653. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15654. begin
  15655. { Hp1 is a better position than p for debugging purposes }
  15656. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15657. RemoveCurrentp(p, hp1);
  15658. Result := True;
  15659. end;
  15660. if SizeChange then
  15661. DebugMsg(SPeepholeOptimization + PreMessage +
  15662. 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)
  15663. else
  15664. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15665. Exit;
  15666. end;
  15667. { Change (using movzwl %ax,%eax as an example):
  15668. movzwl %ax, %eax
  15669. movb %al, (dest) (Register is smaller than read register in movz)
  15670. To:
  15671. movb %al, (dest) (Move one back to avoid a false dependency)
  15672. movzwl %ax, %eax
  15673. }
  15674. if (taicpu(hp1).opcode = A_MOV) and
  15675. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15676. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15677. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15678. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15679. begin
  15680. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15681. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15682. asml.Remove(hp1);
  15683. asml.InsertBefore(hp1, p);
  15684. if taicpu(hp1).oper[1]^.typ = top_reg then
  15685. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15686. { Check if the register is used aferwards - if not, we can
  15687. remove the movzx instruction completely }
  15688. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15689. begin
  15690. { Hp1 is a better position than p for debugging purposes }
  15691. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15692. RemoveCurrentp(p, hp1);
  15693. Result := True;
  15694. end;
  15695. Exit;
  15696. end;
  15697. end;
  15698. end;
  15699. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15700. var
  15701. hp1: tai;
  15702. {$ifdef x86_64}
  15703. PreMessage, RegName: string;
  15704. {$endif x86_64}
  15705. begin
  15706. Result := False;
  15707. { If x is a power of 2 (popcnt = 1), change:
  15708. xor $x, %reg/ref
  15709. To:
  15710. btc lb(x), %reg/ref
  15711. }
  15712. if IsBTXAcceptable(p) and
  15713. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15714. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15715. (
  15716. { Don't optimise if a test instruction follows }
  15717. not GetNextInstruction(p, hp1) or
  15718. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15719. ) then
  15720. begin
  15721. DebugMsg(SPeepholeOptimization + 'Changed XOR $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BTC $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Xor2Btc)', p);
  15722. taicpu(p).opcode := A_BTC;
  15723. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15724. Result := True;
  15725. Exit;
  15726. end;
  15727. {$ifdef x86_64}
  15728. { Code size reduction by J. Gareth "Kit" Moreton }
  15729. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15730. as this removes the REX prefix }
  15731. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15732. Exit;
  15733. if taicpu(p).oper[0]^.typ <> top_reg then
  15734. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15735. InternalError(2018011500);
  15736. case taicpu(p).opsize of
  15737. S_Q:
  15738. begin
  15739. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15740. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15741. { The actual optimization }
  15742. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15743. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15744. taicpu(p).changeopsize(S_L);
  15745. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15746. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15747. end;
  15748. else
  15749. ;
  15750. end;
  15751. {$endif x86_64}
  15752. end;
  15753. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15754. var
  15755. XReg: TRegister;
  15756. begin
  15757. Result := False;
  15758. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15759. Smaller encoding and slightly faster on some platforms (also works for
  15760. ZMM-sized registers) }
  15761. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15762. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15763. begin
  15764. XReg := taicpu(p).oper[0]^.reg;
  15765. if (taicpu(p).oper[1]^.reg = XReg) then
  15766. begin
  15767. taicpu(p).changeopsize(S_XMM);
  15768. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15769. if (cs_opt_size in current_settings.optimizerswitches) then
  15770. begin
  15771. { Change input registers to %xmm0 to reduce size. Note that
  15772. there's a risk of a false dependency doing this, so only
  15773. optimise for size here }
  15774. XReg := NR_XMM0;
  15775. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15776. end
  15777. else
  15778. begin
  15779. setsubreg(XReg, R_SUBMMX);
  15780. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15781. end;
  15782. taicpu(p).oper[0]^.reg := XReg;
  15783. taicpu(p).oper[1]^.reg := XReg;
  15784. Result := True;
  15785. end;
  15786. end;
  15787. end;
  15788. function TX86AsmOptimizer.PostPeepholeOptRET(var p: tai): Boolean;
  15789. var
  15790. hp1, p_new: tai;
  15791. begin
  15792. Result := False;
  15793. { Check for:
  15794. ret
  15795. .Lbl:
  15796. ret
  15797. Remove first 'ret'
  15798. }
  15799. if GetNextInstruction(p, hp1) and
  15800. { Remember where the label is }
  15801. SetAndTest(hp1, p_new) and
  15802. (hp1.typ in [ait_align, ait_label]) and
  15803. SkipLabels(hp1, hp1) and
  15804. MatchInstruction(hp1, A_RET, []) and
  15805. { To be safe, make sure the RET instructions are identical }
  15806. (taicpu(p).ops = taicpu(hp1).ops) and
  15807. (
  15808. (taicpu(p).ops = 0) or
  15809. (
  15810. (taicpu(p).ops = 1) and
  15811. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^)
  15812. )
  15813. ) then
  15814. begin
  15815. DebugMsg(SPeepholeOptimization + 'Removed superfluous RET', p);
  15816. UpdateUsedRegs(tai(p.Next));
  15817. RemoveCurrentP(p, p_new);
  15818. Result := True;
  15819. Exit;
  15820. end;
  15821. end;
  15822. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15823. var
  15824. OperIdx: Integer;
  15825. begin
  15826. for OperIdx := 0 to p.ops - 1 do
  15827. if p.oper[OperIdx]^.typ = top_ref then
  15828. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15829. end;
  15830. end.