aoptx86.pas 751 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551
  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. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  181. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  182. function TrySwapMovOp(var p, hp1: tai): Boolean;
  183. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  184. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  185. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  186. { Processor-dependent reference optimisation }
  187. class procedure OptimizeRefs(var p: taicpu); static;
  188. end;
  189. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  190. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  191. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  192. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  193. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  194. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  195. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  196. {$if max_operands>2}
  197. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  198. {$endif max_operands>2}
  199. function RefsEqual(const r1, r2: treference): boolean;
  200. { Like RefsEqual, but doesn't compare the offsets }
  201. function RefsAlmostEqual(const r1, r2: treference): boolean;
  202. { Note that Result is set to True if the references COULD overlap but the
  203. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  204. might still overlap because %reg2 could be equal to %reg1-4 }
  205. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  206. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  207. { returns true, if ref is a reference using only the registers passed as base and index
  208. and having an offset }
  209. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  210. implementation
  211. uses
  212. cutils,verbose,
  213. systems,
  214. globals,
  215. cpuinfo,
  216. procinfo,
  217. paramgr,
  218. aasmbase,
  219. aoptbase,aoptutils,
  220. symconst,symsym,
  221. cgx86,
  222. itcpugas;
  223. {$ifndef 8086}
  224. const
  225. MAX_CMOV_INSTRUCTIONS = 4;
  226. MAX_CMOV_REGISTERS = 8;
  227. type
  228. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  229. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  230. tsProcessed);
  231. { For OptPass2Jcc }
  232. TCMOVTracking = object
  233. private
  234. CMOVScore, ConstCount: LongInt;
  235. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  236. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  237. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  238. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  239. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  240. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  241. fOptimizer: TX86AsmOptimizer;
  242. fLabel: TAsmSymbol;
  243. fInsertionPoint,
  244. fCondition,
  245. fInitialJump,
  246. fFirstMovBlock,
  247. fFirstMovBlockStop,
  248. fSecondJump,
  249. fThirdJump,
  250. fSecondMovBlock,
  251. fSecondMovBlockStop,
  252. fMidLabel,
  253. fEndLabel,
  254. fAllocationRange: tai;
  255. fState: TCMovTrackingState;
  256. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  257. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  258. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  259. public
  260. RegisterTracking: TAllUsedRegs;
  261. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  262. destructor Done;
  263. procedure Process(out new_p: tai);
  264. property State: TCMovTrackingState read fState;
  265. end;
  266. PCMOVTracking = ^TCMOVTracking;
  267. {$endif 8086}
  268. {$ifdef DEBUG_AOPTCPU}
  269. const
  270. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  271. {$else DEBUG_AOPTCPU}
  272. { Empty strings help the optimizer to remove string concatenations that won't
  273. ever appear to the user on release builds. [Kit] }
  274. const
  275. SPeepholeOptimization = '';
  276. {$endif DEBUG_AOPTCPU}
  277. LIST_STEP_SIZE = 4;
  278. type
  279. TJumpTrackingItem = class(TLinkedListItem)
  280. private
  281. FSymbol: TAsmSymbol;
  282. FRefs: LongInt;
  283. public
  284. constructor Create(ASymbol: TAsmSymbol);
  285. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  286. property Symbol: TAsmSymbol read FSymbol;
  287. property Refs: LongInt read FRefs;
  288. end;
  289. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  290. begin
  291. inherited Create;
  292. FSymbol := ASymbol;
  293. FRefs := 0;
  294. end;
  295. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  296. begin
  297. Inc(FRefs);
  298. end;
  299. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  300. begin
  301. result :=
  302. (instr.typ = ait_instruction) and
  303. (taicpu(instr).opcode = op) and
  304. ((opsize = []) or (taicpu(instr).opsize in opsize));
  305. end;
  306. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  307. begin
  308. result :=
  309. (instr.typ = ait_instruction) and
  310. ((taicpu(instr).opcode = op1) or
  311. (taicpu(instr).opcode = op2)
  312. ) and
  313. ((opsize = []) or (taicpu(instr).opsize in opsize));
  314. end;
  315. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  316. begin
  317. result :=
  318. (instr.typ = ait_instruction) and
  319. ((taicpu(instr).opcode = op1) or
  320. (taicpu(instr).opcode = op2) or
  321. (taicpu(instr).opcode = op3)
  322. ) and
  323. ((opsize = []) or (taicpu(instr).opsize in opsize));
  324. end;
  325. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  326. const opsize : topsizes) : boolean;
  327. var
  328. op : TAsmOp;
  329. begin
  330. result:=false;
  331. if (instr.typ <> ait_instruction) or
  332. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  333. exit;
  334. for op in ops do
  335. begin
  336. if taicpu(instr).opcode = op then
  337. begin
  338. result:=true;
  339. exit;
  340. end;
  341. end;
  342. end;
  343. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  344. begin
  345. result := (oper.typ = top_reg) and (oper.reg = reg);
  346. end;
  347. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  348. begin
  349. result := (oper.typ = top_const) and (oper.val = a);
  350. end;
  351. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  352. begin
  353. result := oper1.typ = oper2.typ;
  354. if result then
  355. case oper1.typ of
  356. top_const:
  357. Result:=oper1.val = oper2.val;
  358. top_reg:
  359. Result:=oper1.reg = oper2.reg;
  360. top_ref:
  361. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  362. else
  363. internalerror(2013102801);
  364. end
  365. end;
  366. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  367. begin
  368. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  369. if result then
  370. case oper1.typ of
  371. top_const:
  372. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  373. top_reg:
  374. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  375. top_ref:
  376. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  377. else
  378. internalerror(2020052401);
  379. end
  380. end;
  381. function RefsEqual(const r1, r2: treference): boolean;
  382. begin
  383. RefsEqual :=
  384. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  385. (r1.relsymbol = r2.relsymbol) and
  386. (r1.segment = r2.segment) and (r1.base = r2.base) and
  387. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  388. (r1.offset = r2.offset) and
  389. (r1.volatility + r2.volatility = []);
  390. end;
  391. function RefsAlmostEqual(const r1, r2: treference): boolean;
  392. begin
  393. RefsAlmostEqual :=
  394. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  395. (r1.relsymbol = r2.relsymbol) and
  396. (r1.segment = r2.segment) and (r1.base = r2.base) and
  397. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  398. { Don't compare the offsets }
  399. (r1.volatility + r2.volatility = []);
  400. end;
  401. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  402. begin
  403. if (r1.symbol<>r2.symbol) then
  404. { If the index registers are different, there's a chance one could
  405. be set so it equals the other symbol }
  406. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  407. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  408. (r1.relsymbol = r2.relsymbol) and
  409. (r1.segment = r2.segment) and (r1.base = r2.base) and
  410. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  411. (r1.volatility + r2.volatility = []) then
  412. { In this case, it all depends on the offsets }
  413. Exit(abs(r1.offset - r2.offset) < Range);
  414. { There's a chance things MIGHT overlap, so take no chances }
  415. Result := True;
  416. end;
  417. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  418. begin
  419. Result:=(ref.offset=0) and
  420. (ref.scalefactor in [0,1]) and
  421. (ref.segment=NR_NO) and
  422. (ref.symbol=nil) and
  423. (ref.relsymbol=nil) and
  424. ((base=NR_INVALID) or
  425. (ref.base=base)) and
  426. ((index=NR_INVALID) or
  427. (ref.index=index)) and
  428. (ref.volatility=[]);
  429. end;
  430. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  431. begin
  432. Result:=(ref.scalefactor in [0,1]) and
  433. (ref.segment=NR_NO) and
  434. (ref.symbol=nil) and
  435. (ref.relsymbol=nil) and
  436. ((base=NR_INVALID) or
  437. (ref.base=base)) and
  438. ((index=NR_INVALID) or
  439. (ref.index=index)) and
  440. (ref.volatility=[]);
  441. end;
  442. function InstrReadsFlags(p: tai): boolean;
  443. begin
  444. InstrReadsFlags := true;
  445. case p.typ of
  446. ait_instruction:
  447. if InsProp[taicpu(p).opcode].Ch*
  448. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  449. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  450. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  451. exit;
  452. ait_label:
  453. exit;
  454. else
  455. ;
  456. end;
  457. InstrReadsFlags := false;
  458. end;
  459. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  460. begin
  461. Next:=Current;
  462. repeat
  463. Result:=GetNextInstruction(Next,Next);
  464. until not (Result) or
  465. not(cs_opt_level3 in current_settings.optimizerswitches) or
  466. (Next.typ<>ait_instruction) or
  467. RegInInstruction(reg,Next) or
  468. is_calljmp(taicpu(Next).opcode);
  469. end;
  470. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  471. var
  472. GetNextResult: Boolean;
  473. begin
  474. Result:=0;
  475. Next:=Current;
  476. repeat
  477. GetNextResult := GetNextInstruction(Next,Next);
  478. if GetNextResult then
  479. Inc(Result)
  480. else
  481. { Must return zero upon hitting the end of the linked list without a match }
  482. Result := 0;
  483. until not (GetNextResult) or
  484. not(cs_opt_level3 in current_settings.optimizerswitches) or
  485. (Next.typ<>ait_instruction) or
  486. RegInInstruction(reg,Next) or
  487. is_calljmp(taicpu(Next).opcode);
  488. end;
  489. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  490. procedure TrackJump(Symbol: TAsmSymbol);
  491. var
  492. Search: TJumpTrackingItem;
  493. begin
  494. { See if an entry already exists in our jump tracking list
  495. (faster to search backwards due to the higher chance of
  496. matching destinations) }
  497. Search := TJumpTrackingItem(JumpTracking.Last);
  498. while Assigned(Search) do
  499. begin
  500. if Search.Symbol = Symbol then
  501. begin
  502. { Found it - remove it so it can be pushed to the front }
  503. JumpTracking.Remove(Search);
  504. Break;
  505. end;
  506. Search := TJumpTrackingItem(Search.Previous);
  507. end;
  508. if not Assigned(Search) then
  509. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  510. JumpTracking.Concat(Search);
  511. Search.IncRefs;
  512. end;
  513. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  514. var
  515. Search: TJumpTrackingItem;
  516. begin
  517. Result := False;
  518. { See if this label appears in the tracking list }
  519. Search := TJumpTrackingItem(JumpTracking.Last);
  520. while Assigned(Search) do
  521. begin
  522. if Search.Symbol = Symbol then
  523. begin
  524. { Found it - let's see what we can discover }
  525. if Search.Symbol.getrefs = Search.Refs then
  526. begin
  527. { Success - all the references are accounted for }
  528. JumpTracking.Remove(Search);
  529. Search.Free;
  530. { It is logically impossible for CrossJump to be false here
  531. because we must have run into a conditional jump for
  532. this label at some point }
  533. if not CrossJump then
  534. InternalError(2022041710);
  535. if JumpTracking.First = nil then
  536. { Tracking list is now empty - no more cross jumps }
  537. CrossJump := False;
  538. Result := True;
  539. Exit;
  540. end;
  541. { If the references don't match, it's possible to enter
  542. this label through other means, so drop out }
  543. Exit;
  544. end;
  545. Search := TJumpTrackingItem(Search.Previous);
  546. end;
  547. end;
  548. var
  549. Next_Label: tai;
  550. begin
  551. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  552. Next := Current;
  553. repeat
  554. Result := GetNextInstruction(Next,Next);
  555. if not Result then
  556. Break;
  557. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  558. if is_calljmpuncondret(taicpu(Next).opcode) then
  559. begin
  560. if (taicpu(Next).opcode = A_JMP) and
  561. { Remove dead code now to save time }
  562. RemoveDeadCodeAfterJump(taicpu(Next)) then
  563. { A jump was removed, but not the current instruction, and
  564. Result doesn't necessarily translate into an optimisation
  565. routine's Result, so use the "Force New Iteration" flag so
  566. mark a new pass }
  567. Include(OptsToCheck, aoc_ForceNewIteration);
  568. if not Assigned(JumpTracking) then
  569. begin
  570. { Cross-label optimisations often causes other optimisations
  571. to perform worse because they're not given the chance to
  572. optimise locally. In this case, don't do the cross-label
  573. optimisations yet, but flag them as a potential possibility
  574. for the next iteration of Pass 1 }
  575. if not NotFirstIteration then
  576. Include(OptsToCheck, aoc_ForceNewIteration);
  577. end
  578. else if IsJumpToLabel(taicpu(Next)) and
  579. GetNextInstruction(Next, Next_Label) then
  580. begin
  581. { If we have JMP .lbl, and the label after it has all of its
  582. references tracked, then this is probably an if-else style of
  583. block and we can keep tracking. If the label for this jump
  584. then appears later and is fully tracked, then it's the end
  585. of the if-else blocks and the code paths converge (thus
  586. marking the end of the cross-jump) }
  587. if (Next_Label.typ = ait_label) then
  588. begin
  589. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  590. begin
  591. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  592. Next := Next_Label;
  593. { CrossJump gets set to false by LabelAccountedFor if the
  594. list is completely emptied (as it indicates that all
  595. code paths have converged). We could avoid this nuance
  596. by moving the TrackJump call to before the
  597. LabelAccountedFor call, but this is slower in situations
  598. where LabelAccountedFor would return False due to the
  599. creation of a new object that is not used and destroyed
  600. soon after. }
  601. CrossJump := True;
  602. Continue;
  603. end;
  604. end
  605. else if (Next_Label.typ <> ait_marker) then
  606. { We just did a RemoveDeadCodeAfterJump, so either we find
  607. a label, the end of the procedure or some kind of marker}
  608. InternalError(2022041720);
  609. end;
  610. Result := False;
  611. Exit;
  612. end
  613. else
  614. begin
  615. if not Assigned(JumpTracking) then
  616. begin
  617. { Cross-label optimisations often causes other optimisations
  618. to perform worse because they're not given the chance to
  619. optimise locally. In this case, don't do the cross-label
  620. optimisations yet, but flag them as a potential possibility
  621. for the next iteration of Pass 1 }
  622. if not NotFirstIteration then
  623. Include(OptsToCheck, aoc_ForceNewIteration);
  624. end
  625. else if IsJumpToLabel(taicpu(Next)) then
  626. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  627. else
  628. { Conditional jumps should always be a jump to label }
  629. InternalError(2022041701);
  630. CrossJump := True;
  631. Continue;
  632. end;
  633. if Next.typ = ait_label then
  634. begin
  635. if not Assigned(JumpTracking) then
  636. begin
  637. { Cross-label optimisations often causes other optimisations
  638. to perform worse because they're not given the chance to
  639. optimise locally. In this case, don't do the cross-label
  640. optimisations yet, but flag them as a potential possibility
  641. for the next iteration of Pass 1 }
  642. if not NotFirstIteration then
  643. Include(OptsToCheck, aoc_ForceNewIteration);
  644. end
  645. else if LabelAccountedFor(tai_label(Next).labsym) then
  646. Continue;
  647. { If we reach here, we're at a label that hasn't been seen before
  648. (or JumpTracking was nil) }
  649. Break;
  650. end;
  651. until not Result or
  652. not (cs_opt_level3 in current_settings.optimizerswitches) or
  653. not (Next.typ in [ait_label, ait_instruction]) or
  654. RegInInstruction(reg,Next);
  655. end;
  656. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  657. begin
  658. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  659. begin
  660. Result:=GetNextInstruction(Current,Next);
  661. exit;
  662. end;
  663. Next:=tai(Current.Next);
  664. Result:=false;
  665. while assigned(Next) do
  666. begin
  667. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  668. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  669. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  670. exit
  671. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  672. begin
  673. Result:=true;
  674. exit;
  675. end;
  676. Next:=tai(Next.Next);
  677. end;
  678. end;
  679. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  680. begin
  681. Result:=RegReadByInstruction(reg,hp);
  682. end;
  683. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  684. var
  685. p: taicpu;
  686. opcount: longint;
  687. begin
  688. RegReadByInstruction := false;
  689. if hp.typ <> ait_instruction then
  690. exit;
  691. p := taicpu(hp);
  692. case p.opcode of
  693. A_CALL:
  694. regreadbyinstruction := true;
  695. A_IMUL:
  696. case p.ops of
  697. 1:
  698. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  699. (
  700. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  701. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  702. );
  703. 2,3:
  704. regReadByInstruction :=
  705. reginop(reg,p.oper[0]^) or
  706. reginop(reg,p.oper[1]^);
  707. else
  708. InternalError(2019112801);
  709. end;
  710. A_MUL:
  711. begin
  712. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  713. (
  714. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  715. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  716. );
  717. end;
  718. A_IDIV,A_DIV:
  719. begin
  720. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  721. (
  722. (getregtype(reg)=R_INTREGISTER) and
  723. (
  724. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  725. )
  726. );
  727. end;
  728. else
  729. begin
  730. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  731. begin
  732. RegReadByInstruction := false;
  733. exit;
  734. end;
  735. for opcount := 0 to p.ops-1 do
  736. if (p.oper[opCount]^.typ = top_ref) and
  737. RegInRef(reg,p.oper[opcount]^.ref^) then
  738. begin
  739. RegReadByInstruction := true;
  740. exit
  741. end;
  742. { special handling for SSE MOVSD }
  743. if (p.opcode=A_MOVSD) and (p.ops>0) then
  744. begin
  745. if p.ops<>2 then
  746. internalerror(2017042702);
  747. regReadByInstruction := reginop(reg,p.oper[0]^) or
  748. (
  749. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  750. );
  751. exit;
  752. end;
  753. with insprop[p.opcode] do
  754. begin
  755. case getregtype(reg) of
  756. R_INTREGISTER:
  757. begin
  758. case getsupreg(reg) of
  759. RS_EAX:
  760. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  761. begin
  762. RegReadByInstruction := true;
  763. exit
  764. end;
  765. RS_ECX:
  766. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  767. begin
  768. RegReadByInstruction := true;
  769. exit
  770. end;
  771. RS_EDX:
  772. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  773. begin
  774. RegReadByInstruction := true;
  775. exit
  776. end;
  777. RS_EBX:
  778. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  779. begin
  780. RegReadByInstruction := true;
  781. exit
  782. end;
  783. RS_ESP:
  784. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  785. begin
  786. RegReadByInstruction := true;
  787. exit
  788. end;
  789. RS_EBP:
  790. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  791. begin
  792. RegReadByInstruction := true;
  793. exit
  794. end;
  795. RS_ESI:
  796. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  797. begin
  798. RegReadByInstruction := true;
  799. exit
  800. end;
  801. RS_EDI:
  802. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  803. begin
  804. RegReadByInstruction := true;
  805. exit
  806. end;
  807. end;
  808. end;
  809. R_MMREGISTER:
  810. begin
  811. case getsupreg(reg) of
  812. RS_XMM0:
  813. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  814. begin
  815. RegReadByInstruction := true;
  816. exit
  817. end;
  818. end;
  819. end;
  820. else
  821. ;
  822. end;
  823. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  824. begin
  825. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  826. begin
  827. case p.condition of
  828. C_A,C_NBE, { CF=0 and ZF=0 }
  829. C_BE,C_NA: { CF=1 or ZF=1 }
  830. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  831. C_AE,C_NB,C_NC, { CF=0 }
  832. C_B,C_NAE,C_C: { CF=1 }
  833. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  834. C_NE,C_NZ, { ZF=0 }
  835. C_E,C_Z: { ZF=1 }
  836. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  837. C_G,C_NLE, { ZF=0 and SF=OF }
  838. C_LE,C_NG: { ZF=1 or SF<>OF }
  839. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  840. C_GE,C_NL, { SF=OF }
  841. C_L,C_NGE: { SF<>OF }
  842. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  843. C_NO, { OF=0 }
  844. C_O: { OF=1 }
  845. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  846. C_NP,C_PO, { PF=0 }
  847. C_P,C_PE: { PF=1 }
  848. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  849. C_NS, { SF=0 }
  850. C_S: { SF=1 }
  851. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  852. else
  853. internalerror(2017042701);
  854. end;
  855. if RegReadByInstruction then
  856. exit;
  857. end;
  858. case getsubreg(reg) of
  859. R_SUBW,R_SUBD,R_SUBQ:
  860. RegReadByInstruction :=
  861. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  862. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  863. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  864. R_SUBFLAGCARRY:
  865. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  866. R_SUBFLAGPARITY:
  867. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  868. R_SUBFLAGAUXILIARY:
  869. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  870. R_SUBFLAGZERO:
  871. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  872. R_SUBFLAGSIGN:
  873. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  874. R_SUBFLAGOVERFLOW:
  875. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  876. R_SUBFLAGINTERRUPT:
  877. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  878. R_SUBFLAGDIRECTION:
  879. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  880. else
  881. internalerror(2017042601);
  882. end;
  883. exit;
  884. end;
  885. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  886. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  887. (p.oper[0]^.reg=p.oper[1]^.reg) then
  888. exit;
  889. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  890. begin
  891. RegReadByInstruction := true;
  892. exit
  893. end;
  894. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  895. begin
  896. RegReadByInstruction := true;
  897. exit
  898. end;
  899. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  900. begin
  901. RegReadByInstruction := true;
  902. exit
  903. end;
  904. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  905. begin
  906. RegReadByInstruction := true;
  907. exit
  908. end;
  909. end;
  910. end;
  911. end;
  912. end;
  913. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  914. begin
  915. result:=false;
  916. if p1.typ<>ait_instruction then
  917. exit;
  918. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  919. exit(true);
  920. if (getregtype(reg)=R_INTREGISTER) and
  921. { change information for xmm movsd are not correct }
  922. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  923. begin
  924. { Handle instructions that behave differently depending on the size and operand count }
  925. case taicpu(p1).opcode of
  926. A_MUL, A_DIV, A_IDIV:
  927. if taicpu(p1).opsize = S_B then
  928. Result := (getsupreg(Reg) = RS_EAX)
  929. else
  930. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  931. A_IMUL:
  932. if taicpu(p1).ops = 1 then
  933. begin
  934. if taicpu(p1).opsize = S_B then
  935. Result := (getsupreg(Reg) = RS_EAX)
  936. else
  937. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  938. end;
  939. { If ops are greater than 1, call inherited method }
  940. else
  941. case getsupreg(reg) of
  942. { RS_EAX = RS_RAX on x86-64 }
  943. RS_EAX:
  944. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  945. RS_ECX:
  946. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  947. RS_EDX:
  948. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  949. RS_EBX:
  950. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  951. RS_ESP:
  952. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  953. RS_EBP:
  954. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  955. RS_ESI:
  956. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  957. RS_EDI:
  958. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  959. else
  960. ;
  961. end;
  962. end;
  963. if result then
  964. exit;
  965. end
  966. else if getregtype(reg)=R_MMREGISTER then
  967. begin
  968. case getsupreg(reg) of
  969. RS_XMM0:
  970. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  971. else
  972. ;
  973. end;
  974. if result then
  975. exit;
  976. end
  977. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  978. begin
  979. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  980. exit(true);
  981. case getsubreg(reg) of
  982. R_SUBFLAGCARRY:
  983. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  984. R_SUBFLAGPARITY:
  985. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  986. R_SUBFLAGAUXILIARY:
  987. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  988. R_SUBFLAGZERO:
  989. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  990. R_SUBFLAGSIGN:
  991. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  992. R_SUBFLAGOVERFLOW:
  993. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  994. R_SUBFLAGINTERRUPT:
  995. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  996. R_SUBFLAGDIRECTION:
  997. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  998. R_SUBW,R_SUBD,R_SUBQ:
  999. { Everything except the direction bits }
  1000. Result:=
  1001. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  1002. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1003. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1004. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1005. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1006. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  1007. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  1008. else
  1009. ;
  1010. end;
  1011. if result then
  1012. exit;
  1013. end
  1014. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  1015. exit(true);
  1016. Result:=inherited RegInInstruction(Reg, p1);
  1017. end;
  1018. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1019. const
  1020. WriteOps: array[0..3] of set of TInsChange =
  1021. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1022. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1023. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1024. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1025. var
  1026. OperIdx: Integer;
  1027. begin
  1028. Result := False;
  1029. if p1.typ <> ait_instruction then
  1030. exit;
  1031. with insprop[taicpu(p1).opcode] do
  1032. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1033. begin
  1034. case getsubreg(reg) of
  1035. R_SUBW,R_SUBD,R_SUBQ:
  1036. Result :=
  1037. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1038. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1039. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1040. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1041. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1042. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1043. R_SUBFLAGCARRY:
  1044. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1045. R_SUBFLAGPARITY:
  1046. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1047. R_SUBFLAGAUXILIARY:
  1048. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1049. R_SUBFLAGZERO:
  1050. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1051. R_SUBFLAGSIGN:
  1052. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1053. R_SUBFLAGOVERFLOW:
  1054. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1055. R_SUBFLAGINTERRUPT:
  1056. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1057. R_SUBFLAGDIRECTION:
  1058. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1059. else
  1060. internalerror(2017042602);
  1061. end;
  1062. exit;
  1063. end;
  1064. case taicpu(p1).opcode of
  1065. A_CALL:
  1066. { We could potentially set Result to False if the register in
  1067. question is non-volatile for the subroutine's calling convention,
  1068. but this would require detecting the calling convention in use and
  1069. also assuming that the routine doesn't contain malformed assembly
  1070. language, for example... so it could only be done under -O4 as it
  1071. would be considered a side-effect. [Kit] }
  1072. Result := True;
  1073. A_MOVSD:
  1074. { special handling for SSE MOVSD }
  1075. if (taicpu(p1).ops>0) then
  1076. begin
  1077. if taicpu(p1).ops<>2 then
  1078. internalerror(2017042703);
  1079. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1080. end;
  1081. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1082. so fix it here (FK)
  1083. }
  1084. A_VMOVSS,
  1085. A_VMOVSD:
  1086. begin
  1087. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1088. exit;
  1089. end;
  1090. A_MUL, A_DIV, A_IDIV:
  1091. begin
  1092. if taicpu(p1).opsize = S_B then
  1093. Result := (getsupreg(Reg) = RS_EAX)
  1094. else
  1095. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1096. end;
  1097. A_IMUL:
  1098. begin
  1099. if taicpu(p1).ops = 1 then
  1100. begin
  1101. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1102. end
  1103. else
  1104. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1105. Exit;
  1106. end;
  1107. else
  1108. ;
  1109. end;
  1110. if Result then
  1111. exit;
  1112. with insprop[taicpu(p1).opcode] do
  1113. begin
  1114. if getregtype(reg)=R_INTREGISTER then
  1115. begin
  1116. case getsupreg(reg) of
  1117. RS_EAX:
  1118. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1119. begin
  1120. Result := True;
  1121. exit
  1122. end;
  1123. RS_ECX:
  1124. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1125. begin
  1126. Result := True;
  1127. exit
  1128. end;
  1129. RS_EDX:
  1130. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1131. begin
  1132. Result := True;
  1133. exit
  1134. end;
  1135. RS_EBX:
  1136. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1137. begin
  1138. Result := True;
  1139. exit
  1140. end;
  1141. RS_ESP:
  1142. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1143. begin
  1144. Result := True;
  1145. exit
  1146. end;
  1147. RS_EBP:
  1148. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1149. begin
  1150. Result := True;
  1151. exit
  1152. end;
  1153. RS_ESI:
  1154. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1155. begin
  1156. Result := True;
  1157. exit
  1158. end;
  1159. RS_EDI:
  1160. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1161. begin
  1162. Result := True;
  1163. exit
  1164. end;
  1165. end;
  1166. end;
  1167. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1168. if (WriteOps[OperIdx]*Ch<>[]) and
  1169. { The register doesn't get modified inside a reference }
  1170. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1171. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1172. begin
  1173. Result := true;
  1174. exit
  1175. end;
  1176. end;
  1177. end;
  1178. function TX86AsmOptimizer.RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  1179. const
  1180. WriteOps: array[0..3] of set of TInsChange =
  1181. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1182. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1183. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1184. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1185. var
  1186. X: Integer;
  1187. CurrentP1Size: asizeint;
  1188. begin
  1189. Result := (
  1190. (Ref.base <> NR_NO) and
  1191. {$ifdef x86_64}
  1192. (Ref.base <> NR_RIP) and
  1193. {$endif x86_64}
  1194. RegModifiedBetween(Ref.base, p1, p2)
  1195. ) or
  1196. (
  1197. (Ref.index <> NR_NO) and
  1198. (Ref.index <> Ref.base) and
  1199. RegModifiedBetween(Ref.index, p1, p2)
  1200. );
  1201. { Now check to see if the memory itself is written to }
  1202. if not Result then
  1203. begin
  1204. while assigned(p1) and assigned(p2) and GetNextInstruction(p1,p1) and (p1<>p2) do
  1205. if p1.typ = ait_instruction then
  1206. begin
  1207. CurrentP1Size := topsize2memsize[taicpu(p1).opsize] shr 3; { Convert to bytes }
  1208. with insprop[taicpu(p1).opcode] do
  1209. for X := 0 to taicpu(p1).ops - 1 do
  1210. if (taicpu(p1).oper[X]^.typ = top_ref) and
  1211. RefsAlmostEqual(Ref, taicpu(p1).oper[X]^.ref^) and
  1212. { Catch any potential overlaps }
  1213. (
  1214. (RefSize = 0) or
  1215. ((taicpu(p1).oper[X]^.ref^.offset - Ref.offset) < RefSize)
  1216. ) and
  1217. (
  1218. (CurrentP1Size = 0) or
  1219. ((Ref.offset - taicpu(p1).oper[X]^.ref^.offset) < CurrentP1Size)
  1220. ) and
  1221. { Reference is used, but does the instruction write to it? }
  1222. (
  1223. (Ch_All in Ch) or
  1224. ((WriteOps[X] * Ch) <> [])
  1225. ) then
  1226. begin
  1227. Result := True;
  1228. Break;
  1229. end;
  1230. end;
  1231. end;
  1232. end;
  1233. {$ifdef DEBUG_AOPTCPU}
  1234. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1235. begin
  1236. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1237. end;
  1238. function debug_tostr(i: tcgint): string; inline;
  1239. begin
  1240. Result := tostr(i);
  1241. end;
  1242. function debug_hexstr(i: tcgint): string;
  1243. begin
  1244. Result := '0x';
  1245. case i of
  1246. 0..$FF:
  1247. Result := Result + hexstr(i, 2);
  1248. $100..$FFFF:
  1249. Result := Result + hexstr(i, 4);
  1250. $10000..$FFFFFF:
  1251. Result := Result + hexstr(i, 6);
  1252. $1000000..$FFFFFFFF:
  1253. Result := Result + hexstr(i, 8);
  1254. else
  1255. Result := Result + hexstr(i, 16);
  1256. end;
  1257. end;
  1258. function debug_regname(r: TRegister): string; inline;
  1259. begin
  1260. Result := '%' + std_regname(r);
  1261. end;
  1262. { Debug output function - creates a string representation of an operator }
  1263. function debug_operstr(oper: TOper): string;
  1264. begin
  1265. case oper.typ of
  1266. top_const:
  1267. Result := '$' + debug_tostr(oper.val);
  1268. top_reg:
  1269. Result := debug_regname(oper.reg);
  1270. top_ref:
  1271. begin
  1272. if oper.ref^.offset <> 0 then
  1273. Result := debug_tostr(oper.ref^.offset) + '('
  1274. else
  1275. Result := '(';
  1276. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1277. begin
  1278. Result := Result + debug_regname(oper.ref^.base);
  1279. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1280. Result := Result + ',' + debug_regname(oper.ref^.index);
  1281. end
  1282. else
  1283. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1284. Result := Result + debug_regname(oper.ref^.index);
  1285. if (oper.ref^.scalefactor > 1) then
  1286. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1287. else
  1288. Result := Result + ')';
  1289. end;
  1290. else
  1291. Result := '[UNKNOWN]';
  1292. end;
  1293. end;
  1294. function debug_op2str(opcode: tasmop): string; inline;
  1295. begin
  1296. Result := std_op2str[opcode];
  1297. end;
  1298. function debug_opsize2str(opsize: topsize): string; inline;
  1299. begin
  1300. Result := gas_opsize2str[opsize];
  1301. end;
  1302. {$else DEBUG_AOPTCPU}
  1303. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1304. begin
  1305. end;
  1306. function debug_tostr(i: tcgint): string; inline;
  1307. begin
  1308. Result := '';
  1309. end;
  1310. function debug_hexstr(i: tcgint): string; inline;
  1311. begin
  1312. Result := '';
  1313. end;
  1314. function debug_regname(r: TRegister): string; inline;
  1315. begin
  1316. Result := '';
  1317. end;
  1318. function debug_operstr(oper: TOper): string; inline;
  1319. begin
  1320. Result := '';
  1321. end;
  1322. function debug_op2str(opcode: tasmop): string; inline;
  1323. begin
  1324. Result := '';
  1325. end;
  1326. function debug_opsize2str(opsize: topsize): string; inline;
  1327. begin
  1328. Result := '';
  1329. end;
  1330. {$endif DEBUG_AOPTCPU}
  1331. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1332. begin
  1333. {$ifdef x86_64}
  1334. { Always fine on x86-64 }
  1335. Result := True;
  1336. {$else x86_64}
  1337. Result :=
  1338. {$ifdef i8086}
  1339. (current_settings.cputype >= cpu_386) and
  1340. {$endif i8086}
  1341. (
  1342. { Always accept if optimising for size }
  1343. (cs_opt_size in current_settings.optimizerswitches) or
  1344. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1345. (current_settings.optimizecputype >= cpu_Pentium2)
  1346. );
  1347. {$endif x86_64}
  1348. end;
  1349. { Attempts to allocate a volatile integer register for use between p and hp,
  1350. using AUsedRegs for the current register usage information. Returns NR_NO
  1351. if no free register could be found }
  1352. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1353. var
  1354. RegSet: TCPURegisterSet;
  1355. CurrentSuperReg: Integer;
  1356. CurrentReg: TRegister;
  1357. Currentp: tai;
  1358. Breakout: Boolean;
  1359. begin
  1360. Result := NR_NO;
  1361. RegSet :=
  1362. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1363. current_procinfo.saved_regs_int;
  1364. (*
  1365. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1366. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1367. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1368. *)
  1369. for CurrentSuperReg in RegSet do
  1370. begin
  1371. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1372. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1373. {$if defined(i386) or defined(i8086)}
  1374. { If the target size is 8-bit, make sure we can actually encode it }
  1375. and (
  1376. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1377. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1378. )
  1379. {$endif i386 or i8086}
  1380. then
  1381. begin
  1382. Currentp := p;
  1383. Breakout := False;
  1384. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1385. begin
  1386. case Currentp.typ of
  1387. ait_instruction:
  1388. begin
  1389. if RegInInstruction(CurrentReg, Currentp) then
  1390. begin
  1391. Breakout := True;
  1392. Break;
  1393. end;
  1394. { Cannot allocate across an unconditional jump }
  1395. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1396. Exit;
  1397. end;
  1398. ait_marker:
  1399. { Don't try anything more if a marker is hit }
  1400. Exit;
  1401. ait_regalloc:
  1402. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1403. begin
  1404. Breakout := True;
  1405. Break;
  1406. end;
  1407. else
  1408. ;
  1409. end;
  1410. end;
  1411. if Breakout then
  1412. { Try the next register }
  1413. Continue;
  1414. { We have a free register available }
  1415. Result := CurrentReg;
  1416. if not DontAlloc then
  1417. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1418. Exit;
  1419. end;
  1420. end;
  1421. end;
  1422. { Attempts to allocate a volatile MM register for use between p and hp,
  1423. using AUsedRegs for the current register usage information. Returns NR_NO
  1424. if no free register could be found }
  1425. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1426. var
  1427. RegSet: TCPURegisterSet;
  1428. CurrentSuperReg: Integer;
  1429. CurrentReg: TRegister;
  1430. Currentp: tai;
  1431. Breakout: Boolean;
  1432. begin
  1433. Result := NR_NO;
  1434. RegSet :=
  1435. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1436. current_procinfo.saved_regs_mm;
  1437. for CurrentSuperReg in RegSet do
  1438. begin
  1439. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1440. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1441. begin
  1442. Currentp := p;
  1443. Breakout := False;
  1444. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1445. begin
  1446. case Currentp.typ of
  1447. ait_instruction:
  1448. begin
  1449. if RegInInstruction(CurrentReg, Currentp) then
  1450. begin
  1451. Breakout := True;
  1452. Break;
  1453. end;
  1454. { Cannot allocate across an unconditional jump }
  1455. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1456. Exit;
  1457. end;
  1458. ait_marker:
  1459. { Don't try anything more if a marker is hit }
  1460. Exit;
  1461. ait_regalloc:
  1462. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1463. begin
  1464. Breakout := True;
  1465. Break;
  1466. end;
  1467. else
  1468. ;
  1469. end;
  1470. end;
  1471. if Breakout then
  1472. { Try the next register }
  1473. Continue;
  1474. { We have a free register available }
  1475. Result := CurrentReg;
  1476. if not DontAlloc then
  1477. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1478. Exit;
  1479. end;
  1480. end;
  1481. end;
  1482. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1483. begin
  1484. if not SuperRegistersEqual(reg1,reg2) then
  1485. exit(false);
  1486. if getregtype(reg1)<>R_INTREGISTER then
  1487. exit(true); {because SuperRegisterEqual is true}
  1488. case getsubreg(reg1) of
  1489. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1490. higher, it preserves the high bits, so the new value depends on
  1491. reg2's previous value. In other words, it is equivalent to doing:
  1492. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1493. R_SUBL:
  1494. exit(getsubreg(reg2)=R_SUBL);
  1495. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1496. higher, it actually does a:
  1497. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1498. R_SUBH:
  1499. exit(getsubreg(reg2)=R_SUBH);
  1500. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1501. bits of reg2:
  1502. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1503. R_SUBW:
  1504. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1505. { a write to R_SUBD always overwrites every other subregister,
  1506. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1507. R_SUBD,
  1508. R_SUBQ:
  1509. exit(true);
  1510. else
  1511. internalerror(2017042801);
  1512. end;
  1513. end;
  1514. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1515. begin
  1516. if not SuperRegistersEqual(reg1,reg2) then
  1517. exit(false);
  1518. if getregtype(reg1)<>R_INTREGISTER then
  1519. exit(true); {because SuperRegisterEqual is true}
  1520. case getsubreg(reg1) of
  1521. R_SUBL:
  1522. exit(getsubreg(reg2)<>R_SUBH);
  1523. R_SUBH:
  1524. exit(getsubreg(reg2)<>R_SUBL);
  1525. R_SUBW,
  1526. R_SUBD,
  1527. R_SUBQ:
  1528. exit(true);
  1529. else
  1530. internalerror(2017042802);
  1531. end;
  1532. end;
  1533. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1534. var
  1535. hp1 : tai;
  1536. l : TCGInt;
  1537. begin
  1538. result:=false;
  1539. if not(GetNextInstruction(p, hp1)) then
  1540. exit;
  1541. { changes the code sequence
  1542. shr/sar const1, x
  1543. shl const2, x
  1544. to
  1545. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1546. if (taicpu(p).oper[0]^.typ = top_const) and
  1547. MatchInstruction(hp1,A_SHL,[]) and
  1548. (taicpu(hp1).oper[0]^.typ = top_const) and
  1549. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1550. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1551. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1552. begin
  1553. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1554. not(cs_opt_size in current_settings.optimizerswitches) then
  1555. begin
  1556. { shr/sar const1, %reg
  1557. shl const2, %reg
  1558. with const1 > const2 }
  1559. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1560. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1561. taicpu(hp1).opcode := A_AND;
  1562. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1563. case taicpu(p).opsize Of
  1564. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1565. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1566. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1567. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1568. else
  1569. Internalerror(2017050703)
  1570. end;
  1571. end
  1572. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1573. not(cs_opt_size in current_settings.optimizerswitches) then
  1574. begin
  1575. { shr/sar const1, %reg
  1576. shl const2, %reg
  1577. with const1 < const2 }
  1578. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1579. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1580. taicpu(p).opcode := A_AND;
  1581. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1582. case taicpu(p).opsize Of
  1583. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1584. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1585. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1586. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1587. else
  1588. Internalerror(2017050702)
  1589. end;
  1590. end
  1591. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1592. begin
  1593. { shr/sar const1, %reg
  1594. shl const2, %reg
  1595. with const1 = const2 }
  1596. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1597. taicpu(p).opcode := A_AND;
  1598. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1599. case taicpu(p).opsize Of
  1600. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1601. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1602. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1603. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1604. else
  1605. Internalerror(2017050701)
  1606. end;
  1607. RemoveInstruction(hp1);
  1608. end;
  1609. end;
  1610. end;
  1611. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1612. var
  1613. opsize : topsize;
  1614. hp1, hp2 : tai;
  1615. tmpref : treference;
  1616. ShiftValue : Cardinal;
  1617. BaseValue : TCGInt;
  1618. begin
  1619. result:=false;
  1620. opsize:=taicpu(p).opsize;
  1621. { changes certain "imul const, %reg"'s to lea sequences }
  1622. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1623. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1624. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1625. if (taicpu(p).oper[0]^.val = 1) then
  1626. if (taicpu(p).ops = 2) then
  1627. { remove "imul $1, reg" }
  1628. begin
  1629. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1630. Result := RemoveCurrentP(p);
  1631. end
  1632. else
  1633. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1634. begin
  1635. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1636. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1637. asml.InsertAfter(hp1, p);
  1638. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1639. RemoveCurrentP(p, hp1);
  1640. Result := True;
  1641. end
  1642. else if ((taicpu(p).ops <= 2) or
  1643. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1644. not(cs_opt_size in current_settings.optimizerswitches) and
  1645. (not(GetNextInstruction(p, hp1)) or
  1646. not((tai(hp1).typ = ait_instruction) and
  1647. ((taicpu(hp1).opcode=A_Jcc) and
  1648. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1649. begin
  1650. {
  1651. imul X, reg1, reg2 to
  1652. lea (reg1,reg1,Y), reg2
  1653. shl ZZ,reg2
  1654. imul XX, reg1 to
  1655. lea (reg1,reg1,YY), reg1
  1656. shl ZZ,reg2
  1657. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1658. it does not exist as a separate optimization target in FPC though.
  1659. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1660. at most two zeros
  1661. }
  1662. reference_reset(tmpref,1,[]);
  1663. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1664. begin
  1665. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1666. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1667. TmpRef.base := taicpu(p).oper[1]^.reg;
  1668. TmpRef.index := taicpu(p).oper[1]^.reg;
  1669. if not(BaseValue in [3,5,9]) then
  1670. Internalerror(2018110101);
  1671. TmpRef.ScaleFactor := BaseValue-1;
  1672. if (taicpu(p).ops = 2) then
  1673. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1674. else
  1675. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1676. AsmL.InsertAfter(hp1,p);
  1677. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1678. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1679. RemoveCurrentP(p, hp1);
  1680. if ShiftValue>0 then
  1681. begin
  1682. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1683. AsmL.InsertAfter(hp2,hp1);
  1684. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1685. end;
  1686. Result := True;
  1687. end;
  1688. end;
  1689. end;
  1690. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1691. begin
  1692. Result := False;
  1693. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1694. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1695. begin
  1696. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1697. taicpu(p).opcode := A_MOV;
  1698. Result := True;
  1699. end;
  1700. end;
  1701. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1702. var
  1703. p: taicpu absolute hp; { Implicit typecast }
  1704. i: Integer;
  1705. begin
  1706. Result := False;
  1707. if not assigned(hp) or
  1708. (hp.typ <> ait_instruction) then
  1709. Exit;
  1710. Prefetch(insprop[p.opcode]);
  1711. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1712. with insprop[p.opcode] do
  1713. begin
  1714. case getsubreg(reg) of
  1715. R_SUBW,R_SUBD,R_SUBQ:
  1716. Result:=
  1717. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1718. uncommon flags are checked first }
  1719. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1720. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1721. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1722. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1723. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1724. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1725. R_SUBFLAGCARRY:
  1726. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1727. R_SUBFLAGPARITY:
  1728. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1729. R_SUBFLAGAUXILIARY:
  1730. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1731. R_SUBFLAGZERO:
  1732. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1733. R_SUBFLAGSIGN:
  1734. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1735. R_SUBFLAGOVERFLOW:
  1736. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1737. R_SUBFLAGINTERRUPT:
  1738. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1739. R_SUBFLAGDIRECTION:
  1740. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1741. else
  1742. internalerror(2017050501);
  1743. end;
  1744. exit;
  1745. end;
  1746. { Handle special cases first }
  1747. case p.opcode of
  1748. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1749. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1750. begin
  1751. Result :=
  1752. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1753. (p.oper[1]^.typ = top_reg) and
  1754. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1755. (
  1756. (p.oper[0]^.typ = top_const) or
  1757. (
  1758. (p.oper[0]^.typ = top_reg) and
  1759. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1760. ) or (
  1761. (p.oper[0]^.typ = top_ref) and
  1762. not RegInRef(reg,p.oper[0]^.ref^)
  1763. )
  1764. );
  1765. end;
  1766. A_MUL, A_IMUL:
  1767. Result :=
  1768. (
  1769. (p.ops=3) and { IMUL only }
  1770. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1771. (
  1772. (
  1773. (p.oper[1]^.typ=top_reg) and
  1774. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1775. ) or (
  1776. (p.oper[1]^.typ=top_ref) and
  1777. not RegInRef(reg,p.oper[1]^.ref^)
  1778. )
  1779. )
  1780. ) or (
  1781. (
  1782. (p.ops=1) and
  1783. (
  1784. (
  1785. (
  1786. (p.oper[0]^.typ=top_reg) and
  1787. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1788. )
  1789. ) or (
  1790. (p.oper[0]^.typ=top_ref) and
  1791. not RegInRef(reg,p.oper[0]^.ref^)
  1792. )
  1793. ) and (
  1794. (
  1795. (p.opsize=S_B) and
  1796. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1797. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1798. ) or (
  1799. (p.opsize=S_W) and
  1800. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1801. ) or (
  1802. (p.opsize=S_L) and
  1803. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1804. {$ifdef x86_64}
  1805. ) or (
  1806. (p.opsize=S_Q) and
  1807. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1808. {$endif x86_64}
  1809. )
  1810. )
  1811. )
  1812. );
  1813. A_CBW:
  1814. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1815. {$ifndef x86_64}
  1816. A_LDS:
  1817. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1818. A_LES:
  1819. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1820. {$endif not x86_64}
  1821. A_LFS:
  1822. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1823. A_LGS:
  1824. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1825. A_LSS:
  1826. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1827. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1828. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1829. A_LODSB:
  1830. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1831. A_LODSW:
  1832. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1833. {$ifdef x86_64}
  1834. A_LODSQ:
  1835. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1836. {$endif x86_64}
  1837. A_LODSD:
  1838. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1839. A_FSTSW, A_FNSTSW:
  1840. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1841. else
  1842. begin
  1843. with insprop[p.opcode] do
  1844. begin
  1845. if (
  1846. { xor %reg,%reg etc. is classed as a new value }
  1847. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1848. MatchOpType(p, top_reg, top_reg) and
  1849. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1850. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1851. ) then
  1852. begin
  1853. Result := True;
  1854. Exit;
  1855. end;
  1856. { Make sure the entire register is overwritten }
  1857. if (getregtype(reg) = R_INTREGISTER) then
  1858. begin
  1859. if (p.ops > 0) then
  1860. begin
  1861. if RegInOp(reg, p.oper[0]^) then
  1862. begin
  1863. if (p.oper[0]^.typ = top_ref) then
  1864. begin
  1865. if RegInRef(reg, p.oper[0]^.ref^) then
  1866. begin
  1867. Result := False;
  1868. Exit;
  1869. end;
  1870. end
  1871. else if (p.oper[0]^.typ = top_reg) then
  1872. begin
  1873. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1874. begin
  1875. Result := False;
  1876. Exit;
  1877. end
  1878. else if ([Ch_WOp1]*Ch<>[]) then
  1879. begin
  1880. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1881. Result := True
  1882. else
  1883. begin
  1884. Result := False;
  1885. Exit;
  1886. end;
  1887. end;
  1888. end;
  1889. end;
  1890. if (p.ops > 1) then
  1891. begin
  1892. if RegInOp(reg, p.oper[1]^) then
  1893. begin
  1894. if (p.oper[1]^.typ = top_ref) then
  1895. begin
  1896. if RegInRef(reg, p.oper[1]^.ref^) then
  1897. begin
  1898. Result := False;
  1899. Exit;
  1900. end;
  1901. end
  1902. else if (p.oper[1]^.typ = top_reg) then
  1903. begin
  1904. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1905. begin
  1906. Result := False;
  1907. Exit;
  1908. end
  1909. else if ([Ch_WOp2]*Ch<>[]) then
  1910. begin
  1911. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1912. Result := True
  1913. else
  1914. begin
  1915. Result := False;
  1916. Exit;
  1917. end;
  1918. end;
  1919. end;
  1920. end;
  1921. if (p.ops > 2) then
  1922. begin
  1923. if RegInOp(reg, p.oper[2]^) then
  1924. begin
  1925. if (p.oper[2]^.typ = top_ref) then
  1926. begin
  1927. if RegInRef(reg, p.oper[2]^.ref^) then
  1928. begin
  1929. Result := False;
  1930. Exit;
  1931. end;
  1932. end
  1933. else if (p.oper[2]^.typ = top_reg) then
  1934. begin
  1935. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1936. begin
  1937. Result := False;
  1938. Exit;
  1939. end
  1940. else if ([Ch_WOp3]*Ch<>[]) then
  1941. begin
  1942. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1943. Result := True
  1944. else
  1945. begin
  1946. Result := False;
  1947. Exit;
  1948. end;
  1949. end;
  1950. end;
  1951. end;
  1952. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1953. begin
  1954. if (p.oper[3]^.typ = top_ref) then
  1955. begin
  1956. if RegInRef(reg, p.oper[3]^.ref^) then
  1957. begin
  1958. Result := False;
  1959. Exit;
  1960. end;
  1961. end
  1962. else if (p.oper[3]^.typ = top_reg) then
  1963. begin
  1964. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1965. begin
  1966. Result := False;
  1967. Exit;
  1968. end
  1969. else if ([Ch_WOp4]*Ch<>[]) then
  1970. begin
  1971. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1972. Result := True
  1973. else
  1974. begin
  1975. Result := False;
  1976. Exit;
  1977. end;
  1978. end;
  1979. end;
  1980. end;
  1981. end;
  1982. end;
  1983. end;
  1984. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1985. case getsupreg(reg) of
  1986. RS_EAX:
  1987. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1988. begin
  1989. Result := True;
  1990. Exit;
  1991. end;
  1992. RS_ECX:
  1993. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1994. begin
  1995. Result := True;
  1996. Exit;
  1997. end;
  1998. RS_EDX:
  1999. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  2000. begin
  2001. Result := True;
  2002. Exit;
  2003. end;
  2004. RS_EBX:
  2005. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  2006. begin
  2007. Result := True;
  2008. Exit;
  2009. end;
  2010. RS_ESP:
  2011. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  2012. begin
  2013. Result := True;
  2014. Exit;
  2015. end;
  2016. RS_EBP:
  2017. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  2018. begin
  2019. Result := True;
  2020. Exit;
  2021. end;
  2022. RS_ESI:
  2023. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  2024. begin
  2025. Result := True;
  2026. Exit;
  2027. end;
  2028. RS_EDI:
  2029. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  2030. begin
  2031. Result := True;
  2032. Exit;
  2033. end;
  2034. else
  2035. ;
  2036. end;
  2037. end;
  2038. end;
  2039. end;
  2040. end;
  2041. end;
  2042. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  2043. var
  2044. hp2,hp3 : tai;
  2045. begin
  2046. { some x86-64 issue a NOP before the real exit code }
  2047. if MatchInstruction(p,A_NOP,[]) then
  2048. GetNextInstruction(p,p);
  2049. result:=assigned(p) and (p.typ=ait_instruction) and
  2050. ((taicpu(p).opcode = A_RET) or
  2051. ((taicpu(p).opcode=A_LEAVE) and
  2052. GetNextInstruction(p,hp2) and
  2053. MatchInstruction(hp2,A_RET,[S_NO])
  2054. ) or
  2055. (((taicpu(p).opcode=A_LEA) and
  2056. MatchOpType(taicpu(p),top_ref,top_reg) and
  2057. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  2058. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2059. ) and
  2060. GetNextInstruction(p,hp2) and
  2061. MatchInstruction(hp2,A_RET,[S_NO])
  2062. ) or
  2063. ((((taicpu(p).opcode=A_MOV) and
  2064. MatchOpType(taicpu(p),top_reg,top_reg) and
  2065. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  2066. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  2067. ((taicpu(p).opcode=A_LEA) and
  2068. MatchOpType(taicpu(p),top_ref,top_reg) and
  2069. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  2070. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2071. )
  2072. ) and
  2073. GetNextInstruction(p,hp2) and
  2074. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2075. MatchOpType(taicpu(hp2),top_reg) and
  2076. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2077. GetNextInstruction(hp2,hp3) and
  2078. MatchInstruction(hp3,A_RET,[S_NO])
  2079. )
  2080. );
  2081. end;
  2082. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2083. begin
  2084. isFoldableArithOp := False;
  2085. case hp1.opcode of
  2086. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2087. isFoldableArithOp :=
  2088. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2089. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2090. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2091. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2092. (taicpu(hp1).oper[1]^.reg = reg);
  2093. A_INC,A_DEC,A_NEG,A_NOT:
  2094. isFoldableArithOp :=
  2095. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2096. (taicpu(hp1).oper[0]^.reg = reg);
  2097. else
  2098. ;
  2099. end;
  2100. end;
  2101. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2102. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2103. var
  2104. hp2: tai;
  2105. begin
  2106. hp2 := p;
  2107. repeat
  2108. hp2 := tai(hp2.previous);
  2109. if assigned(hp2) and
  2110. (hp2.typ = ait_regalloc) and
  2111. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2112. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2113. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2114. begin
  2115. RemoveInstruction(hp2);
  2116. break;
  2117. end;
  2118. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2119. end;
  2120. begin
  2121. case current_procinfo.procdef.returndef.typ of
  2122. arraydef,recorddef,pointerdef,
  2123. stringdef,enumdef,procdef,objectdef,errordef,
  2124. filedef,setdef,procvardef,
  2125. classrefdef,forwarddef:
  2126. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2127. orddef:
  2128. if current_procinfo.procdef.returndef.size <> 0 then
  2129. begin
  2130. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2131. { for int64/qword }
  2132. if current_procinfo.procdef.returndef.size = 8 then
  2133. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2134. end;
  2135. else
  2136. ;
  2137. end;
  2138. end;
  2139. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2140. var
  2141. hp1: tai;
  2142. operswap: poper;
  2143. begin
  2144. Result := False;
  2145. { Optimise:
  2146. cmov(c) %reg1,%reg2
  2147. mov %reg2,%reg1
  2148. (%reg2 dealloc.)
  2149. To:
  2150. cmov(~c) %reg2,%reg1
  2151. }
  2152. if (taicpu(p).oper[0]^.typ = top_reg) then
  2153. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2154. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2155. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2156. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2157. begin
  2158. TransferUsedRegs(TmpUsedRegs);
  2159. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2160. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2161. begin
  2162. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2163. { Save time by swapping the pointers (they're both registers, so
  2164. we don't need to worry about reference counts) }
  2165. operswap := taicpu(p).oper[0];
  2166. taicpu(p).oper[0] := taicpu(p).oper[1];
  2167. taicpu(p).oper[1] := operswap;
  2168. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2169. RemoveInstruction(hp1);
  2170. { It's still a CMOV, so we can look further ahead }
  2171. Include(OptsToCheck, aoc_ForceNewIteration);
  2172. { But first, let's see if this will get optimised again
  2173. (probably won't happen, but best to be sure) }
  2174. Continue;
  2175. end;
  2176. Break;
  2177. end;
  2178. end;
  2179. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2180. var
  2181. hp1,hp2 : tai;
  2182. begin
  2183. result:=false;
  2184. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2185. begin
  2186. { vmova* reg1,reg1
  2187. =>
  2188. <nop> }
  2189. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2190. begin
  2191. RemoveCurrentP(p);
  2192. result:=true;
  2193. exit;
  2194. end;
  2195. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2196. (hp1.typ = ait_instruction) and
  2197. (
  2198. { Under -O2 and below, the instructions are always adjacent }
  2199. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2200. (taicpu(hp1).ops <= 1) or
  2201. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2202. { If reg1 = reg3, reg1 must not be modified in between }
  2203. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2204. ) then
  2205. begin
  2206. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2207. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2208. begin
  2209. { vmova* reg1,reg2
  2210. ...
  2211. vmova* reg2,reg3
  2212. dealloc reg2
  2213. =>
  2214. vmova* reg1,reg3 }
  2215. TransferUsedRegs(TmpUsedRegs);
  2216. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2217. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2218. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2219. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2220. begin
  2221. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2222. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2223. TransferUsedRegs(TmpUsedRegs);
  2224. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2225. RemoveInstruction(hp1);
  2226. result:=true;
  2227. exit;
  2228. end;
  2229. { special case:
  2230. vmova* reg1,<op>
  2231. ...
  2232. vmova* <op>,reg1
  2233. =>
  2234. vmova* reg1,<op> }
  2235. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2236. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2237. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2238. ) then
  2239. begin
  2240. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2241. RemoveInstruction(hp1);
  2242. result:=true;
  2243. exit;
  2244. end
  2245. end
  2246. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2247. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2248. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2249. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2250. ) and
  2251. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2252. begin
  2253. { vmova* reg1,reg2
  2254. ...
  2255. vmovs* reg2,<op>
  2256. dealloc reg2
  2257. =>
  2258. vmovs* reg1,<op> }
  2259. TransferUsedRegs(TmpUsedRegs);
  2260. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2261. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2262. begin
  2263. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2264. taicpu(p).opcode:=taicpu(hp1).opcode;
  2265. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2266. TransferUsedRegs(TmpUsedRegs);
  2267. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2268. RemoveInstruction(hp1);
  2269. result:=true;
  2270. exit;
  2271. end
  2272. end;
  2273. if MatchInstruction(hp1,[A_VFMADDPD,
  2274. A_VFMADD132PD,
  2275. A_VFMADD132PS,
  2276. A_VFMADD132SD,
  2277. A_VFMADD132SS,
  2278. A_VFMADD213PD,
  2279. A_VFMADD213PS,
  2280. A_VFMADD213SD,
  2281. A_VFMADD213SS,
  2282. A_VFMADD231PD,
  2283. A_VFMADD231PS,
  2284. A_VFMADD231SD,
  2285. A_VFMADD231SS,
  2286. A_VFMADDSUB132PD,
  2287. A_VFMADDSUB132PS,
  2288. A_VFMADDSUB213PD,
  2289. A_VFMADDSUB213PS,
  2290. A_VFMADDSUB231PD,
  2291. A_VFMADDSUB231PS,
  2292. A_VFMSUB132PD,
  2293. A_VFMSUB132PS,
  2294. A_VFMSUB132SD,
  2295. A_VFMSUB132SS,
  2296. A_VFMSUB213PD,
  2297. A_VFMSUB213PS,
  2298. A_VFMSUB213SD,
  2299. A_VFMSUB213SS,
  2300. A_VFMSUB231PD,
  2301. A_VFMSUB231PS,
  2302. A_VFMSUB231SD,
  2303. A_VFMSUB231SS,
  2304. A_VFMSUBADD132PD,
  2305. A_VFMSUBADD132PS,
  2306. A_VFMSUBADD213PD,
  2307. A_VFMSUBADD213PS,
  2308. A_VFMSUBADD231PD,
  2309. A_VFMSUBADD231PS,
  2310. A_VFNMADD132PD,
  2311. A_VFNMADD132PS,
  2312. A_VFNMADD132SD,
  2313. A_VFNMADD132SS,
  2314. A_VFNMADD213PD,
  2315. A_VFNMADD213PS,
  2316. A_VFNMADD213SD,
  2317. A_VFNMADD213SS,
  2318. A_VFNMADD231PD,
  2319. A_VFNMADD231PS,
  2320. A_VFNMADD231SD,
  2321. A_VFNMADD231SS,
  2322. A_VFNMSUB132PD,
  2323. A_VFNMSUB132PS,
  2324. A_VFNMSUB132SD,
  2325. A_VFNMSUB132SS,
  2326. A_VFNMSUB213PD,
  2327. A_VFNMSUB213PS,
  2328. A_VFNMSUB213SD,
  2329. A_VFNMSUB213SS,
  2330. A_VFNMSUB231PD,
  2331. A_VFNMSUB231PS,
  2332. A_VFNMSUB231SD,
  2333. A_VFNMSUB231SS],[S_NO]) and
  2334. { we mix single and double opperations here because we assume that the compiler
  2335. generates vmovapd only after double operations and vmovaps only after single operations }
  2336. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2337. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2338. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2339. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2340. begin
  2341. TransferUsedRegs(TmpUsedRegs);
  2342. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2343. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2344. begin
  2345. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2346. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2347. RemoveCurrentP(p)
  2348. else
  2349. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2350. RemoveInstruction(hp2);
  2351. end;
  2352. end
  2353. else if (hp1.typ = ait_instruction) and
  2354. (((taicpu(p).opcode=A_MOVAPS) and
  2355. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2356. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2357. ((taicpu(p).opcode=A_MOVAPD) and
  2358. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2359. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2360. ) and
  2361. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2362. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2363. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2364. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2365. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2366. { change
  2367. movapX reg,reg2
  2368. addsX/subsX/... reg3, reg2
  2369. movapX reg2,reg
  2370. to
  2371. addsX/subsX/... reg3,reg
  2372. }
  2373. begin
  2374. TransferUsedRegs(TmpUsedRegs);
  2375. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2376. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2377. begin
  2378. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2379. debug_op2str(taicpu(p).opcode)+' '+
  2380. debug_op2str(taicpu(hp1).opcode)+' '+
  2381. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2382. { we cannot eliminate the first move if
  2383. the operations uses the same register for source and dest }
  2384. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2385. { Remember that hp1 is not necessarily the immediate
  2386. next instruction }
  2387. RemoveCurrentP(p);
  2388. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2389. RemoveInstruction(hp2);
  2390. result:=true;
  2391. end;
  2392. end
  2393. else if (hp1.typ = ait_instruction) and
  2394. (((taicpu(p).opcode=A_VMOVAPD) and
  2395. (taicpu(hp1).opcode=A_VCOMISD)) or
  2396. ((taicpu(p).opcode=A_VMOVAPS) and
  2397. ((taicpu(hp1).opcode=A_VCOMISS))
  2398. )
  2399. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2400. { change
  2401. movapX reg,reg1
  2402. vcomisX reg1,reg1
  2403. to
  2404. vcomisX reg,reg
  2405. }
  2406. begin
  2407. TransferUsedRegs(TmpUsedRegs);
  2408. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2409. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2410. begin
  2411. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2412. debug_op2str(taicpu(p).opcode)+' '+
  2413. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2414. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2415. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2416. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2417. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2418. RemoveCurrentP(p);
  2419. result:=true;
  2420. exit;
  2421. end;
  2422. end
  2423. end;
  2424. end;
  2425. end;
  2426. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2427. var
  2428. hp1 : tai;
  2429. begin
  2430. result:=false;
  2431. { replace
  2432. V<Op>X %mreg1,%mreg2,%mreg3
  2433. VMovX %mreg3,%mreg4
  2434. dealloc %mreg3
  2435. by
  2436. V<Op>X %mreg1,%mreg2,%mreg4
  2437. ?
  2438. }
  2439. if GetNextInstruction(p,hp1) and
  2440. { we mix single and double operations here because we assume that the compiler
  2441. generates vmovapd only after double operations and vmovaps only after single operations }
  2442. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2443. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2444. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2445. begin
  2446. TransferUsedRegs(TmpUsedRegs);
  2447. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2448. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2449. begin
  2450. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2451. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2452. RemoveInstruction(hp1);
  2453. result:=true;
  2454. end;
  2455. end;
  2456. end;
  2457. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2458. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2459. begin
  2460. Result := False;
  2461. { For safety reasons, only check for exact register matches }
  2462. { Check base register }
  2463. if (ref.base = AOldReg) then
  2464. begin
  2465. ref.base := ANewReg;
  2466. Result := True;
  2467. end;
  2468. { Check index register }
  2469. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2470. begin
  2471. ref.index := ANewReg;
  2472. Result := True;
  2473. end;
  2474. end;
  2475. { Replaces all references to AOldReg in an operand to ANewReg }
  2476. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2477. var
  2478. OldSupReg, NewSupReg: TSuperRegister;
  2479. OldSubReg, NewSubReg: TSubRegister;
  2480. OldRegType: TRegisterType;
  2481. ThisOper: POper;
  2482. begin
  2483. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2484. Result := False;
  2485. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2486. InternalError(2020011801);
  2487. OldSupReg := getsupreg(AOldReg);
  2488. OldSubReg := getsubreg(AOldReg);
  2489. OldRegType := getregtype(AOldReg);
  2490. NewSupReg := getsupreg(ANewReg);
  2491. NewSubReg := getsubreg(ANewReg);
  2492. if OldRegType <> getregtype(ANewReg) then
  2493. InternalError(2020011802);
  2494. if OldSubReg <> NewSubReg then
  2495. InternalError(2020011803);
  2496. case ThisOper^.typ of
  2497. top_reg:
  2498. if (
  2499. (ThisOper^.reg = AOldReg) or
  2500. (
  2501. (OldRegType = R_INTREGISTER) and
  2502. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2503. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2504. (
  2505. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2506. {$ifndef x86_64}
  2507. and (
  2508. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2509. don't have an 8-bit representation }
  2510. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2511. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2512. )
  2513. {$endif x86_64}
  2514. )
  2515. )
  2516. ) then
  2517. begin
  2518. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2519. Result := True;
  2520. end;
  2521. top_ref:
  2522. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2523. Result := True;
  2524. else
  2525. ;
  2526. end;
  2527. end;
  2528. { Replaces all references to AOldReg in an instruction to ANewReg }
  2529. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2530. const
  2531. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2532. var
  2533. OperIdx: Integer;
  2534. begin
  2535. Result := False;
  2536. for OperIdx := 0 to p.ops - 1 do
  2537. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2538. begin
  2539. { The shift and rotate instructions can only use CL }
  2540. if not (
  2541. (OperIdx = 0) and
  2542. { This second condition just helps to avoid unnecessarily
  2543. calling MatchInstruction for 10 different opcodes }
  2544. (p.oper[0]^.reg = NR_CL) and
  2545. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2546. ) then
  2547. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2548. end
  2549. else if p.oper[OperIdx]^.typ = top_ref then
  2550. { It's okay to replace registers in references that get written to }
  2551. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2552. end;
  2553. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2554. begin
  2555. Result :=
  2556. (ref^.index = NR_NO) and
  2557. (
  2558. {$ifdef x86_64}
  2559. (
  2560. (ref^.base = NR_RIP) and
  2561. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2562. ) or
  2563. {$endif x86_64}
  2564. (ref^.refaddr = addr_full) or
  2565. (ref^.base = NR_STACK_POINTER_REG) or
  2566. (ref^.base = current_procinfo.framepointer)
  2567. );
  2568. end;
  2569. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2570. var
  2571. l: asizeint;
  2572. begin
  2573. Result := False;
  2574. { Should have been checked previously }
  2575. if p.opcode <> A_LEA then
  2576. InternalError(2020072501);
  2577. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2578. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2579. not(cs_opt_size in current_settings.optimizerswitches) then
  2580. exit;
  2581. with p.oper[0]^.ref^ do
  2582. begin
  2583. if (base <> p.oper[1]^.reg) or
  2584. (index <> NR_NO) or
  2585. assigned(symbol) then
  2586. exit;
  2587. l:=offset;
  2588. if (l=1) and UseIncDec then
  2589. begin
  2590. p.opcode:=A_INC;
  2591. p.loadreg(0,p.oper[1]^.reg);
  2592. p.ops:=1;
  2593. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2594. end
  2595. else if (l=-1) and UseIncDec then
  2596. begin
  2597. p.opcode:=A_DEC;
  2598. p.loadreg(0,p.oper[1]^.reg);
  2599. p.ops:=1;
  2600. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2601. end
  2602. else
  2603. begin
  2604. if (l<0) and (l<>-2147483648) then
  2605. begin
  2606. p.opcode:=A_SUB;
  2607. p.loadConst(0,-l);
  2608. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2609. end
  2610. else
  2611. begin
  2612. p.opcode:=A_ADD;
  2613. p.loadConst(0,l);
  2614. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2615. end;
  2616. end;
  2617. end;
  2618. Result := True;
  2619. end;
  2620. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2621. var
  2622. CurrentReg, ReplaceReg: TRegister;
  2623. begin
  2624. Result := False;
  2625. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2626. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2627. case hp.opcode of
  2628. A_FSTSW, A_FNSTSW,
  2629. A_IN, A_INS, A_OUT, A_OUTS,
  2630. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2631. { These routines have explicit operands, but they are restricted in
  2632. what they can be (e.g. IN and OUT can only read from AL, AX or
  2633. EAX. }
  2634. Exit;
  2635. A_IMUL:
  2636. begin
  2637. { The 1-operand version writes to implicit registers
  2638. The 2-operand version reads from the first operator, and reads
  2639. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2640. the 3-operand version reads from a register that it doesn't write to
  2641. }
  2642. case hp.ops of
  2643. 1:
  2644. if (
  2645. (
  2646. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2647. ) or
  2648. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2649. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2650. begin
  2651. Result := True;
  2652. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2653. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2654. end;
  2655. 2:
  2656. { Only modify the first parameter }
  2657. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2658. begin
  2659. Result := True;
  2660. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2661. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2662. end;
  2663. 3:
  2664. { Only modify the second parameter }
  2665. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2666. begin
  2667. Result := True;
  2668. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2669. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2670. end;
  2671. else
  2672. InternalError(2020012901);
  2673. end;
  2674. end;
  2675. else
  2676. if (hp.ops > 0) and
  2677. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2678. begin
  2679. Result := True;
  2680. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2681. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2682. end;
  2683. end;
  2684. end;
  2685. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2686. var
  2687. hp2, hp_regalloc: tai;
  2688. p_SourceReg, p_TargetReg: TRegister;
  2689. begin
  2690. Result := False;
  2691. { Backward optimisation. If we have:
  2692. func. %reg1,%reg2
  2693. mov %reg2,%reg3
  2694. (dealloc %reg2)
  2695. Change to:
  2696. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2697. Perform similar optimisations with 1, 3 and 4-operand instructions
  2698. that only have one output.
  2699. }
  2700. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2701. begin
  2702. p_SourceReg := taicpu(p).oper[0]^.reg;
  2703. p_TargetReg := taicpu(p).oper[1]^.reg;
  2704. TransferUsedRegs(TmpUsedRegs);
  2705. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2706. GetLastInstruction(p, hp2) and
  2707. (hp2.typ = ait_instruction) and
  2708. { Have to make sure it's an instruction that only reads from
  2709. the first operands and only writes (not reads or modifies) to
  2710. the last one; in essence, a pure function such as BSR, POPCNT
  2711. or ANDN }
  2712. (
  2713. (
  2714. (taicpu(hp2).ops = 1) and
  2715. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2716. ) or
  2717. (
  2718. (taicpu(hp2).ops = 2) and
  2719. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2720. ) or
  2721. (
  2722. (taicpu(hp2).ops = 3) and
  2723. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2724. ) or
  2725. (
  2726. (taicpu(hp2).ops = 4) and
  2727. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2728. )
  2729. ) and
  2730. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2731. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2732. begin
  2733. case taicpu(hp2).opcode of
  2734. A_FSTSW, A_FNSTSW,
  2735. A_IN, A_INS, A_OUT, A_OUTS,
  2736. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2737. { These routines have explicit operands, but they are restricted in
  2738. what they can be (e.g. IN and OUT can only read from AL, AX or
  2739. EAX. }
  2740. ;
  2741. else
  2742. begin
  2743. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2744. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2745. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2746. if Assigned(hp_regalloc) then
  2747. begin
  2748. Asml.Remove(hp_regalloc);
  2749. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2750. begin
  2751. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2752. hp_regalloc.Free;
  2753. end
  2754. else
  2755. { If the register is not explicitly deallocated, it's
  2756. being reused, so move the allocation to after func. }
  2757. AsmL.InsertAfter(hp_regalloc, hp2);
  2758. end;
  2759. if not RegInInstruction(p_TargetReg, hp2) then
  2760. begin
  2761. TransferUsedRegs(TmpUsedRegs);
  2762. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2763. end;
  2764. { Actually make the changes }
  2765. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2766. RemoveCurrentp(p, hp1);
  2767. { If the Func was another MOV instruction, we might get
  2768. "mov %reg,%reg" that doesn't get removed in Pass 2
  2769. otherwise, so deal with it here (also do something
  2770. similar with lea (%reg),%reg}
  2771. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2772. begin
  2773. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2774. if p = hp2 then
  2775. RemoveCurrentp(p)
  2776. else
  2777. RemoveInstruction(hp2);
  2778. end;
  2779. Result := True;
  2780. Exit;
  2781. end;
  2782. end;
  2783. end;
  2784. end;
  2785. end;
  2786. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2787. begin
  2788. Result := False;
  2789. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2790. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2791. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2792. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2793. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2794. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2795. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2796. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2797. begin
  2798. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2799. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2800. Result := True;
  2801. Include(OptsToCheck, aoc_ForceNewIteration);
  2802. end;
  2803. end;
  2804. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2805. var
  2806. hp1, hp2, hp3, hp4: tai;
  2807. DoOptimisation, TempBool: Boolean;
  2808. {$ifdef x86_64}
  2809. NewConst: TCGInt;
  2810. {$endif x86_64}
  2811. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2812. begin
  2813. if taicpu(hp1).opcode = signed_movop then
  2814. begin
  2815. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2816. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2817. end
  2818. else
  2819. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2820. end;
  2821. function TryConstMerge(var p1, p2: tai): Boolean;
  2822. var
  2823. ThisRef: TReference;
  2824. begin
  2825. Result := False;
  2826. ThisRef := taicpu(p2).oper[1]^.ref^;
  2827. { Only permit writes to the stack, since we can guarantee alignment with that }
  2828. if (ThisRef.index = NR_NO) and
  2829. (
  2830. (ThisRef.base = NR_STACK_POINTER_REG) or
  2831. (ThisRef.base = current_procinfo.framepointer)
  2832. ) then
  2833. begin
  2834. case taicpu(p).opsize of
  2835. S_B:
  2836. begin
  2837. { Word writes must be on a 2-byte boundary }
  2838. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2839. begin
  2840. { Reduce offset of second reference to see if it is sequential with the first }
  2841. Dec(ThisRef.offset, 1);
  2842. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2843. begin
  2844. { Make sure the constants aren't represented as a
  2845. negative number, as these won't merge properly }
  2846. taicpu(p1).opsize := S_W;
  2847. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2848. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2849. RemoveInstruction(p2);
  2850. Result := True;
  2851. end;
  2852. end;
  2853. end;
  2854. S_W:
  2855. begin
  2856. { Longword writes must be on a 4-byte boundary }
  2857. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2858. begin
  2859. { Reduce offset of second reference to see if it is sequential with the first }
  2860. Dec(ThisRef.offset, 2);
  2861. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2862. begin
  2863. { Make sure the constants aren't represented as a
  2864. negative number, as these won't merge properly }
  2865. taicpu(p1).opsize := S_L;
  2866. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2867. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2868. RemoveInstruction(p2);
  2869. Result := True;
  2870. end;
  2871. end;
  2872. end;
  2873. {$ifdef x86_64}
  2874. S_L:
  2875. begin
  2876. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2877. see if the constants can be encoded this way. }
  2878. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2879. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2880. { Quadword writes must be on an 8-byte boundary }
  2881. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2882. begin
  2883. { Reduce offset of second reference to see if it is sequential with the first }
  2884. Dec(ThisRef.offset, 4);
  2885. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2886. begin
  2887. { Make sure the constants aren't represented as a
  2888. negative number, as these won't merge properly }
  2889. taicpu(p1).opsize := S_Q;
  2890. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2891. taicpu(p1).oper[0]^.val := NewConst;
  2892. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2893. RemoveInstruction(p2);
  2894. Result := True;
  2895. end;
  2896. end;
  2897. end;
  2898. {$endif x86_64}
  2899. else
  2900. ;
  2901. end;
  2902. end;
  2903. end;
  2904. var
  2905. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2906. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2907. NewSize: topsize; NewOffset: asizeint;
  2908. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2909. SourceRef, TargetRef: TReference;
  2910. MovAligned, MovUnaligned: TAsmOp;
  2911. ThisRef: TReference;
  2912. JumpTracking: TLinkedList;
  2913. begin
  2914. Result:=false;
  2915. { remove mov reg1,reg1? }
  2916. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2917. then
  2918. begin
  2919. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2920. { take care of the register (de)allocs following p }
  2921. RemoveCurrentP(p);
  2922. Result := True;
  2923. exit;
  2924. end;
  2925. { Prevent compiler warnings }
  2926. p_SourceReg := NR_NO;
  2927. p_TargetReg := NR_NO;
  2928. if taicpu(p).oper[1]^.typ = top_reg then
  2929. begin
  2930. { Saves on a large number of dereferences }
  2931. p_TargetReg := taicpu(p).oper[1]^.reg;
  2932. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  2933. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_TargetReg)
  2934. else
  2935. GetNextInstruction_p := GetNextInstruction(p, hp1);
  2936. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  2937. begin
  2938. if (taicpu(hp1).opcode = A_AND) and
  2939. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2940. begin
  2941. if MatchOperand(taicpu(hp1).oper[1]^, p_TargetReg) then
  2942. begin
  2943. case taicpu(p).opsize of
  2944. S_L:
  2945. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2946. begin
  2947. { Optimize out:
  2948. mov x, %reg
  2949. and ffffffffh, %reg
  2950. }
  2951. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2952. RemoveInstruction(hp1);
  2953. Result:=true;
  2954. exit;
  2955. end;
  2956. S_Q: { TODO: Confirm if this is even possible }
  2957. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2958. begin
  2959. { Optimize out:
  2960. mov x, %reg
  2961. and ffffffffffffffffh, %reg
  2962. }
  2963. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2964. RemoveInstruction(hp1);
  2965. Result:=true;
  2966. exit;
  2967. end;
  2968. else
  2969. ;
  2970. end;
  2971. if (
  2972. { Make sure that if a reference is used, its registers
  2973. are not modified in between }
  2974. (
  2975. (taicpu(p).oper[0]^.typ = top_reg) and
  2976. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2977. ) or
  2978. (
  2979. (taicpu(p).oper[0]^.typ = top_ref) and
  2980. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  2981. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1)
  2982. )
  2983. ) and
  2984. GetNextInstruction(hp1,hp2) and
  2985. MatchInstruction(hp2,A_TEST,[]) and
  2986. (
  2987. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2988. (
  2989. { If the register being tested is smaller than the one
  2990. that received a bitwise AND, permit it if the constant
  2991. fits into the smaller size }
  2992. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2993. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2994. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2995. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2996. (
  2997. (
  2998. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2999. (taicpu(hp1).oper[0]^.val <= $FF)
  3000. ) or
  3001. (
  3002. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3003. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3004. {$ifdef x86_64}
  3005. ) or
  3006. (
  3007. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3008. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3009. {$endif x86_64}
  3010. )
  3011. )
  3012. )
  3013. ) and
  3014. (
  3015. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3016. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3017. ) and
  3018. GetNextInstruction(hp2,hp3) and
  3019. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3020. (taicpu(hp3).condition in [C_E,C_NE]) then
  3021. begin
  3022. TransferUsedRegs(TmpUsedRegs);
  3023. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3024. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3025. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3026. begin
  3027. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3028. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3029. taicpu(hp1).opcode:=A_TEST;
  3030. { Shrink the TEST instruction down to the smallest possible size }
  3031. case taicpu(hp1).oper[0]^.val of
  3032. 0..255:
  3033. if (taicpu(hp1).opsize <> S_B)
  3034. {$ifndef x86_64}
  3035. and (
  3036. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3037. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3038. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3039. )
  3040. {$endif x86_64}
  3041. then
  3042. begin
  3043. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3044. { Only print debug message if the TEST instruction
  3045. is a different size before and after }
  3046. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3047. taicpu(hp1).opsize := S_B;
  3048. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3049. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3050. end;
  3051. 256..65535:
  3052. if (taicpu(hp1).opsize <> S_W) then
  3053. begin
  3054. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3055. { Only print debug message if the TEST instruction
  3056. is a different size before and after }
  3057. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3058. taicpu(hp1).opsize := S_W;
  3059. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3060. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3061. end;
  3062. {$ifdef x86_64}
  3063. 65536..$7FFFFFFF:
  3064. if (taicpu(hp1).opsize <> S_L) then
  3065. begin
  3066. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3067. { Only print debug message if the TEST instruction
  3068. is a different size before and after }
  3069. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3070. taicpu(hp1).opsize := S_L;
  3071. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3072. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3073. end;
  3074. {$endif x86_64}
  3075. else
  3076. ;
  3077. end;
  3078. RemoveInstruction(hp2);
  3079. RemoveCurrentP(p);
  3080. Result:=true;
  3081. exit;
  3082. end;
  3083. end;
  3084. end;
  3085. if IsMOVZXAcceptable and
  3086. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3087. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3088. (getsupreg(p_TargetReg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3089. then
  3090. begin
  3091. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3092. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3093. case taicpu(p).opsize of
  3094. S_B:
  3095. if (taicpu(hp1).oper[0]^.val = $ff) then
  3096. begin
  3097. { Convert:
  3098. movb x, %regl movb x, %regl
  3099. andw ffh, %regw andl ffh, %regd
  3100. To:
  3101. movzbw x, %regd movzbl x, %regd
  3102. (Identical registers, just different sizes)
  3103. }
  3104. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3105. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3106. case taicpu(hp1).opsize of
  3107. S_W: NewSize := S_BW;
  3108. S_L: NewSize := S_BL;
  3109. {$ifdef x86_64}
  3110. S_Q: NewSize := S_BQ;
  3111. {$endif x86_64}
  3112. else
  3113. InternalError(2018011510);
  3114. end;
  3115. end
  3116. else
  3117. NewSize := S_NO;
  3118. S_W:
  3119. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3120. begin
  3121. { Convert:
  3122. movw x, %regw
  3123. andl ffffh, %regd
  3124. To:
  3125. movzwl x, %regd
  3126. (Identical registers, just different sizes)
  3127. }
  3128. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3129. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3130. case taicpu(hp1).opsize of
  3131. S_L: NewSize := S_WL;
  3132. {$ifdef x86_64}
  3133. S_Q: NewSize := S_WQ;
  3134. {$endif x86_64}
  3135. else
  3136. InternalError(2018011511);
  3137. end;
  3138. end
  3139. else
  3140. NewSize := S_NO;
  3141. else
  3142. NewSize := S_NO;
  3143. end;
  3144. if NewSize <> S_NO then
  3145. begin
  3146. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3147. { The actual optimization }
  3148. taicpu(p).opcode := A_MOVZX;
  3149. taicpu(p).changeopsize(NewSize);
  3150. taicpu(p).loadoper(1, taicpu(hp1).oper[1]^);
  3151. { Make sure we deal with any reference counts that were increased }
  3152. if taicpu(hp1).oper[1]^.typ = top_ref then
  3153. begin
  3154. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  3155. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  3156. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  3157. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  3158. end;
  3159. { Safeguard if "and" is followed by a conditional command }
  3160. TransferUsedRegs(TmpUsedRegs);
  3161. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  3162. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3163. begin
  3164. { At this point, the "and" command is effectively equivalent to
  3165. "test %reg,%reg". This will be handled separately by the
  3166. Peephole Optimizer. [Kit] }
  3167. DebugMsg(SPeepholeOptimization + PreMessage +
  3168. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3169. end
  3170. else
  3171. begin
  3172. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3173. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3174. RemoveInstruction(hp1);
  3175. end;
  3176. Result := True;
  3177. Exit;
  3178. end;
  3179. end;
  3180. end;
  3181. if taicpu(p).oper[0]^.typ = top_reg then
  3182. begin
  3183. p_SourceReg := taicpu(p).oper[0]^.reg;
  3184. { Look for:
  3185. mov %reg1,%reg2
  3186. ??? %reg2,r/m
  3187. Change to:
  3188. mov %reg1,%reg2
  3189. ??? %reg1,r/m
  3190. }
  3191. if RegReadByInstruction(p_TargetReg, hp1) and
  3192. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3193. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  3194. begin
  3195. { A change has occurred, just not in p }
  3196. Include(OptsToCheck, aoc_ForceNewIteration);
  3197. TransferUsedRegs(TmpUsedRegs);
  3198. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3199. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3200. { Just in case something didn't get modified (e.g. an
  3201. implicit register) }
  3202. not RegReadByInstruction(p_TargetReg, hp1) then
  3203. begin
  3204. { We can remove the original MOV }
  3205. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  3206. RemoveCurrentP(p);
  3207. { UsedRegs got updated by RemoveCurrentp }
  3208. Result := True;
  3209. Exit;
  3210. end;
  3211. { If we know a MOV instruction has become a null operation, we might as well
  3212. get rid of it now to save time. }
  3213. if (taicpu(hp1).opcode = A_MOV) and
  3214. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3215. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  3216. { Just being a register is enough to confirm it's a null operation }
  3217. (taicpu(hp1).oper[0]^.typ = top_reg) then
  3218. begin
  3219. Result := True;
  3220. { Speed-up to reduce a pipeline stall... if we had something like...
  3221. movl %eax,%edx
  3222. movw %dx,%ax
  3223. ... the second instruction would change to movw %ax,%ax, but
  3224. given that it is now %ax that's active rather than %eax,
  3225. penalties might occur due to a partial register write, so instead,
  3226. change it to a MOVZX instruction when optimising for speed.
  3227. }
  3228. if not (cs_opt_size in current_settings.optimizerswitches) and
  3229. IsMOVZXAcceptable and
  3230. (taicpu(hp1).opsize < taicpu(p).opsize)
  3231. {$ifdef x86_64}
  3232. { operations already implicitly set the upper 64 bits to zero }
  3233. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  3234. {$endif x86_64}
  3235. then
  3236. begin
  3237. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  3238. case taicpu(p).opsize of
  3239. S_W:
  3240. if taicpu(hp1).opsize = S_B then
  3241. taicpu(hp1).opsize := S_BL
  3242. else
  3243. InternalError(2020012911);
  3244. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  3245. case taicpu(hp1).opsize of
  3246. S_B:
  3247. taicpu(hp1).opsize := S_BL;
  3248. S_W:
  3249. taicpu(hp1).opsize := S_WL;
  3250. else
  3251. InternalError(2020012912);
  3252. end;
  3253. else
  3254. InternalError(2020012910);
  3255. end;
  3256. taicpu(hp1).opcode := A_MOVZX;
  3257. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3258. end
  3259. else
  3260. begin
  3261. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  3262. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  3263. RemoveInstruction(hp1);
  3264. { The instruction after what was hp1 is now the immediate next instruction,
  3265. so we can continue to make optimisations if it's present }
  3266. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  3267. Exit;
  3268. hp1 := hp2;
  3269. end;
  3270. end;
  3271. end;
  3272. {$ifdef x86_64}
  3273. { Change:
  3274. movl %reg1l,%reg2l
  3275. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3276. To:
  3277. movl %reg1l,%reg2l
  3278. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3279. If %reg1 = %reg3, convert to:
  3280. movl %reg1l,%reg2l
  3281. andl %reg1l,%reg1l
  3282. }
  3283. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3284. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3285. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3286. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg) then
  3287. begin
  3288. TransferUsedRegs(TmpUsedRegs);
  3289. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3290. taicpu(hp1).opsize := S_L;
  3291. taicpu(hp1).loadreg(0, p_SourceReg);
  3292. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3293. AllocRegBetween(p_SourceReg, p, hp1, UsedRegs);
  3294. if (p_SourceReg = taicpu(hp1).oper[1]^.reg) then
  3295. begin
  3296. { %reg1 = %reg3 }
  3297. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3298. taicpu(hp1).opcode := A_AND;
  3299. end
  3300. else
  3301. begin
  3302. { %reg1 <> %reg3 }
  3303. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3304. end;
  3305. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3306. begin
  3307. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3308. RemoveCurrentP(p);
  3309. Result := True;
  3310. Exit;
  3311. end
  3312. else
  3313. begin
  3314. { Initial instruction wasn't actually changed }
  3315. Include(OptsToCheck, aoc_ForceNewIteration);
  3316. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3317. appears below since %reg1 has technically changed }
  3318. if taicpu(hp1).opcode = A_AND then
  3319. Exit;
  3320. end;
  3321. end;
  3322. {$endif x86_64}
  3323. end
  3324. else if taicpu(p).oper[0]^.typ = top_const then
  3325. begin
  3326. if (taicpu(hp1).opcode = A_OR) and
  3327. (taicpu(p).oper[1]^.typ = top_reg) and
  3328. MatchOperand(taicpu(p).oper[0]^, 0) and
  3329. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3330. begin
  3331. { mov 0, %reg
  3332. or ###,%reg
  3333. Change to (only if the flags are not used):
  3334. mov ###,%reg
  3335. }
  3336. TransferUsedRegs(TmpUsedRegs);
  3337. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3338. DoOptimisation := True;
  3339. { Even if the flags are used, we might be able to do the optimisation
  3340. if the conditions are predictable }
  3341. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3342. begin
  3343. { Only perform if ### = %reg (the same register) or equal to 0,
  3344. so %reg is guaranteed to still have a value of zero }
  3345. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3346. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3347. begin
  3348. hp2 := hp1;
  3349. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3350. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3351. GetNextInstruction(hp2, hp3) do
  3352. begin
  3353. { Don't continue modifying if the flags state is getting changed }
  3354. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3355. Break;
  3356. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3357. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3358. begin
  3359. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3360. begin
  3361. { Condition is always true }
  3362. case taicpu(hp3).opcode of
  3363. A_Jcc:
  3364. begin
  3365. { Check for jump shortcuts before we destroy the condition }
  3366. hp4 := hp3;
  3367. DoJumpOptimizations(hp3, TempBool);
  3368. { Make sure hp3 hasn't changed }
  3369. if (hp4 = hp3) then
  3370. begin
  3371. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3372. MakeUnconditional(taicpu(hp3));
  3373. end;
  3374. Result := True;
  3375. end;
  3376. A_CMOVcc:
  3377. begin
  3378. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3379. taicpu(hp3).opcode := A_MOV;
  3380. taicpu(hp3).condition := C_None;
  3381. Result := True;
  3382. end;
  3383. A_SETcc:
  3384. begin
  3385. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3386. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3387. taicpu(hp3).opcode := A_MOV;
  3388. taicpu(hp3).ops := 2;
  3389. taicpu(hp3).condition := C_None;
  3390. taicpu(hp3).opsize := S_B;
  3391. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3392. taicpu(hp3).loadconst(0, 1);
  3393. Result := True;
  3394. end;
  3395. else
  3396. InternalError(2021090701);
  3397. end;
  3398. end
  3399. 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
  3400. begin
  3401. { Condition is always false }
  3402. case taicpu(hp3).opcode of
  3403. A_Jcc:
  3404. begin
  3405. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3406. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3407. RemoveInstruction(hp3);
  3408. Result := True;
  3409. { Since hp3 was deleted, hp2 must not be updated }
  3410. Continue;
  3411. end;
  3412. A_CMOVcc:
  3413. begin
  3414. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3415. RemoveInstruction(hp3);
  3416. Result := True;
  3417. { Since hp3 was deleted, hp2 must not be updated }
  3418. Continue;
  3419. end;
  3420. A_SETcc:
  3421. begin
  3422. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3423. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3424. taicpu(hp3).opcode := A_MOV;
  3425. taicpu(hp3).ops := 2;
  3426. taicpu(hp3).condition := C_None;
  3427. taicpu(hp3).opsize := S_B;
  3428. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3429. taicpu(hp3).loadconst(0, 0);
  3430. Result := True;
  3431. end;
  3432. else
  3433. InternalError(2021090702);
  3434. end;
  3435. end
  3436. else
  3437. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3438. DoOptimisation := False;
  3439. end;
  3440. hp2 := hp3;
  3441. end;
  3442. if DoOptimisation then
  3443. begin
  3444. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3445. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3446. { Flags are still in use - don't optimise }
  3447. DoOptimisation := False;
  3448. end;
  3449. end
  3450. else
  3451. DoOptimisation := False;
  3452. end;
  3453. if DoOptimisation then
  3454. begin
  3455. {$ifdef x86_64}
  3456. { OR only supports 32-bit sign-extended constants for 64-bit
  3457. instructions, so compensate for this if the constant is
  3458. encoded as a value greater than or equal to 2^31 }
  3459. if (taicpu(hp1).opsize = S_Q) and
  3460. (taicpu(hp1).oper[0]^.typ = top_const) and
  3461. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3462. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3463. {$endif x86_64}
  3464. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3465. taicpu(hp1).opcode := A_MOV;
  3466. RemoveCurrentP(p);
  3467. Result := True;
  3468. Exit;
  3469. end;
  3470. end;
  3471. end
  3472. else if
  3473. { oper[0] is a reference }
  3474. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) then
  3475. begin
  3476. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  3477. begin
  3478. if ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3479. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3480. ) or
  3481. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3482. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3483. )
  3484. ) and
  3485. not RegModifiedBetween(Taicpu(hp1).oper[1]^.reg, p, hp1) then
  3486. { mov ref,reg1
  3487. lea (reg1,reg2),reg2
  3488. to
  3489. add ref,reg2 }
  3490. begin
  3491. TransferUsedRegs(TmpUsedRegs);
  3492. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3493. { If the flags register is in use, don't change the instruction to an
  3494. ADD otherwise this will scramble the flags. [Kit] }
  3495. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3496. { reg1 may not be used afterwards }
  3497. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3498. begin
  3499. Taicpu(hp1).opcode:=A_ADD;
  3500. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3501. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3502. RemoveCurrentp(p);
  3503. result:=true;
  3504. exit;
  3505. end;
  3506. end;
  3507. { If the LEA instruction can be converted into an arithmetic instruction,
  3508. it may be possible to then fold it in the next optimisation. }
  3509. if ConvertLEA(taicpu(hp1)) then
  3510. Include(OptsToCheck, aoc_ForceNewIteration);
  3511. end;
  3512. end;
  3513. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  3514. overwrites the original destination register. e.g.
  3515. movl ###,%reg2d
  3516. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  3517. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  3518. }
  3519. if MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  3520. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3521. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  3522. begin
  3523. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  3524. begin
  3525. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  3526. case taicpu(p).oper[0]^.typ of
  3527. top_const:
  3528. { We have something like:
  3529. movb $x, %regb
  3530. movzbl %regb,%regd
  3531. Change to:
  3532. movl $x, %regd
  3533. }
  3534. begin
  3535. case taicpu(hp1).opsize of
  3536. S_BW:
  3537. begin
  3538. convert_mov_value(A_MOVSX, $FF);
  3539. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  3540. taicpu(p).opsize := S_W;
  3541. end;
  3542. S_BL:
  3543. begin
  3544. convert_mov_value(A_MOVSX, $FF);
  3545. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3546. taicpu(p).opsize := S_L;
  3547. end;
  3548. S_WL:
  3549. begin
  3550. convert_mov_value(A_MOVSX, $FFFF);
  3551. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3552. taicpu(p).opsize := S_L;
  3553. end;
  3554. {$ifdef x86_64}
  3555. S_BQ:
  3556. begin
  3557. convert_mov_value(A_MOVSX, $FF);
  3558. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3559. taicpu(p).opsize := S_Q;
  3560. end;
  3561. S_WQ:
  3562. begin
  3563. convert_mov_value(A_MOVSX, $FFFF);
  3564. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3565. taicpu(p).opsize := S_Q;
  3566. end;
  3567. S_LQ:
  3568. begin
  3569. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3570. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3571. taicpu(p).opsize := S_Q;
  3572. end;
  3573. {$endif x86_64}
  3574. else
  3575. { If hp1 was a MOV instruction, it should have been
  3576. optimised already }
  3577. InternalError(2020021001);
  3578. end;
  3579. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3580. RemoveInstruction(hp1);
  3581. Result := True;
  3582. Exit;
  3583. end;
  3584. top_ref:
  3585. begin
  3586. { We have something like:
  3587. movb mem, %regb
  3588. movzbl %regb,%regd
  3589. Change to:
  3590. movzbl mem, %regd
  3591. }
  3592. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3593. begin
  3594. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3595. taicpu(p).opcode := taicpu(hp1).opcode;
  3596. taicpu(p).opsize := taicpu(hp1).opsize;
  3597. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  3598. RemoveInstruction(hp1);
  3599. Result := True;
  3600. Exit;
  3601. end;
  3602. end;
  3603. else
  3604. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3605. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3606. Exit;
  3607. end;
  3608. end
  3609. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3610. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3611. optimised }
  3612. else
  3613. begin
  3614. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3615. RemoveCurrentP(p);
  3616. Result := True;
  3617. Exit;
  3618. end;
  3619. end;
  3620. if (taicpu(hp1).opcode = A_MOV) and
  3621. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3622. begin
  3623. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3624. TransferUsedRegs(TmpUsedRegs);
  3625. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3626. { we have
  3627. mov x, %treg
  3628. mov %treg, y
  3629. }
  3630. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3631. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3632. begin
  3633. { we've got
  3634. mov x, %treg
  3635. mov %treg, y
  3636. with %treg is not used after }
  3637. case taicpu(p).oper[0]^.typ Of
  3638. { top_reg is covered by DeepMOVOpt }
  3639. top_const:
  3640. begin
  3641. { change
  3642. mov const, %treg
  3643. mov %treg, y
  3644. to
  3645. mov const, y
  3646. }
  3647. {$ifdef x86_64}
  3648. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3649. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3650. {$endif x86_64}
  3651. begin
  3652. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3653. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done', hp1);
  3654. RemoveCurrentP(p);
  3655. Result := True;
  3656. Exit;
  3657. end;
  3658. end;
  3659. top_ref:
  3660. case taicpu(hp1).oper[1]^.typ of
  3661. top_reg:
  3662. { change
  3663. mov mem, %treg
  3664. mov %treg, %reg
  3665. to
  3666. mov mem, %reg"
  3667. }
  3668. if not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) then
  3669. begin
  3670. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3671. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3a done', p);
  3672. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  3673. RemoveInstruction(hp1);
  3674. Result := True;
  3675. Exit;
  3676. end
  3677. else if
  3678. { Make sure that if a reference is used, its
  3679. registers are not modified in between }
  3680. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3681. begin
  3682. 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
  3683. AllocRegBetween(taicpu(p).oper[0]^.ref^.base, p, hp1, UsedRegs);
  3684. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and (taicpu(p).oper[0]^.ref^.index <> taicpu(p).oper[0]^.ref^.base) then
  3685. AllocRegBetween(taicpu(p).oper[0]^.ref^.index, p, hp1, UsedRegs);
  3686. taicpu(hp1).loadref(0, taicpu(p).oper[0]^.ref^);
  3687. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3688. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3689. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3690. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3691. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done', hp1);
  3692. RemoveCurrentP(p);
  3693. Result := True;
  3694. Exit;
  3695. end;
  3696. top_ref:
  3697. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3698. begin
  3699. {$ifdef x86_64}
  3700. { Look for the following to simplify:
  3701. mov x(mem1), %reg
  3702. mov %reg, y(mem2)
  3703. mov x+8(mem1), %reg
  3704. mov %reg, y+8(mem2)
  3705. Change to:
  3706. movdqu x(mem1), %xmmreg
  3707. movdqu %xmmreg, y(mem2)
  3708. ...but only as long as the memory blocks don't overlap
  3709. }
  3710. SourceRef := taicpu(p).oper[0]^.ref^;
  3711. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3712. if (taicpu(p).opsize = S_Q) and
  3713. not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3714. GetNextInstruction(hp1, hp2) and
  3715. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3716. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3717. begin
  3718. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3719. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3720. Inc(SourceRef.offset, 8);
  3721. if UseAVX then
  3722. begin
  3723. MovAligned := A_VMOVDQA;
  3724. MovUnaligned := A_VMOVDQU;
  3725. end
  3726. else
  3727. begin
  3728. MovAligned := A_MOVDQA;
  3729. MovUnaligned := A_MOVDQU;
  3730. end;
  3731. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3732. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3733. begin
  3734. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3735. Inc(TargetRef.offset, 8);
  3736. if GetNextInstruction(hp2, hp3) and
  3737. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3738. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3739. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3740. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3741. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3742. begin
  3743. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3744. if NewMMReg <> NR_NO then
  3745. begin
  3746. { Remember that the offsets are 8 ahead }
  3747. if ((SourceRef.offset mod 16) = 8) and
  3748. (
  3749. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3750. (SourceRef.base = current_procinfo.framepointer) or
  3751. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3752. ) then
  3753. taicpu(p).opcode := MovAligned
  3754. else
  3755. taicpu(p).opcode := MovUnaligned;
  3756. taicpu(p).opsize := S_XMM;
  3757. taicpu(p).oper[1]^.reg := NewMMReg;
  3758. if ((TargetRef.offset mod 16) = 8) and
  3759. (
  3760. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3761. (TargetRef.base = current_procinfo.framepointer) or
  3762. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3763. ) then
  3764. taicpu(hp1).opcode := MovAligned
  3765. else
  3766. taicpu(hp1).opcode := MovUnaligned;
  3767. taicpu(hp1).opsize := S_XMM;
  3768. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3769. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3770. RemoveInstruction(hp2);
  3771. RemoveInstruction(hp3);
  3772. Result := True;
  3773. Exit;
  3774. end;
  3775. end;
  3776. end
  3777. else
  3778. begin
  3779. { See if the next references are 8 less rather than 8 greater }
  3780. Dec(SourceRef.offset, 16); { -8 the other way }
  3781. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3782. begin
  3783. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3784. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3785. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3786. GetNextInstruction(hp2, hp3) and
  3787. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3788. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3789. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3790. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3791. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3792. begin
  3793. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3794. if NewMMReg <> NR_NO then
  3795. begin
  3796. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3797. if ((SourceRef.offset mod 16) = 0) and
  3798. (
  3799. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3800. (SourceRef.base = current_procinfo.framepointer) or
  3801. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3802. ) then
  3803. taicpu(hp2).opcode := MovAligned
  3804. else
  3805. taicpu(hp2).opcode := MovUnaligned;
  3806. taicpu(hp2).opsize := S_XMM;
  3807. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3808. if ((TargetRef.offset mod 16) = 0) and
  3809. (
  3810. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3811. (TargetRef.base = current_procinfo.framepointer) or
  3812. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3813. ) then
  3814. taicpu(hp3).opcode := MovAligned
  3815. else
  3816. taicpu(hp3).opcode := MovUnaligned;
  3817. taicpu(hp3).opsize := S_XMM;
  3818. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3819. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3820. RemoveInstruction(hp1);
  3821. RemoveCurrentP(p);
  3822. Result := True;
  3823. Exit;
  3824. end;
  3825. end;
  3826. end;
  3827. end;
  3828. end;
  3829. {$endif x86_64}
  3830. end;
  3831. else
  3832. { The write target should be a reg or a ref }
  3833. InternalError(2021091601);
  3834. end;
  3835. else
  3836. ;
  3837. end;
  3838. end
  3839. else if (taicpu(p).oper[0]^.typ = top_const) and
  3840. { %treg is used afterwards, but all eventualities other
  3841. than the first MOV instruction being a constant are
  3842. covered by DeepMOVOpt, so only check for that }
  3843. (
  3844. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3845. not (cs_opt_size in current_settings.optimizerswitches) or
  3846. (taicpu(hp1).opsize = S_B)
  3847. ) and
  3848. (
  3849. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3850. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3851. ) then
  3852. begin
  3853. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3854. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3855. Include(OptsToCheck, aoc_ForceNewIteration);
  3856. end;
  3857. end;
  3858. end;
  3859. end;
  3860. if taicpu(p).oper[0]^.typ = top_reg then
  3861. begin
  3862. { oper[1] is a reference }
  3863. { Saves on a large number of dereferences }
  3864. p_SourceReg := taicpu(p).oper[0]^.reg;
  3865. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  3866. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_SourceReg)
  3867. else
  3868. GetNextInstruction_p := GetNextInstruction(p, hp1);
  3869. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  3870. begin
  3871. if taicpu(p).oper[1]^.typ = top_reg then
  3872. begin
  3873. p_TargetReg := taicpu(p).oper[1]^.reg;
  3874. { Change:
  3875. movl %reg1,%reg2
  3876. ...
  3877. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3878. ...
  3879. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3880. To:
  3881. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3882. ...
  3883. movl x(%reg1),%reg1
  3884. ...
  3885. movl %reg1,%regX
  3886. }
  3887. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  3888. (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3889. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3890. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3891. not RegModifiedBetween(p_TargetReg, p, hp1) and
  3892. GetNextInstructionUsingReg(hp1, hp2, p_TargetReg) and
  3893. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3894. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3895. not RegModifiedBetween(p_SourceReg, hp1, hp2) then
  3896. begin
  3897. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3898. if RegInRef(p_TargetReg, SourceRef) and
  3899. { If %reg1 also appears in the second reference, then it will
  3900. not refer to the same memory block as the first reference }
  3901. not RegInRef(p_SourceReg, SourceRef) then
  3902. begin
  3903. { Check to see if the references match if %reg2 is changed to %reg1 }
  3904. if SourceRef.base = p_TargetReg then
  3905. SourceRef.base := p_SourceReg;
  3906. if SourceRef.index = p_TargetReg then
  3907. SourceRef.index := p_SourceReg;
  3908. { RefsEqual also checks to ensure both references are non-volatile }
  3909. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3910. begin
  3911. taicpu(hp2).loadreg(0, p_SourceReg);
  3912. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3913. Result := True;
  3914. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3915. begin
  3916. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3917. RemoveCurrentP(p);
  3918. Exit;
  3919. end
  3920. else
  3921. begin
  3922. { Check to see if %reg2 is no longer in use }
  3923. TransferUsedRegs(TmpUsedRegs);
  3924. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3925. UpdateUsedRegsBetween(TmpUsedRegs, tai(hp1.Next), hp2);
  3926. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3927. begin
  3928. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3929. RemoveCurrentP(p);
  3930. Exit;
  3931. end;
  3932. end;
  3933. { If we reach this point, p and hp1 weren't actually modified,
  3934. so we can do a bit more work on this pass }
  3935. end;
  3936. end;
  3937. end;
  3938. end;
  3939. end;
  3940. end;
  3941. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  3942. { All the next optimisations require a next instruction }
  3943. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  3944. Exit;
  3945. { Next instruction is also a MOV ? }
  3946. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3947. begin
  3948. if MatchOpType(taicpu(p), top_const, top_ref) and
  3949. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3950. TryConstMerge(p, hp1) then
  3951. begin
  3952. Result := True;
  3953. { In case we have four byte writes in a row, check for 2 more
  3954. right now so we don't have to wait for another iteration of
  3955. pass 1
  3956. }
  3957. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3958. case taicpu(p).opsize of
  3959. S_W:
  3960. begin
  3961. if GetNextInstruction(p, hp1) and
  3962. MatchInstruction(hp1, A_MOV, [S_B]) and
  3963. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3964. GetNextInstruction(hp1, hp2) and
  3965. MatchInstruction(hp2, A_MOV, [S_B]) and
  3966. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3967. { Try to merge the two bytes }
  3968. TryConstMerge(hp1, hp2) then
  3969. { Now try to merge the two words (hp2 will get deleted) }
  3970. TryConstMerge(p, hp1);
  3971. end;
  3972. S_L:
  3973. begin
  3974. { Though this only really benefits x86_64 and not i386, it
  3975. gets a potential optimisation done faster and hence
  3976. reduces the number of times OptPass1MOV is entered }
  3977. if GetNextInstruction(p, hp1) and
  3978. MatchInstruction(hp1, A_MOV, [S_W]) and
  3979. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3980. GetNextInstruction(hp1, hp2) and
  3981. MatchInstruction(hp2, A_MOV, [S_W]) and
  3982. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3983. { Try to merge the two words }
  3984. TryConstMerge(hp1, hp2) then
  3985. { This will always fail on i386, so don't bother
  3986. calling it unless we're doing x86_64 }
  3987. {$ifdef x86_64}
  3988. { Now try to merge the two longwords (hp2 will get deleted) }
  3989. TryConstMerge(p, hp1)
  3990. {$endif x86_64}
  3991. ;
  3992. end;
  3993. else
  3994. ;
  3995. end;
  3996. Exit;
  3997. end;
  3998. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3999. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4000. { mov reg1, mem1 or mov mem1, reg1
  4001. mov mem2, reg2 mov reg2, mem2}
  4002. begin
  4003. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4004. { mov reg1, mem1 or mov mem1, reg1
  4005. mov mem2, reg1 mov reg2, mem1}
  4006. begin
  4007. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4008. { Removes the second statement from
  4009. mov reg1, mem1/reg2
  4010. mov mem1/reg2, reg1 }
  4011. begin
  4012. if taicpu(p).oper[0]^.typ=top_reg then
  4013. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4014. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  4015. RemoveInstruction(hp1);
  4016. Result:=true;
  4017. exit;
  4018. end
  4019. else
  4020. begin
  4021. TransferUsedRegs(TmpUsedRegs);
  4022. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4023. if (taicpu(p).oper[1]^.typ = top_ref) and
  4024. { mov reg1, mem1
  4025. mov mem2, reg1 }
  4026. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  4027. GetNextInstruction(hp1, hp2) and
  4028. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  4029. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  4030. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  4031. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  4032. { change to
  4033. mov reg1, mem1 mov reg1, mem1
  4034. mov mem2, reg1 cmp reg1, mem2
  4035. cmp mem1, reg1
  4036. }
  4037. begin
  4038. RemoveInstruction(hp2);
  4039. taicpu(hp1).opcode := A_CMP;
  4040. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  4041. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4042. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4043. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  4044. end;
  4045. end;
  4046. end
  4047. else if (taicpu(p).oper[1]^.typ=top_ref) and
  4048. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4049. begin
  4050. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4051. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4052. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  4053. end
  4054. else
  4055. begin
  4056. TransferUsedRegs(TmpUsedRegs);
  4057. if GetNextInstruction(hp1, hp2) and
  4058. MatchOpType(taicpu(p),top_ref,top_reg) and
  4059. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4060. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4061. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  4062. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  4063. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4064. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  4065. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  4066. { mov mem1, %reg1
  4067. mov %reg1, mem2
  4068. mov mem2, reg2
  4069. to:
  4070. mov mem1, reg2
  4071. mov reg2, mem2}
  4072. begin
  4073. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  4074. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  4075. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  4076. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  4077. RemoveInstruction(hp2);
  4078. Result := True;
  4079. end
  4080. {$ifdef i386}
  4081. { this is enabled for i386 only, as the rules to create the reg sets below
  4082. are too complicated for x86-64, so this makes this code too error prone
  4083. on x86-64
  4084. }
  4085. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  4086. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  4087. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  4088. { mov mem1, reg1 mov mem1, reg1
  4089. mov reg1, mem2 mov reg1, mem2
  4090. mov mem2, reg2 mov mem2, reg1
  4091. to: to:
  4092. mov mem1, reg1 mov mem1, reg1
  4093. mov mem1, reg2 mov reg1, mem2
  4094. mov reg1, mem2
  4095. or (if mem1 depends on reg1
  4096. and/or if mem2 depends on reg2)
  4097. to:
  4098. mov mem1, reg1
  4099. mov reg1, mem2
  4100. mov reg1, reg2
  4101. }
  4102. begin
  4103. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  4104. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  4105. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  4106. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  4107. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4108. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4109. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4110. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  4111. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  4112. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4113. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  4114. end
  4115. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  4116. begin
  4117. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  4118. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4119. end
  4120. else
  4121. begin
  4122. RemoveInstruction(hp2);
  4123. end
  4124. {$endif i386}
  4125. ;
  4126. end;
  4127. end
  4128. { movl [mem1],reg1
  4129. movl [mem1],reg2
  4130. to
  4131. movl [mem1],reg1
  4132. movl reg1,reg2
  4133. }
  4134. else if not CheckMovMov2MovMov2(p, hp1) and
  4135. { movl const1,[mem1]
  4136. movl [mem1],reg1
  4137. to
  4138. movl const1,reg1
  4139. movl reg1,[mem1]
  4140. }
  4141. MatchOpType(Taicpu(p),top_const,top_ref) and
  4142. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  4143. (taicpu(p).opsize = taicpu(hp1).opsize) and
  4144. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  4145. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  4146. begin
  4147. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  4148. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  4149. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  4150. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  4151. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  4152. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  4153. Result:=true;
  4154. exit;
  4155. end;
  4156. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  4157. end;
  4158. { search further than the next instruction for a mov (as long as it's not a jump) }
  4159. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4160. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4161. (taicpu(p).oper[1]^.typ = top_reg) and
  4162. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4163. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4164. begin
  4165. { we work with hp2 here, so hp1 can be still used later on when
  4166. checking for GetNextInstruction_p }
  4167. hp3 := hp1;
  4168. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4169. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4170. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4171. TransferUsedRegs(TmpUsedRegs);
  4172. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4173. if NotFirstIteration then
  4174. JumpTracking := TLinkedList.Create
  4175. else
  4176. JumpTracking := nil;
  4177. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4178. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4179. (hp2.typ=ait_instruction) do
  4180. begin
  4181. case taicpu(hp2).opcode of
  4182. A_POP:
  4183. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4184. begin
  4185. if not CrossJump and
  4186. not RegUsedBetween(p_TargetReg, p, hp2) then
  4187. begin
  4188. { We can remove the original MOV since the register
  4189. wasn't used between it and its popping from the stack }
  4190. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4191. RemoveCurrentp(p, hp1);
  4192. Result := True;
  4193. JumpTracking.Free;
  4194. Exit;
  4195. end;
  4196. { Can't go any further }
  4197. Break;
  4198. end;
  4199. A_MOV:
  4200. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4201. ((taicpu(p).oper[0]^.typ=top_const) or
  4202. ((taicpu(p).oper[0]^.typ=top_reg) and
  4203. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4204. )
  4205. ) then
  4206. begin
  4207. { we have
  4208. mov x, %treg
  4209. mov %treg, y
  4210. }
  4211. { We don't need to call UpdateUsedRegs for every instruction between
  4212. p and hp2 because the register we're concerned about will not
  4213. become deallocated (otherwise GetNextInstructionUsingReg would
  4214. have stopped at an earlier instruction). [Kit] }
  4215. TempRegUsed :=
  4216. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4217. RegReadByInstruction(p_TargetReg, hp3) or
  4218. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4219. case taicpu(p).oper[0]^.typ Of
  4220. top_reg:
  4221. begin
  4222. { change
  4223. mov %reg, %treg
  4224. mov %treg, y
  4225. to
  4226. mov %reg, y
  4227. }
  4228. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4229. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4230. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4231. begin
  4232. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4233. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4234. if TempRegUsed then
  4235. begin
  4236. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4237. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4238. { Set the start of the next GetNextInstructionUsingRegCond search
  4239. to start at the entry right before hp2 (which is about to be removed) }
  4240. hp3 := tai(hp2.Previous);
  4241. RemoveInstruction(hp2);
  4242. Include(OptsToCheck, aoc_ForceNewIteration);
  4243. { See if there's more we can optimise }
  4244. Continue;
  4245. end
  4246. else
  4247. begin
  4248. RemoveInstruction(hp2);
  4249. { We can remove the original MOV too }
  4250. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4251. RemoveCurrentP(p, hp1);
  4252. Result:=true;
  4253. JumpTracking.Free;
  4254. Exit;
  4255. end;
  4256. end
  4257. else
  4258. begin
  4259. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4260. taicpu(hp2).loadReg(0, p_SourceReg);
  4261. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4262. { Check to see if the register also appears in the reference }
  4263. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4264. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4265. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4266. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4267. begin
  4268. { Don't remove the first instruction if the temporary register is in use }
  4269. if not TempRegUsed then
  4270. begin
  4271. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4272. RemoveCurrentP(p, hp1);
  4273. Result:=true;
  4274. JumpTracking.Free;
  4275. Exit;
  4276. end;
  4277. { No need to set Result to True here. If there's another instruction later
  4278. on that can be optimised, it will be detected when the main Pass 1 loop
  4279. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4280. hp3 := hp2;
  4281. Continue;
  4282. end;
  4283. end;
  4284. end;
  4285. top_const:
  4286. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4287. begin
  4288. { change
  4289. mov const, %treg
  4290. mov %treg, y
  4291. to
  4292. mov const, y
  4293. }
  4294. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4295. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4296. begin
  4297. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4298. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4299. if TempRegUsed then
  4300. begin
  4301. { Don't remove the first instruction if the temporary register is in use }
  4302. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4303. { No need to set Result to True. If there's another instruction later on
  4304. that can be optimised, it will be detected when the main Pass 1 loop
  4305. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4306. end
  4307. else
  4308. begin
  4309. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4310. RemoveCurrentP(p, hp1);
  4311. Result:=true;
  4312. Exit;
  4313. end;
  4314. end;
  4315. end;
  4316. else
  4317. Internalerror(2019103001);
  4318. end;
  4319. end
  4320. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4321. begin
  4322. if not CrossJump and
  4323. not RegUsedBetween(p_TargetReg, p, hp2) and
  4324. not RegReadByInstruction(p_TargetReg, hp2) then
  4325. begin
  4326. { Register is not used before it is overwritten }
  4327. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4328. RemoveCurrentp(p, hp1);
  4329. Result := True;
  4330. Exit;
  4331. end;
  4332. if (taicpu(p).oper[0]^.typ = top_const) and
  4333. (taicpu(hp2).oper[0]^.typ = top_const) then
  4334. begin
  4335. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4336. begin
  4337. { Same value - register hasn't changed }
  4338. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4339. RemoveInstruction(hp2);
  4340. Include(OptsToCheck, aoc_ForceNewIteration);
  4341. { See if there's more we can optimise }
  4342. Continue;
  4343. end;
  4344. end;
  4345. {$ifdef x86_64}
  4346. end
  4347. { Change:
  4348. movl %reg1l,%reg2l
  4349. ...
  4350. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4351. To:
  4352. movl %reg1l,%reg2l
  4353. ...
  4354. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4355. If %reg1 = %reg3, convert to:
  4356. movl %reg1l,%reg2l
  4357. ...
  4358. andl %reg1l,%reg1l
  4359. }
  4360. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4361. (taicpu(p).oper[0]^.typ = top_reg) and
  4362. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4363. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4364. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4365. begin
  4366. TempRegUsed :=
  4367. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4368. RegReadByInstruction(p_TargetReg, hp3) or
  4369. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4370. taicpu(hp2).opsize := S_L;
  4371. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4372. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4373. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4374. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4375. begin
  4376. { %reg1 = %reg3 }
  4377. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4378. taicpu(hp2).opcode := A_AND;
  4379. end
  4380. else
  4381. begin
  4382. { %reg1 <> %reg3 }
  4383. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4384. end;
  4385. if not TempRegUsed then
  4386. begin
  4387. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4388. RemoveCurrentP(p, hp1);
  4389. Result := True;
  4390. Exit;
  4391. end
  4392. else
  4393. begin
  4394. { Initial instruction wasn't actually changed }
  4395. Include(OptsToCheck, aoc_ForceNewIteration);
  4396. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4397. appears below since %reg1 has technically changed }
  4398. if taicpu(hp2).opcode = A_AND then
  4399. Break;
  4400. end;
  4401. {$endif x86_64}
  4402. end
  4403. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4404. GetNextInstruction(hp2, hp4) and
  4405. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4406. { Optimise the following first:
  4407. movl [mem1],reg1
  4408. movl [mem1],reg2
  4409. to
  4410. movl [mem1],reg1
  4411. movl reg1,reg2
  4412. If [mem1] contains the target register and reg1 is the
  4413. the source register, this optimisation will get missed
  4414. and produce less efficient code later on.
  4415. }
  4416. if CheckMovMov2MovMov2(hp2, hp4) then
  4417. { Initial instruction wasn't actually changed }
  4418. Include(OptsToCheck, aoc_ForceNewIteration);
  4419. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4420. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4421. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4422. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4423. begin
  4424. {
  4425. Change from:
  4426. mov ###, %reg
  4427. ...
  4428. movs/z %reg,%reg (Same register, just different sizes)
  4429. To:
  4430. movs/z ###, %reg (Longer version)
  4431. ...
  4432. (remove)
  4433. }
  4434. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4435. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4436. { Keep the first instruction as mov if ### is a constant }
  4437. if taicpu(p).oper[0]^.typ = top_const then
  4438. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4439. else
  4440. begin
  4441. taicpu(p).opcode := taicpu(hp2).opcode;
  4442. taicpu(p).opsize := taicpu(hp2).opsize;
  4443. end;
  4444. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4445. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4446. RemoveInstruction(hp2);
  4447. Result := True;
  4448. JumpTracking.Free;
  4449. Exit;
  4450. end;
  4451. else
  4452. { Move down to the if-block below };
  4453. end;
  4454. { Also catches MOV/S/Z instructions that aren't modified }
  4455. if taicpu(p).oper[0]^.typ = top_reg then
  4456. begin
  4457. p_SourceReg := taicpu(p).oper[0]^.reg;
  4458. if
  4459. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4460. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4461. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4462. begin
  4463. Result := True;
  4464. { Just in case something didn't get modified (e.g. an
  4465. implicit register). Also, if it does read from this
  4466. register, then there's no longer an advantage to
  4467. changing the register on subsequent instructions.}
  4468. if not RegReadByInstruction(p_TargetReg, hp2) then
  4469. begin
  4470. { If a conditional jump was crossed, do not delete
  4471. the original MOV no matter what }
  4472. if not CrossJump and
  4473. { RegEndOfLife returns True if the register is
  4474. deallocated before the next instruction or has
  4475. been loaded with a new value }
  4476. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4477. begin
  4478. { We can remove the original MOV }
  4479. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4480. RemoveCurrentp(p, hp1);
  4481. JumpTracking.Free;
  4482. Result := True;
  4483. Exit;
  4484. end;
  4485. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4486. begin
  4487. { See if there's more we can optimise }
  4488. hp3 := hp2;
  4489. Continue;
  4490. end;
  4491. end;
  4492. end;
  4493. end;
  4494. { Break out of the while loop under normal circumstances }
  4495. Break;
  4496. end;
  4497. JumpTracking.Free;
  4498. end;
  4499. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4500. (taicpu(p).oper[1]^.typ = top_reg) and
  4501. (taicpu(p).opsize = S_L) and
  4502. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4503. (hp2.typ = ait_instruction) and
  4504. (taicpu(hp2).opcode = A_AND) and
  4505. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4506. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4507. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4508. ) then
  4509. begin
  4510. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4511. begin
  4512. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4513. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4514. begin
  4515. { Optimize out:
  4516. mov x, %reg
  4517. and ffffffffh, %reg
  4518. }
  4519. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4520. RemoveInstruction(hp2);
  4521. Result:=true;
  4522. exit;
  4523. end;
  4524. end;
  4525. end;
  4526. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4527. x >= RetOffset) as it doesn't do anything (it writes either to a
  4528. parameter or to the temporary storage room for the function
  4529. result)
  4530. }
  4531. if IsExitCode(hp1) and
  4532. (taicpu(p).oper[1]^.typ = top_ref) and
  4533. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4534. (
  4535. (
  4536. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4537. not (
  4538. assigned(current_procinfo.procdef.funcretsym) and
  4539. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4540. )
  4541. ) or
  4542. { Also discard writes to the stack that are below the base pointer,
  4543. as this is temporary storage rather than a function result on the
  4544. stack, say. }
  4545. (
  4546. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4547. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4548. )
  4549. ) then
  4550. begin
  4551. RemoveCurrentp(p, hp1);
  4552. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4553. RemoveLastDeallocForFuncRes(p);
  4554. Result:=true;
  4555. exit;
  4556. end;
  4557. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4558. begin
  4559. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4560. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4561. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4562. begin
  4563. { change
  4564. mov reg1, mem1
  4565. test/cmp x, mem1
  4566. to
  4567. mov reg1, mem1
  4568. test/cmp x, reg1
  4569. }
  4570. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4571. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4572. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4573. Result := True;
  4574. Exit;
  4575. end;
  4576. if DoMovCmpMemOpt(p, hp1) then
  4577. begin
  4578. Result := True;
  4579. Exit;
  4580. end;
  4581. end;
  4582. if (taicpu(p).oper[1]^.typ = top_reg) and
  4583. (hp1.typ = ait_instruction) and
  4584. GetNextInstruction(hp1, hp2) and
  4585. MatchInstruction(hp2,A_MOV,[]) and
  4586. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4587. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4588. (
  4589. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4590. {$ifdef x86_64}
  4591. or
  4592. (
  4593. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4594. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4595. )
  4596. {$endif x86_64}
  4597. ) then
  4598. begin
  4599. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4600. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4601. { change movsX/movzX reg/ref, reg2
  4602. add/sub/or/... reg3/$const, reg2
  4603. mov reg2 reg/ref
  4604. dealloc reg2
  4605. to
  4606. add/sub/or/... reg3/$const, reg/ref }
  4607. begin
  4608. TransferUsedRegs(TmpUsedRegs);
  4609. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4610. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4611. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4612. begin
  4613. { by example:
  4614. movswl %si,%eax movswl %si,%eax p
  4615. decl %eax addl %edx,%eax hp1
  4616. movw %ax,%si movw %ax,%si hp2
  4617. ->
  4618. movswl %si,%eax movswl %si,%eax p
  4619. decw %eax addw %edx,%eax hp1
  4620. movw %ax,%si movw %ax,%si hp2
  4621. }
  4622. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4623. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4624. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4625. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4626. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4627. {
  4628. ->
  4629. movswl %si,%eax movswl %si,%eax p
  4630. decw %si addw %dx,%si hp1
  4631. movw %ax,%si movw %ax,%si hp2
  4632. }
  4633. case taicpu(hp1).ops of
  4634. 1:
  4635. begin
  4636. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4637. if taicpu(hp1).oper[0]^.typ=top_reg then
  4638. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4639. end;
  4640. 2:
  4641. begin
  4642. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4643. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4644. (taicpu(hp1).opcode<>A_SHL) and
  4645. (taicpu(hp1).opcode<>A_SHR) and
  4646. (taicpu(hp1).opcode<>A_SAR) then
  4647. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4648. end;
  4649. else
  4650. internalerror(2008042701);
  4651. end;
  4652. {
  4653. ->
  4654. decw %si addw %dx,%si p
  4655. }
  4656. RemoveInstruction(hp2);
  4657. RemoveCurrentP(p, hp1);
  4658. Result:=True;
  4659. Exit;
  4660. end;
  4661. end;
  4662. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4663. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4664. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4665. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4666. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4667. )
  4668. {$ifdef i386}
  4669. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4670. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4671. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4672. {$endif i386}
  4673. then
  4674. { change movsX/movzX reg/ref, reg2
  4675. add/sub/or/... regX/$const, reg2
  4676. mov reg2, reg3
  4677. dealloc reg2
  4678. to
  4679. movsX/movzX reg/ref, reg3
  4680. add/sub/or/... reg3/$const, reg3
  4681. }
  4682. begin
  4683. TransferUsedRegs(TmpUsedRegs);
  4684. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4685. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4686. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4687. begin
  4688. { by example:
  4689. movswl %si,%eax movswl %si,%eax p
  4690. decl %eax addl %edx,%eax hp1
  4691. movw %ax,%si movw %ax,%si hp2
  4692. ->
  4693. movswl %si,%eax movswl %si,%eax p
  4694. decw %eax addw %edx,%eax hp1
  4695. movw %ax,%si movw %ax,%si hp2
  4696. }
  4697. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4698. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4699. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4700. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4701. { limit size of constants as well to avoid assembler errors, but
  4702. check opsize to avoid overflow when left shifting the 1 }
  4703. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4704. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4705. {$ifdef x86_64}
  4706. { Be careful of, for example:
  4707. movl %reg1,%reg2
  4708. addl %reg3,%reg2
  4709. movq %reg2,%reg4
  4710. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4711. }
  4712. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4713. begin
  4714. taicpu(hp2).changeopsize(S_L);
  4715. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4716. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4717. end;
  4718. {$endif x86_64}
  4719. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4720. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4721. if taicpu(p).oper[0]^.typ=top_reg then
  4722. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4723. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4724. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4725. {
  4726. ->
  4727. movswl %si,%eax movswl %si,%eax p
  4728. decw %si addw %dx,%si hp1
  4729. movw %ax,%si movw %ax,%si hp2
  4730. }
  4731. case taicpu(hp1).ops of
  4732. 1:
  4733. begin
  4734. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4735. if taicpu(hp1).oper[0]^.typ=top_reg then
  4736. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4737. end;
  4738. 2:
  4739. begin
  4740. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4741. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4742. (taicpu(hp1).opcode<>A_SHL) and
  4743. (taicpu(hp1).opcode<>A_SHR) and
  4744. (taicpu(hp1).opcode<>A_SAR) then
  4745. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4746. end;
  4747. else
  4748. internalerror(2018111801);
  4749. end;
  4750. {
  4751. ->
  4752. decw %si addw %dx,%si p
  4753. }
  4754. RemoveInstruction(hp2);
  4755. end;
  4756. end;
  4757. end;
  4758. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4759. GetNextInstruction(hp1, hp2) and
  4760. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4761. MatchOperand(Taicpu(p).oper[0]^,0) and
  4762. (Taicpu(p).oper[1]^.typ = top_reg) and
  4763. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4764. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4765. { mov reg1,0
  4766. bts reg1,operand1 --> mov reg1,operand2
  4767. or reg1,operand2 bts reg1,operand1}
  4768. begin
  4769. Taicpu(hp2).opcode:=A_MOV;
  4770. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4771. asml.remove(hp1);
  4772. insertllitem(hp2,hp2.next,hp1);
  4773. RemoveCurrentp(p, hp1);
  4774. Result:=true;
  4775. exit;
  4776. end;
  4777. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4778. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4779. GetNextInstruction(hp1, hp2) and
  4780. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4781. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4782. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4783. { change
  4784. mov reg1,reg2
  4785. sub reg3,reg2
  4786. cmp reg3,reg1
  4787. into
  4788. mov reg1,reg2
  4789. sub reg3,reg2
  4790. }
  4791. begin
  4792. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4793. RemoveInstruction(hp2);
  4794. Result:=true;
  4795. exit;
  4796. end;
  4797. {
  4798. mov ref,reg0
  4799. <op> reg0,reg1
  4800. dealloc reg0
  4801. to
  4802. <op> ref,reg1
  4803. }
  4804. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4805. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4806. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4807. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4808. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4809. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4810. begin
  4811. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4812. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4813. RemoveCurrentp(p, hp1);
  4814. Result:=true;
  4815. exit;
  4816. end;
  4817. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4818. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4819. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4820. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4821. begin
  4822. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4823. {$ifdef x86_64}
  4824. { Convert:
  4825. movq x(ref),%reg64
  4826. shrq y,%reg64
  4827. To:
  4828. movl x+4(ref),%reg32
  4829. shrl y-32,%reg32 (Remove if y = 32)
  4830. }
  4831. if (taicpu(p).opsize = S_Q) and
  4832. (taicpu(hp1).opcode = A_SHR) and
  4833. (taicpu(hp1).oper[0]^.val >= 32) then
  4834. begin
  4835. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4836. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4837. { Convert to 32-bit }
  4838. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4839. taicpu(p).opsize := S_L;
  4840. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4841. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4842. if (taicpu(hp1).oper[0]^.val = 32) then
  4843. begin
  4844. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4845. RemoveInstruction(hp1);
  4846. end
  4847. else
  4848. begin
  4849. { This will potentially open up more arithmetic operations since
  4850. the peephole optimizer now has a big hint that only the lower
  4851. 32 bits are currently in use (and opcodes are smaller in size) }
  4852. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4853. taicpu(hp1).opsize := S_L;
  4854. Dec(taicpu(hp1).oper[0]^.val, 32);
  4855. DebugMsg(SPeepholeOptimization + PreMessage +
  4856. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4857. end;
  4858. Result := True;
  4859. Exit;
  4860. end;
  4861. {$endif x86_64}
  4862. { Convert:
  4863. movl x(ref),%reg
  4864. shrl $24,%reg
  4865. To:
  4866. movzbl x+3(ref),%reg
  4867. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4868. Also accept sar instead of shr, but convert to movsx instead of movzx
  4869. }
  4870. if taicpu(hp1).opcode = A_SHR then
  4871. MovUnaligned := A_MOVZX
  4872. else
  4873. MovUnaligned := A_MOVSX;
  4874. NewSize := S_NO;
  4875. NewOffset := 0;
  4876. case taicpu(p).opsize of
  4877. S_B:
  4878. { No valid combinations };
  4879. S_W:
  4880. if (taicpu(hp1).oper[0]^.val = 8) then
  4881. begin
  4882. NewSize := S_BW;
  4883. NewOffset := 1;
  4884. end;
  4885. S_L:
  4886. case taicpu(hp1).oper[0]^.val of
  4887. 16:
  4888. begin
  4889. NewSize := S_WL;
  4890. NewOffset := 2;
  4891. end;
  4892. 24:
  4893. begin
  4894. NewSize := S_BL;
  4895. NewOffset := 3;
  4896. end;
  4897. else
  4898. ;
  4899. end;
  4900. {$ifdef x86_64}
  4901. S_Q:
  4902. case taicpu(hp1).oper[0]^.val of
  4903. 32:
  4904. begin
  4905. if taicpu(hp1).opcode = A_SAR then
  4906. begin
  4907. { 32-bit to 64-bit is a distinct instruction }
  4908. MovUnaligned := A_MOVSXD;
  4909. NewSize := S_LQ;
  4910. NewOffset := 4;
  4911. end
  4912. else
  4913. { Should have been handled by MovShr2Mov above }
  4914. InternalError(2022081811);
  4915. end;
  4916. 48:
  4917. begin
  4918. NewSize := S_WQ;
  4919. NewOffset := 6;
  4920. end;
  4921. 56:
  4922. begin
  4923. NewSize := S_BQ;
  4924. NewOffset := 7;
  4925. end;
  4926. else
  4927. ;
  4928. end;
  4929. {$endif x86_64}
  4930. else
  4931. InternalError(2022081810);
  4932. end;
  4933. if (NewSize <> S_NO) and
  4934. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4935. begin
  4936. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4937. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4938. debug_op2str(MovUnaligned);
  4939. {$ifdef x86_64}
  4940. if MovUnaligned <> A_MOVSXD then
  4941. { Don't add size suffix for MOVSXD }
  4942. {$endif x86_64}
  4943. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4944. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4945. taicpu(p).opcode := MovUnaligned;
  4946. taicpu(p).opsize := NewSize;
  4947. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4948. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4949. RemoveInstruction(hp1);
  4950. Result := True;
  4951. Exit;
  4952. end;
  4953. end;
  4954. { Backward optimisation shared with OptPass2MOV }
  4955. if FuncMov2Func(p, hp1) then
  4956. begin
  4957. Result := True;
  4958. Exit;
  4959. end;
  4960. end;
  4961. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4962. var
  4963. hp1 : tai;
  4964. begin
  4965. Result:=false;
  4966. if taicpu(p).ops <> 2 then
  4967. exit;
  4968. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4969. GetNextInstruction(p,hp1) then
  4970. begin
  4971. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4972. (taicpu(hp1).ops = 2) then
  4973. begin
  4974. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4975. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4976. { movXX reg1, mem1 or movXX mem1, reg1
  4977. movXX mem2, reg2 movXX reg2, mem2}
  4978. begin
  4979. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4980. { movXX reg1, mem1 or movXX mem1, reg1
  4981. movXX mem2, reg1 movXX reg2, mem1}
  4982. begin
  4983. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4984. begin
  4985. { Removes the second statement from
  4986. movXX reg1, mem1/reg2
  4987. movXX mem1/reg2, reg1
  4988. }
  4989. if taicpu(p).oper[0]^.typ=top_reg then
  4990. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4991. { Removes the second statement from
  4992. movXX mem1/reg1, reg2
  4993. movXX reg2, mem1/reg1
  4994. }
  4995. if (taicpu(p).oper[1]^.typ=top_reg) and
  4996. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4997. begin
  4998. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4999. RemoveInstruction(hp1);
  5000. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  5001. Result:=true;
  5002. exit;
  5003. end
  5004. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  5005. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  5006. begin
  5007. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  5008. RemoveInstruction(hp1);
  5009. Result:=true;
  5010. exit;
  5011. end;
  5012. end
  5013. end;
  5014. end;
  5015. end;
  5016. end;
  5017. end;
  5018. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  5019. var
  5020. hp1 : tai;
  5021. begin
  5022. result:=false;
  5023. { replace
  5024. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  5025. MovX %mreg2,%mreg1
  5026. dealloc %mreg2
  5027. by
  5028. <Op>X %mreg2,%mreg1
  5029. ?
  5030. }
  5031. if GetNextInstruction(p,hp1) and
  5032. { we mix single and double opperations here because we assume that the compiler
  5033. generates vmovapd only after double operations and vmovaps only after single operations }
  5034. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5035. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5036. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5037. (taicpu(p).oper[0]^.typ=top_reg) then
  5038. begin
  5039. TransferUsedRegs(TmpUsedRegs);
  5040. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5041. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5042. begin
  5043. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5044. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5045. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5046. RemoveInstruction(hp1);
  5047. result:=true;
  5048. end;
  5049. end;
  5050. end;
  5051. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5052. var
  5053. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5054. JumpLabel, JumpLabel_dist: TAsmLabel;
  5055. FirstValue, SecondValue: TCGInt;
  5056. function OptimizeJump(var InputP: tai): Boolean;
  5057. var
  5058. TempBool: Boolean;
  5059. begin
  5060. Result := False;
  5061. TempBool := True;
  5062. if DoJumpOptimizations(InputP, TempBool) or
  5063. not TempBool then
  5064. begin
  5065. Result := True;
  5066. if Assigned(InputP) then
  5067. begin
  5068. { CollapseZeroDistJump will be set to the label or an align
  5069. before it after the jump if it optimises, whether or not
  5070. the label is live or dead }
  5071. if (InputP.typ = ait_align) or
  5072. (
  5073. (InputP.typ = ait_label) and
  5074. not (tai_label(InputP).labsym.is_used)
  5075. ) then
  5076. GetNextInstruction(InputP, InputP);
  5077. end;
  5078. Exit;
  5079. end;
  5080. end;
  5081. begin
  5082. Result := False;
  5083. if (taicpu(p).oper[0]^.typ = top_const) and
  5084. (taicpu(p).oper[0]^.val <> -1) then
  5085. begin
  5086. { Convert unsigned maximum constants to -1 to aid optimisation }
  5087. case taicpu(p).opsize of
  5088. S_B:
  5089. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5090. begin
  5091. taicpu(p).oper[0]^.val := -1;
  5092. Result := True;
  5093. Exit;
  5094. end;
  5095. S_W:
  5096. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5097. begin
  5098. taicpu(p).oper[0]^.val := -1;
  5099. Result := True;
  5100. Exit;
  5101. end;
  5102. S_L:
  5103. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5104. begin
  5105. taicpu(p).oper[0]^.val := -1;
  5106. Result := True;
  5107. Exit;
  5108. end;
  5109. {$ifdef x86_64}
  5110. S_Q:
  5111. { Storing anything greater than $7FFFFFFF is not possible so do
  5112. nothing };
  5113. {$endif x86_64}
  5114. else
  5115. InternalError(2021121001);
  5116. end;
  5117. end;
  5118. if GetNextInstruction(p, hp1) and
  5119. TrySwapMovCmp(p, hp1) then
  5120. begin
  5121. Result := True;
  5122. Exit;
  5123. end;
  5124. p_label := nil;
  5125. JumpLabel := nil;
  5126. if MatchInstruction(hp1, A_Jcc, []) then
  5127. begin
  5128. if OptimizeJump(hp1) then
  5129. begin
  5130. Result := True;
  5131. if Assigned(hp1) then
  5132. begin
  5133. { CollapseZeroDistJump will be set to the label or an align
  5134. before it after the jump if it optimises, whether or not
  5135. the label is live or dead }
  5136. if (hp1.typ = ait_align) or
  5137. (
  5138. (hp1.typ = ait_label) and
  5139. not (tai_label(hp1).labsym.is_used)
  5140. ) then
  5141. GetNextInstruction(hp1, hp1);
  5142. end;
  5143. TransferUsedRegs(TmpUsedRegs);
  5144. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5145. if not Assigned(hp1) or
  5146. (
  5147. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5148. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5149. ) then
  5150. begin
  5151. { No more conditional jumps; conditional statement is no longer required }
  5152. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5153. RemoveCurrentP(p);
  5154. end;
  5155. Exit;
  5156. end;
  5157. if IsJumpToLabel(taicpu(hp1)) then
  5158. begin
  5159. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5160. if Assigned(JumpLabel) then
  5161. p_label := getlabelwithsym(JumpLabel);
  5162. end;
  5163. end;
  5164. { Search for:
  5165. test $x,(reg/ref)
  5166. jne @lbl1
  5167. test $y,(reg/ref) (same register or reference)
  5168. jne @lbl1
  5169. Change to:
  5170. test $(x or y),(reg/ref)
  5171. jne @lbl1
  5172. (Note, this doesn't work with je instead of jne)
  5173. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5174. Also search for:
  5175. test $x,(reg/ref)
  5176. je @lbl1
  5177. ...
  5178. test $y,(reg/ref)
  5179. je/jne @lbl2
  5180. If (x or y) = x, then the second jump is deterministic
  5181. }
  5182. if (
  5183. (
  5184. (taicpu(p).oper[0]^.typ = top_const) or
  5185. (
  5186. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5187. (taicpu(p).oper[0]^.typ = top_reg) and
  5188. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5189. )
  5190. ) and
  5191. MatchInstruction(hp1, A_JCC, [])
  5192. ) then
  5193. begin
  5194. if (taicpu(p).oper[0]^.typ = top_reg) and
  5195. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5196. FirstValue := -1
  5197. else
  5198. FirstValue := taicpu(p).oper[0]^.val;
  5199. { If we have several test/jne's in a row, it might be the case that
  5200. the second label doesn't go to the same location, but the one
  5201. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5202. so accommodate for this with a while loop.
  5203. }
  5204. hp1_last := hp1;
  5205. while (
  5206. (
  5207. (taicpu(p).oper[1]^.typ = top_reg) and
  5208. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5209. ) or GetNextInstruction(hp1_last, p_dist)
  5210. ) and (p_dist.typ = ait_instruction) do
  5211. begin
  5212. if (
  5213. (
  5214. (taicpu(p_dist).opcode = A_TEST) and
  5215. (
  5216. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5217. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5218. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5219. )
  5220. ) or
  5221. (
  5222. { cmp 0,%reg = test %reg,%reg }
  5223. (taicpu(p_dist).opcode = A_CMP) and
  5224. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5225. )
  5226. ) and
  5227. { Make sure the destination operands are actually the same }
  5228. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5229. GetNextInstruction(p_dist, hp1_dist) and
  5230. MatchInstruction(hp1_dist, A_JCC, []) then
  5231. begin
  5232. if OptimizeJump(hp1_dist) then
  5233. begin
  5234. Result := True;
  5235. Exit;
  5236. end;
  5237. if
  5238. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5239. (
  5240. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5241. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5242. ) then
  5243. SecondValue := -1
  5244. else
  5245. SecondValue := taicpu(p_dist).oper[0]^.val;
  5246. { If both of the TEST constants are identical, delete the
  5247. second TEST that is unnecessary (be careful though, just
  5248. in case the flags are modified in between) }
  5249. if (FirstValue = SecondValue) then
  5250. begin
  5251. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5252. begin
  5253. { Since the second jump's condition is a subset of the first, we
  5254. know it will never branch because the first jump dominates it.
  5255. Get it out of the way now rather than wait for the jump
  5256. optimisations for a speed boost. }
  5257. if IsJumpToLabel(taicpu(hp1_dist)) then
  5258. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5259. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5260. RemoveInstruction(hp1_dist);
  5261. Result := True;
  5262. end
  5263. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5264. begin
  5265. { If the inverse of the first condition is a subset of the second,
  5266. the second one will definitely branch if the first one doesn't }
  5267. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5268. { We can remove the TEST instruction too }
  5269. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5270. RemoveInstruction(p_dist);
  5271. MakeUnconditional(taicpu(hp1_dist));
  5272. RemoveDeadCodeAfterJump(hp1_dist);
  5273. { Since the jump is now unconditional, we can't
  5274. continue any further with this particular
  5275. optimisation. The original TEST is still intact
  5276. though, so there might be something else we can
  5277. do }
  5278. Include(OptsToCheck, aoc_ForceNewIteration);
  5279. Break;
  5280. end;
  5281. if Result or
  5282. { If a jump wasn't removed or made unconditional, only
  5283. remove the identical TEST instruction if the flags
  5284. weren't modified }
  5285. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5286. begin
  5287. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5288. RemoveInstruction(p_dist);
  5289. { If the jump was removed or made unconditional, we
  5290. don't need to allocate NR_DEFAULTFLAGS over the
  5291. entire range }
  5292. if not Result then
  5293. begin
  5294. { Mark the flags as 'in use' over the entire range }
  5295. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5296. { Speed gain - continue search from the Jcc instruction }
  5297. hp1_last := hp1_dist;
  5298. { Only the TEST instruction was removed, and the
  5299. original was unchanged, so we can safely do
  5300. another iteration of the while loop }
  5301. Include(OptsToCheck, aoc_ForceNewIteration);
  5302. Continue;
  5303. end;
  5304. Exit;
  5305. end;
  5306. end;
  5307. hp1_last := nil;
  5308. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5309. (
  5310. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5311. { Always adjacent under -O2 and under }
  5312. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5313. (
  5314. GetNextInstruction(hp1, hp1_last) and
  5315. (hp1_last = p_dist)
  5316. )
  5317. ) and
  5318. (
  5319. (
  5320. { Test the following variant:
  5321. test $x,(reg/ref)
  5322. jne @lbl1
  5323. test $y,(reg/ref)
  5324. je @lbl2
  5325. @lbl1:
  5326. Becomes:
  5327. test $(x or y),(reg/ref)
  5328. je @lbl2
  5329. @lbl1: (may become a dead label)
  5330. }
  5331. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5332. GetNextInstruction(hp1_dist, hp1_last) and
  5333. (hp1_last = p_label)
  5334. ) or
  5335. (
  5336. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5337. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5338. then the second jump will never branch, so it can also be
  5339. removed regardless of where it goes }
  5340. (
  5341. (FirstValue = -1) or
  5342. (SecondValue = -1) or
  5343. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5344. )
  5345. )
  5346. ) then
  5347. begin
  5348. { Same jump location... can be a register since nothing's changed }
  5349. { If any of the entries are equivalent to test %reg,%reg, then the
  5350. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5351. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5352. if (hp1_last = p_label) then
  5353. begin
  5354. { Variant }
  5355. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5356. RemoveInstruction(p_dist);
  5357. if Assigned(JumpLabel) then
  5358. JumpLabel.decrefs;
  5359. RemoveInstruction(hp1);
  5360. end
  5361. else
  5362. begin
  5363. { Only remove the second test if no jumps or other conditional instructions follow }
  5364. TransferUsedRegs(TmpUsedRegs);
  5365. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5366. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5367. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5368. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5369. begin
  5370. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5371. RemoveInstruction(p_dist);
  5372. { Remove the first jump, not the second, to keep
  5373. any register deallocations between the second
  5374. TEST/JNE pair in the same place. Aids future
  5375. optimisation. }
  5376. if Assigned(JumpLabel) then
  5377. JumpLabel.decrefs;
  5378. RemoveInstruction(hp1);
  5379. end
  5380. else
  5381. begin
  5382. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5383. if IsJumpToLabel(taicpu(hp1_dist)) then
  5384. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5385. { Remove second jump in this instance }
  5386. RemoveInstruction(hp1_dist);
  5387. end;
  5388. end;
  5389. Result := True;
  5390. Exit;
  5391. end;
  5392. end;
  5393. if { If -O2 and under, it may stop on any old instruction }
  5394. (cs_opt_level3 in current_settings.optimizerswitches) and
  5395. (taicpu(p).oper[1]^.typ = top_reg) and
  5396. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5397. begin
  5398. hp1_last := p_dist;
  5399. Continue;
  5400. end;
  5401. Break;
  5402. end;
  5403. end;
  5404. { Search for:
  5405. test %reg,%reg
  5406. j(c1) @lbl1
  5407. ...
  5408. @lbl:
  5409. test %reg,%reg (same register)
  5410. j(c2) @lbl2
  5411. If c2 is a subset of c1, change to:
  5412. test %reg,%reg
  5413. j(c1) @lbl2
  5414. (@lbl1 may become a dead label as a result)
  5415. }
  5416. if (taicpu(p).oper[1]^.typ = top_reg) and
  5417. (taicpu(p).oper[0]^.typ = top_reg) and
  5418. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5419. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5420. Assigned(p_label) and
  5421. GetNextInstruction(p_label, p_dist) and
  5422. MatchInstruction(p_dist, A_TEST, []) and
  5423. { It's fine if the second test uses smaller sub-registers }
  5424. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5425. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5426. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5427. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5428. GetNextInstruction(p_dist, hp1_dist) and
  5429. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5430. begin
  5431. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5432. if JumpLabel = JumpLabel_dist then
  5433. { This is an infinite loop }
  5434. Exit;
  5435. { Best optimisation when the first condition is a subset (or equal) of the second }
  5436. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5437. begin
  5438. { Any registers used here will already be allocated }
  5439. if Assigned(JumpLabel) then
  5440. JumpLabel.DecRefs;
  5441. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5442. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5443. Result := True;
  5444. Exit;
  5445. end;
  5446. end;
  5447. end;
  5448. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5449. var
  5450. hp1, hp2: tai;
  5451. ActiveReg: TRegister;
  5452. OldOffset: asizeint;
  5453. ThisConst: TCGInt;
  5454. function RegDeallocated: Boolean;
  5455. begin
  5456. TransferUsedRegs(TmpUsedRegs);
  5457. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5458. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5459. end;
  5460. begin
  5461. result:=false;
  5462. hp1 := nil;
  5463. { replace
  5464. addX const,%reg1
  5465. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5466. dealloc %reg1
  5467. by
  5468. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5469. }
  5470. if MatchOpType(taicpu(p),top_const,top_reg) then
  5471. begin
  5472. ActiveReg := taicpu(p).oper[1]^.reg;
  5473. { Ensures the entire register was updated }
  5474. if (taicpu(p).opsize >= S_L) and
  5475. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5476. MatchInstruction(hp1,A_LEA,[]) and
  5477. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5478. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5479. (
  5480. { Cover the case where the register in the reference is also the destination register }
  5481. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5482. (
  5483. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5484. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5485. RegDeallocated
  5486. )
  5487. ) then
  5488. begin
  5489. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5490. {$push}
  5491. {$R-}{$Q-}
  5492. { Explicitly disable overflow checking for these offset calculation
  5493. as those do not matter for the final result }
  5494. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5495. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5496. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5497. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5498. {$pop}
  5499. {$ifdef x86_64}
  5500. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5501. begin
  5502. { Overflow; abort }
  5503. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5504. end
  5505. else
  5506. {$endif x86_64}
  5507. begin
  5508. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5509. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5510. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5511. RemoveCurrentP(p, hp1)
  5512. else
  5513. RemoveCurrentP(p);
  5514. result:=true;
  5515. Exit;
  5516. end;
  5517. end;
  5518. if (
  5519. { Save calling GetNextInstructionUsingReg again }
  5520. Assigned(hp1) or
  5521. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5522. ) and
  5523. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5524. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5525. begin
  5526. if taicpu(hp1).oper[0]^.typ = top_const then
  5527. begin
  5528. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5529. if taicpu(hp1).opcode = A_ADD then
  5530. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5531. else
  5532. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5533. Result := True;
  5534. { Handle any overflows }
  5535. case taicpu(p).opsize of
  5536. S_B:
  5537. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5538. S_W:
  5539. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5540. S_L:
  5541. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5542. {$ifdef x86_64}
  5543. S_Q:
  5544. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5545. { Overflow; abort }
  5546. Result := False
  5547. else
  5548. taicpu(p).oper[0]^.val := ThisConst;
  5549. {$endif x86_64}
  5550. else
  5551. InternalError(2021102610);
  5552. end;
  5553. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5554. if Result then
  5555. begin
  5556. if (taicpu(p).oper[0]^.val < 0) and
  5557. (
  5558. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5559. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5560. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5561. ) then
  5562. begin
  5563. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5564. taicpu(p).opcode := A_SUB;
  5565. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5566. end
  5567. else
  5568. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5569. RemoveInstruction(hp1);
  5570. end;
  5571. end
  5572. else
  5573. begin
  5574. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5575. TransferUsedRegs(TmpUsedRegs);
  5576. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5577. hp2 := p;
  5578. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5579. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5580. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5581. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5582. begin
  5583. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5584. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5585. Asml.Remove(p);
  5586. Asml.InsertAfter(p, hp1);
  5587. p := hp1;
  5588. Result := True;
  5589. Exit;
  5590. end;
  5591. end;
  5592. end;
  5593. if DoArithCombineOpt(p) then
  5594. Result:=true;
  5595. end;
  5596. end;
  5597. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5598. var
  5599. hp1, hp2: tai;
  5600. ref: Integer;
  5601. saveref: treference;
  5602. offsetcalc: Int64;
  5603. TempReg: TRegister;
  5604. Multiple: TCGInt;
  5605. Adjacent, IntermediateRegDiscarded: Boolean;
  5606. begin
  5607. Result:=false;
  5608. { play save and throw an error if LEA uses a seg register prefix,
  5609. this is most likely an error somewhere else }
  5610. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5611. internalerror(2022022001);
  5612. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5613. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5614. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5615. (
  5616. { do not mess with leas accessing the stack pointer
  5617. unless it's a null operation }
  5618. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5619. (
  5620. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5621. (taicpu(p).oper[0]^.ref^.offset = 0)
  5622. )
  5623. ) and
  5624. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5625. begin
  5626. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5627. begin
  5628. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5629. begin
  5630. taicpu(p).opcode := A_MOV;
  5631. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5632. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5633. end
  5634. else
  5635. begin
  5636. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5637. RemoveCurrentP(p);
  5638. end;
  5639. Result:=true;
  5640. exit;
  5641. end
  5642. else if (
  5643. { continue to use lea to adjust the stack pointer,
  5644. it is the recommended way, but only if not optimizing for size }
  5645. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5646. (cs_opt_size in current_settings.optimizerswitches)
  5647. ) and
  5648. { If the flags register is in use, don't change the instruction
  5649. to an ADD otherwise this will scramble the flags. [Kit] }
  5650. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5651. ConvertLEA(taicpu(p)) then
  5652. begin
  5653. Result:=true;
  5654. exit;
  5655. end;
  5656. end;
  5657. { Don't optimise if the stack or frame pointer is the destination register }
  5658. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5659. Exit;
  5660. if GetNextInstruction(p,hp1) and
  5661. (hp1.typ=ait_instruction) then
  5662. begin
  5663. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5664. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5665. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5666. begin
  5667. TransferUsedRegs(TmpUsedRegs);
  5668. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5669. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5670. begin
  5671. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5672. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5673. RemoveInstruction(hp1);
  5674. result:=true;
  5675. exit;
  5676. end;
  5677. end;
  5678. { changes
  5679. lea <ref1>, reg1
  5680. <op> ...,<ref. with reg1>,...
  5681. to
  5682. <op> ...,<ref1>,... }
  5683. { find a reference which uses reg1 }
  5684. 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
  5685. ref:=0
  5686. 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
  5687. ref:=1
  5688. else
  5689. ref:=-1;
  5690. if (ref<>-1) and
  5691. { reg1 must be either the base or the index }
  5692. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5693. begin
  5694. { reg1 can be removed from the reference }
  5695. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5696. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5697. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5698. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5699. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5700. else
  5701. Internalerror(2019111201);
  5702. { check if the can insert all data of the lea into the second instruction }
  5703. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5704. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5705. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5706. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5707. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5708. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5709. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5710. {$ifdef x86_64}
  5711. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5712. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5713. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5714. )
  5715. {$endif x86_64}
  5716. then
  5717. begin
  5718. { reg1 might not used by the second instruction after it is remove from the reference }
  5719. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5720. begin
  5721. TransferUsedRegs(TmpUsedRegs);
  5722. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5723. { reg1 is not updated so it might not be used afterwards }
  5724. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5725. begin
  5726. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5727. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5728. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5729. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5730. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5731. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5732. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5733. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5734. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5735. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5736. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5737. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5738. RemoveCurrentP(p, hp1);
  5739. result:=true;
  5740. exit;
  5741. end
  5742. end;
  5743. end;
  5744. { recover }
  5745. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5746. end;
  5747. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5748. if Adjacent or
  5749. { Check further ahead (up to 2 instructions ahead for -O2) }
  5750. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5751. begin
  5752. { Check common LEA/LEA conditions }
  5753. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5754. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5755. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5756. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5757. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5758. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5759. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5760. (
  5761. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5762. calling it (since it calls GetNextInstruction) }
  5763. Adjacent or
  5764. (
  5765. (
  5766. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5767. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5768. ) and (
  5769. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5770. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5771. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5772. )
  5773. )
  5774. ) then
  5775. begin
  5776. TransferUsedRegs(TmpUsedRegs);
  5777. hp2 := p;
  5778. repeat
  5779. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5780. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5781. IntermediateRegDiscarded :=
  5782. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5783. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5784. { changes
  5785. lea offset1(regX,scale), reg1
  5786. lea offset2(reg1,reg1), reg2
  5787. to
  5788. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5789. and
  5790. lea offset1(regX,scale1), reg1
  5791. lea offset2(reg1,scale2), reg2
  5792. to
  5793. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5794. and
  5795. lea offset1(regX,scale1), reg1
  5796. lea offset2(reg3,reg1,scale2), reg2
  5797. to
  5798. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5799. ... so long as the final scale does not exceed 8
  5800. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5801. }
  5802. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5803. (
  5804. { Don't optimise if size is a concern and the intermediate register remains in use }
  5805. IntermediateRegDiscarded or
  5806. not (cs_opt_size in current_settings.optimizerswitches)
  5807. ) and
  5808. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5809. (
  5810. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5811. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5812. ) and (
  5813. (
  5814. { lea (reg1,scale2), reg2 variant }
  5815. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5816. (
  5817. Adjacent or
  5818. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5819. ) and
  5820. (
  5821. (
  5822. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5823. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5824. ) or (
  5825. { lea (regX,regX), reg1 variant }
  5826. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5827. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5828. )
  5829. )
  5830. ) or (
  5831. { lea (reg1,reg1), reg1 variant }
  5832. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5833. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5834. )
  5835. ) then
  5836. begin
  5837. { Make everything homogeneous to make calculations easier }
  5838. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5839. begin
  5840. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5841. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5842. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5843. else
  5844. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5845. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5846. end;
  5847. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5848. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5849. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5850. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5851. begin
  5852. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5853. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5854. begin
  5855. { Put the register to change in the index register }
  5856. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5857. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5858. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5859. end;
  5860. { Change lea (reg,reg) to lea(,reg,2) }
  5861. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5862. begin
  5863. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5864. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5865. end;
  5866. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5867. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5868. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5869. { Just to prevent miscalculations }
  5870. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5871. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5872. else
  5873. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5874. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5875. if IntermediateRegDiscarded then
  5876. begin
  5877. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5878. RemoveCurrentP(p);
  5879. end
  5880. else
  5881. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5882. result:=true;
  5883. exit;
  5884. end;
  5885. end;
  5886. { changes
  5887. lea offset1(regX), reg1
  5888. lea offset2(reg1), reg2
  5889. to
  5890. lea offset1+offset2(regX), reg2 }
  5891. if (
  5892. { Don't optimise if size is a concern and the intermediate register remains in use }
  5893. IntermediateRegDiscarded or
  5894. not (cs_opt_size in current_settings.optimizerswitches)
  5895. ) and
  5896. (
  5897. (
  5898. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5899. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5900. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5901. ) or (
  5902. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5903. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5904. (
  5905. (
  5906. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5907. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5908. ) or (
  5909. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5910. (
  5911. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5912. (
  5913. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5914. (
  5915. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5916. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5917. )
  5918. )
  5919. )
  5920. )
  5921. )
  5922. )
  5923. ) then
  5924. begin
  5925. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5926. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5927. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5928. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5929. begin
  5930. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5931. begin
  5932. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5933. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5934. { if the register is used as index and base, we have to increase for base as well
  5935. and adapt base }
  5936. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5937. begin
  5938. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5939. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5940. end;
  5941. end
  5942. else
  5943. begin
  5944. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5945. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5946. end;
  5947. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5948. begin
  5949. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5950. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5951. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  5952. { Catch the situation where the base = index
  5953. and treat this as *2. The scalefactor of
  5954. p will be 0 or 1 due to the conditional
  5955. checks above. Fixes i40647 }
  5956. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  5957. else
  5958. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  5959. end;
  5960. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5961. if IntermediateRegDiscarded then
  5962. begin
  5963. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5964. RemoveCurrentP(p);
  5965. end
  5966. else
  5967. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5968. result:=true;
  5969. exit;
  5970. end;
  5971. end;
  5972. end;
  5973. { Change:
  5974. leal/q $x(%reg1),%reg2
  5975. ...
  5976. shll/q $y,%reg2
  5977. To:
  5978. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5979. }
  5980. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5981. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5982. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5983. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5984. (taicpu(hp1).oper[0]^.val <= 3) then
  5985. begin
  5986. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5987. TransferUsedRegs(TmpUsedRegs);
  5988. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5989. if
  5990. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5991. (this works even if scalefactor is zero) }
  5992. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5993. { Ensure offset doesn't go out of bounds }
  5994. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5995. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5996. (
  5997. (
  5998. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5999. (
  6000. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6001. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  6002. (
  6003. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  6004. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6005. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6006. )
  6007. )
  6008. ) or (
  6009. (
  6010. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  6011. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  6012. ) and
  6013. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  6014. )
  6015. ) then
  6016. begin
  6017. repeat
  6018. with taicpu(p).oper[0]^.ref^ do
  6019. begin
  6020. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  6021. if index = base then
  6022. begin
  6023. if Multiple > 4 then
  6024. { Optimisation will no longer work because resultant
  6025. scale factor will exceed 8 }
  6026. Break;
  6027. base := NR_NO;
  6028. scalefactor := 2;
  6029. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  6030. end
  6031. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6032. begin
  6033. { Scale factor only works on the index register }
  6034. index := base;
  6035. base := NR_NO;
  6036. end;
  6037. { For safety }
  6038. if scalefactor <= 1 then
  6039. begin
  6040. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6041. scalefactor := Multiple;
  6042. end
  6043. else
  6044. begin
  6045. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6046. scalefactor := scalefactor * Multiple;
  6047. end;
  6048. offset := offset * Multiple;
  6049. end;
  6050. RemoveInstruction(hp1);
  6051. Result := True;
  6052. Exit;
  6053. { This repeat..until loop exists for the benefit of Break }
  6054. until True;
  6055. end;
  6056. end;
  6057. end;
  6058. end;
  6059. end;
  6060. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6061. var
  6062. hp1 : tai;
  6063. SubInstr: Boolean;
  6064. ThisConst: TCGInt;
  6065. const
  6066. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6067. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6068. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6069. begin
  6070. Result := False;
  6071. if taicpu(p).oper[0]^.typ <> top_const then
  6072. { Should have been confirmed before calling }
  6073. InternalError(2021102601);
  6074. SubInstr := (taicpu(p).opcode = A_SUB);
  6075. if GetLastInstruction(p, hp1) and
  6076. (hp1.typ = ait_instruction) and
  6077. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6078. begin
  6079. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6080. { Bad size }
  6081. InternalError(2022042001);
  6082. case taicpu(hp1).opcode Of
  6083. A_INC:
  6084. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6085. begin
  6086. if SubInstr then
  6087. ThisConst := taicpu(p).oper[0]^.val - 1
  6088. else
  6089. ThisConst := taicpu(p).oper[0]^.val + 1;
  6090. end
  6091. else
  6092. Exit;
  6093. A_DEC:
  6094. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6095. begin
  6096. if SubInstr then
  6097. ThisConst := taicpu(p).oper[0]^.val + 1
  6098. else
  6099. ThisConst := taicpu(p).oper[0]^.val - 1;
  6100. end
  6101. else
  6102. Exit;
  6103. A_SUB:
  6104. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6105. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6106. begin
  6107. if SubInstr then
  6108. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6109. else
  6110. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6111. end
  6112. else
  6113. Exit;
  6114. A_ADD:
  6115. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6116. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6117. begin
  6118. if SubInstr then
  6119. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6120. else
  6121. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6122. end
  6123. else
  6124. Exit;
  6125. else
  6126. Exit;
  6127. end;
  6128. { Check that the values are in range }
  6129. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6130. { Overflow; abort }
  6131. Exit;
  6132. if (ThisConst = 0) then
  6133. begin
  6134. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6135. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6136. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6137. RemoveInstruction(hp1);
  6138. hp1 := tai(p.next);
  6139. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6140. if not GetLastInstruction(hp1, p) then
  6141. p := hp1;
  6142. end
  6143. else
  6144. begin
  6145. if taicpu(hp1).opercnt=1 then
  6146. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6147. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6148. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6149. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6150. else
  6151. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6152. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6153. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6154. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6155. RemoveInstruction(hp1);
  6156. taicpu(p).loadconst(0, ThisConst);
  6157. end;
  6158. Result := True;
  6159. end;
  6160. end;
  6161. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6162. begin
  6163. Result := False;
  6164. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6165. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6166. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6167. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6168. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6169. (
  6170. (
  6171. (taicpu(hp1).opcode = A_TEST)
  6172. ) or (
  6173. (taicpu(hp1).opcode = A_CMP) and
  6174. { A sanity check more than anything }
  6175. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6176. )
  6177. ) then
  6178. begin
  6179. { change
  6180. mov mem, %reg
  6181. ...
  6182. cmp/test x, %reg / test %reg,%reg
  6183. (reg deallocated)
  6184. to
  6185. cmp/test x, mem / cmp 0, mem
  6186. }
  6187. TransferUsedRegs(TmpUsedRegs);
  6188. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6189. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6190. begin
  6191. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6192. if (taicpu(hp1).opcode = A_TEST) and
  6193. (
  6194. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6195. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6196. ) then
  6197. begin
  6198. taicpu(hp1).opcode := A_CMP;
  6199. taicpu(hp1).loadconst(0, 0);
  6200. end;
  6201. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6202. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6203. RemoveCurrentP(p);
  6204. if (p <> hp1) then
  6205. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6206. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6207. { Make sure the flags are allocated across the CMP instruction }
  6208. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6209. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6210. Result := True;
  6211. Exit;
  6212. end;
  6213. end;
  6214. end;
  6215. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6216. var
  6217. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6218. ThisReg, SecondReg: TRegister;
  6219. JumpLoc: TAsmLabel;
  6220. NewSize: TOpSize;
  6221. begin
  6222. Result := False;
  6223. {
  6224. Convert:
  6225. j<c> .L1
  6226. .L2:
  6227. mov 1,reg
  6228. jmp .L3 (or ret, although it might not be a RET yet)
  6229. .L1:
  6230. mov 0,reg
  6231. jmp .L3 (or ret)
  6232. ( As long as .L3 <> .L1 or .L2)
  6233. To:
  6234. mov 0,reg
  6235. set<not(c)> reg
  6236. jmp .L3 (or ret)
  6237. .L2:
  6238. mov 1,reg
  6239. jmp .L3 (or ret)
  6240. .L1:
  6241. mov 0,reg
  6242. jmp .L3 (or ret)
  6243. }
  6244. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6245. Exit;
  6246. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6247. if GetNextInstruction(hp_label, hp2) and
  6248. MatchInstruction(hp2,A_MOV,[]) and
  6249. (taicpu(hp2).oper[0]^.typ = top_const) and
  6250. (
  6251. (
  6252. (taicpu(hp2).oper[1]^.typ = top_reg)
  6253. {$ifdef i386}
  6254. { Under i386, ESI, EDI, EBP and ESP
  6255. don't have an 8-bit representation }
  6256. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6257. {$endif i386}
  6258. ) or (
  6259. {$ifdef i386}
  6260. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6261. {$endif i386}
  6262. (taicpu(hp2).opsize = S_B)
  6263. )
  6264. ) and
  6265. GetNextInstruction(hp2, hp3) and
  6266. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6267. (
  6268. (taicpu(hp3).opcode=A_RET) or
  6269. (
  6270. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6271. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6272. )
  6273. ) and
  6274. GetNextInstruction(hp3, hp4) and
  6275. (hp4.typ=ait_label) and
  6276. (tai_label(hp4).labsym=JumpLoc) and
  6277. (
  6278. not (cs_opt_size in current_settings.optimizerswitches) or
  6279. { If the initial jump is the label's only reference, then it will
  6280. become a dead label if the other conditions are met and hence
  6281. remove at least 2 instructions, including a jump }
  6282. (JumpLoc.getrefs = 1)
  6283. ) and
  6284. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6285. that will be optimised out }
  6286. GetNextInstruction(hp4, hp5) and
  6287. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6288. (taicpu(hp5).oper[0]^.typ = top_const) and
  6289. (
  6290. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6291. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6292. ) and
  6293. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6294. GetNextInstruction(hp5,hp6) and
  6295. (
  6296. (hp6.typ<>ait_label) or
  6297. SkipLabels(hp6, hp6)
  6298. ) and
  6299. (hp6.typ=ait_instruction) then
  6300. begin
  6301. { First, let's look at the two jumps that are hp3 and hp6 }
  6302. if not
  6303. (
  6304. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6305. (
  6306. (taicpu(hp6).opcode=A_RET) or
  6307. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6308. )
  6309. ) then
  6310. { If condition is False, then the JMP/RET instructions matched conventionally }
  6311. begin
  6312. { See if one of the jumps can be instantly converted into a RET }
  6313. if (taicpu(hp3).opcode=A_JMP) then
  6314. begin
  6315. { Reuse hp5 }
  6316. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6317. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6318. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6319. Exit;
  6320. if MatchInstruction(hp5, A_RET, []) then
  6321. begin
  6322. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6323. ConvertJumpToRET(hp3, hp5);
  6324. Result := True;
  6325. end
  6326. else
  6327. Exit;
  6328. end;
  6329. if (taicpu(hp6).opcode=A_JMP) then
  6330. begin
  6331. { Reuse hp5 }
  6332. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6333. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6334. Exit;
  6335. if MatchInstruction(hp5, A_RET, []) then
  6336. begin
  6337. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6338. ConvertJumpToRET(hp6, hp5);
  6339. Result := True;
  6340. end
  6341. else
  6342. Exit;
  6343. end;
  6344. if not
  6345. (
  6346. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6347. (
  6348. (taicpu(hp6).opcode=A_RET) or
  6349. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6350. )
  6351. ) then
  6352. { Still doesn't match }
  6353. Exit;
  6354. end;
  6355. if (taicpu(hp2).oper[0]^.val = 1) then
  6356. begin
  6357. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6358. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6359. end
  6360. else
  6361. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6362. if taicpu(hp2).opsize=S_B then
  6363. begin
  6364. if taicpu(hp2).oper[1]^.typ = top_reg then
  6365. begin
  6366. SecondReg := taicpu(hp2).oper[1]^.reg;
  6367. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6368. end
  6369. else
  6370. begin
  6371. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6372. SecondReg := NR_NO;
  6373. end;
  6374. hp_pos := p;
  6375. hp_allocstart := hp4;
  6376. end
  6377. else
  6378. begin
  6379. { Will be a register because the size can't be S_B otherwise }
  6380. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6381. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6382. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6383. if (cs_opt_size in current_settings.optimizerswitches) then
  6384. begin
  6385. { Favour using MOVZX when optimising for size }
  6386. case taicpu(hp2).opsize of
  6387. S_W:
  6388. NewSize := S_BW;
  6389. S_L:
  6390. NewSize := S_BL;
  6391. {$ifdef x86_64}
  6392. S_Q:
  6393. begin
  6394. NewSize := S_BL;
  6395. { Will implicitly zero-extend to 64-bit }
  6396. setsubreg(SecondReg, R_SUBD);
  6397. end;
  6398. {$endif x86_64}
  6399. else
  6400. InternalError(2022101301);
  6401. end;
  6402. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6403. { Inserting it right before p will guarantee that the flags are also tracked }
  6404. Asml.InsertBefore(hp5, p);
  6405. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6406. hp_pos := hp5;
  6407. hp_allocstart := hp4;
  6408. end
  6409. else
  6410. begin
  6411. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6412. { Inserting it right before p will guarantee that the flags are also tracked }
  6413. Asml.InsertBefore(hp5, p);
  6414. hp_pos := p;
  6415. hp_allocstart := hp5;
  6416. end;
  6417. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6418. end;
  6419. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6420. taicpu(hp4).condition := taicpu(p).condition;
  6421. asml.InsertBefore(hp4, hp_pos);
  6422. if taicpu(hp3).is_jmp then
  6423. begin
  6424. JumpLoc.decrefs;
  6425. MakeUnconditional(taicpu(p));
  6426. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6427. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6428. end
  6429. else
  6430. ConvertJumpToRET(p, hp3);
  6431. if SecondReg <> NR_NO then
  6432. { Ensure the destination register is allocated over this region }
  6433. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6434. if (JumpLoc.getrefs = 0) then
  6435. RemoveDeadCodeAfterJump(hp3);
  6436. Result:=true;
  6437. exit;
  6438. end;
  6439. end;
  6440. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6441. var
  6442. hp1, hp2: tai;
  6443. ActiveReg: TRegister;
  6444. OldOffset: asizeint;
  6445. ThisConst: TCGInt;
  6446. function RegDeallocated: Boolean;
  6447. begin
  6448. TransferUsedRegs(TmpUsedRegs);
  6449. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6450. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6451. end;
  6452. begin
  6453. Result:=false;
  6454. hp1 := nil;
  6455. { replace
  6456. subX const,%reg1
  6457. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6458. dealloc %reg1
  6459. by
  6460. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6461. }
  6462. if MatchOpType(taicpu(p),top_const,top_reg) then
  6463. begin
  6464. ActiveReg := taicpu(p).oper[1]^.reg;
  6465. { Ensures the entire register was updated }
  6466. if (taicpu(p).opsize >= S_L) and
  6467. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6468. MatchInstruction(hp1,A_LEA,[]) and
  6469. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6470. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6471. (
  6472. { Cover the case where the register in the reference is also the destination register }
  6473. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6474. (
  6475. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6476. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6477. RegDeallocated
  6478. )
  6479. ) then
  6480. begin
  6481. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6482. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6483. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6484. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6485. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6486. {$ifdef x86_64}
  6487. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6488. begin
  6489. { Overflow; abort }
  6490. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6491. end
  6492. else
  6493. {$endif x86_64}
  6494. begin
  6495. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6496. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6497. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6498. RemoveCurrentP(p, hp1)
  6499. else
  6500. RemoveCurrentP(p);
  6501. result:=true;
  6502. Exit;
  6503. end;
  6504. end;
  6505. if (
  6506. { Save calling GetNextInstructionUsingReg again }
  6507. Assigned(hp1) or
  6508. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6509. ) and
  6510. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6511. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6512. begin
  6513. if taicpu(hp1).oper[0]^.typ = top_const then
  6514. begin
  6515. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6516. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6517. Result := True;
  6518. { Handle any overflows }
  6519. case taicpu(p).opsize of
  6520. S_B:
  6521. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6522. S_W:
  6523. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6524. S_L:
  6525. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6526. {$ifdef x86_64}
  6527. S_Q:
  6528. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6529. { Overflow; abort }
  6530. Result := False
  6531. else
  6532. taicpu(p).oper[0]^.val := ThisConst;
  6533. {$endif x86_64}
  6534. else
  6535. InternalError(2021102611);
  6536. end;
  6537. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6538. if Result then
  6539. begin
  6540. if (taicpu(p).oper[0]^.val < 0) and
  6541. (
  6542. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6543. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6544. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6545. ) then
  6546. begin
  6547. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6548. taicpu(p).opcode := A_SUB;
  6549. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6550. end
  6551. else
  6552. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6553. RemoveInstruction(hp1);
  6554. end;
  6555. end
  6556. else
  6557. begin
  6558. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6559. TransferUsedRegs(TmpUsedRegs);
  6560. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6561. hp2 := p;
  6562. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6563. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6564. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6565. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6566. begin
  6567. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6568. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6569. Asml.Remove(p);
  6570. Asml.InsertAfter(p, hp1);
  6571. p := hp1;
  6572. Result := True;
  6573. Exit;
  6574. end;
  6575. end;
  6576. end;
  6577. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6578. { * change "sub/add const1, reg" or "dec reg" followed by
  6579. "sub const2, reg" to one "sub ..., reg" }
  6580. {$ifdef i386}
  6581. if (taicpu(p).oper[0]^.val = 2) and
  6582. (ActiveReg = NR_ESP) and
  6583. { Don't do the sub/push optimization if the sub }
  6584. { comes from setting up the stack frame (JM) }
  6585. (not(GetLastInstruction(p,hp1)) or
  6586. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6587. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6588. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6589. begin
  6590. hp1 := tai(p.next);
  6591. while Assigned(hp1) and
  6592. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6593. not RegReadByInstruction(NR_ESP,hp1) and
  6594. not RegModifiedByInstruction(NR_ESP,hp1) do
  6595. hp1 := tai(hp1.next);
  6596. if Assigned(hp1) and
  6597. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6598. begin
  6599. taicpu(hp1).changeopsize(S_L);
  6600. if taicpu(hp1).oper[0]^.typ=top_reg then
  6601. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6602. hp1 := tai(p.next);
  6603. RemoveCurrentp(p, hp1);
  6604. Result:=true;
  6605. exit;
  6606. end;
  6607. end;
  6608. {$endif i386}
  6609. if DoArithCombineOpt(p) then
  6610. Result:=true;
  6611. end;
  6612. end;
  6613. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6614. var
  6615. TmpBool1,TmpBool2 : Boolean;
  6616. tmpref : treference;
  6617. hp1,hp2: tai;
  6618. mask, shiftval: tcgint;
  6619. begin
  6620. Result:=false;
  6621. { All these optimisations work on "shl/sal const,%reg" }
  6622. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6623. Exit;
  6624. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6625. (taicpu(p).oper[0]^.val <= 3) then
  6626. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6627. begin
  6628. { should we check the next instruction? }
  6629. TmpBool1 := True;
  6630. { have we found an add/sub which could be
  6631. integrated in the lea? }
  6632. TmpBool2 := False;
  6633. reference_reset(tmpref,2,[]);
  6634. TmpRef.index := taicpu(p).oper[1]^.reg;
  6635. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6636. while TmpBool1 and
  6637. GetNextInstruction(p, hp1) and
  6638. (tai(hp1).typ = ait_instruction) and
  6639. ((((taicpu(hp1).opcode = A_ADD) or
  6640. (taicpu(hp1).opcode = A_SUB)) and
  6641. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6642. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6643. (((taicpu(hp1).opcode = A_INC) or
  6644. (taicpu(hp1).opcode = A_DEC)) and
  6645. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6646. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6647. ((taicpu(hp1).opcode = A_LEA) and
  6648. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6649. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6650. (not GetNextInstruction(hp1,hp2) or
  6651. not instrReadsFlags(hp2)) Do
  6652. begin
  6653. TmpBool1 := False;
  6654. if taicpu(hp1).opcode=A_LEA then
  6655. begin
  6656. if (TmpRef.base = NR_NO) and
  6657. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6658. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6659. { Segment register isn't a concern here }
  6660. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6661. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6662. begin
  6663. TmpBool1 := True;
  6664. TmpBool2 := True;
  6665. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6666. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6667. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6668. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6669. RemoveInstruction(hp1);
  6670. end
  6671. end
  6672. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6673. begin
  6674. TmpBool1 := True;
  6675. TmpBool2 := True;
  6676. case taicpu(hp1).opcode of
  6677. A_ADD:
  6678. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6679. A_SUB:
  6680. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6681. else
  6682. internalerror(2019050536);
  6683. end;
  6684. RemoveInstruction(hp1);
  6685. end
  6686. else
  6687. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6688. (((taicpu(hp1).opcode = A_ADD) and
  6689. (TmpRef.base = NR_NO)) or
  6690. (taicpu(hp1).opcode = A_INC) or
  6691. (taicpu(hp1).opcode = A_DEC)) then
  6692. begin
  6693. TmpBool1 := True;
  6694. TmpBool2 := True;
  6695. case taicpu(hp1).opcode of
  6696. A_ADD:
  6697. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6698. A_INC:
  6699. inc(TmpRef.offset);
  6700. A_DEC:
  6701. dec(TmpRef.offset);
  6702. else
  6703. internalerror(2019050535);
  6704. end;
  6705. RemoveInstruction(hp1);
  6706. end;
  6707. end;
  6708. if TmpBool2
  6709. {$ifndef x86_64}
  6710. or
  6711. ((current_settings.optimizecputype < cpu_Pentium2) and
  6712. (taicpu(p).oper[0]^.val <= 3) and
  6713. not(cs_opt_size in current_settings.optimizerswitches))
  6714. {$endif x86_64}
  6715. then
  6716. begin
  6717. if not(TmpBool2) and
  6718. (taicpu(p).oper[0]^.val=1) then
  6719. begin
  6720. taicpu(p).opcode := A_ADD;
  6721. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6722. end
  6723. else
  6724. begin
  6725. taicpu(p).opcode := A_LEA;
  6726. taicpu(p).loadref(0, TmpRef);
  6727. end;
  6728. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6729. Result := True;
  6730. end;
  6731. end
  6732. {$ifndef x86_64}
  6733. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6734. begin
  6735. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6736. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6737. (unlike shl, which is only Tairable in the U pipe) }
  6738. if taicpu(p).oper[0]^.val=1 then
  6739. begin
  6740. taicpu(p).opcode := A_ADD;
  6741. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6742. Result := True;
  6743. end
  6744. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6745. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6746. else if (taicpu(p).opsize = S_L) and
  6747. (taicpu(p).oper[0]^.val<= 3) then
  6748. begin
  6749. reference_reset(tmpref,2,[]);
  6750. TmpRef.index := taicpu(p).oper[1]^.reg;
  6751. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6752. taicpu(p).opcode := A_LEA;
  6753. taicpu(p).loadref(0, TmpRef);
  6754. Result := True;
  6755. end;
  6756. end
  6757. {$endif x86_64}
  6758. else if
  6759. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6760. (
  6761. (
  6762. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6763. SetAndTest(hp1, hp2)
  6764. {$ifdef x86_64}
  6765. ) or
  6766. (
  6767. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6768. GetNextInstruction(hp1, hp2) and
  6769. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6770. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6771. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6772. {$endif x86_64}
  6773. )
  6774. ) and
  6775. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6776. begin
  6777. { Change:
  6778. shl x, %reg1
  6779. mov -(1<<x), %reg2
  6780. and %reg2, %reg1
  6781. Or:
  6782. shl x, %reg1
  6783. and -(1<<x), %reg1
  6784. To just:
  6785. shl x, %reg1
  6786. Since the and operation only zeroes bits that are already zero from the shl operation
  6787. }
  6788. case taicpu(p).oper[0]^.val of
  6789. 8:
  6790. mask:=$FFFFFFFFFFFFFF00;
  6791. 16:
  6792. mask:=$FFFFFFFFFFFF0000;
  6793. 32:
  6794. mask:=$FFFFFFFF00000000;
  6795. 63:
  6796. { Constant pre-calculated to prevent overflow errors with Int64 }
  6797. mask:=$8000000000000000;
  6798. else
  6799. begin
  6800. if taicpu(p).oper[0]^.val >= 64 then
  6801. { Shouldn't happen realistically, since the register
  6802. is guaranteed to be set to zero at this point }
  6803. mask := 0
  6804. else
  6805. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6806. end;
  6807. end;
  6808. if taicpu(hp1).oper[0]^.val = mask then
  6809. begin
  6810. { Everything checks out, perform the optimisation, as long as
  6811. the FLAGS register isn't being used}
  6812. TransferUsedRegs(TmpUsedRegs);
  6813. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6814. {$ifdef x86_64}
  6815. if (hp1 <> hp2) then
  6816. begin
  6817. { "shl/mov/and" version }
  6818. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6819. { Don't do the optimisation if the FLAGS register is in use }
  6820. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6821. begin
  6822. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6823. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6824. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6825. begin
  6826. RemoveInstruction(hp1);
  6827. Result := True;
  6828. end;
  6829. { Only set Result to True if the 'mov' instruction was removed }
  6830. RemoveInstruction(hp2);
  6831. end;
  6832. end
  6833. else
  6834. {$endif x86_64}
  6835. begin
  6836. { "shl/and" version }
  6837. { Don't do the optimisation if the FLAGS register is in use }
  6838. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6839. begin
  6840. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6841. RemoveInstruction(hp1);
  6842. Result := True;
  6843. end;
  6844. end;
  6845. Exit;
  6846. end
  6847. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6848. begin
  6849. { Even if the mask doesn't allow for its removal, we might be
  6850. able to optimise the mask for the "shl/and" version, which
  6851. may permit other peephole optimisations }
  6852. {$ifdef DEBUG_AOPTCPU}
  6853. mask := taicpu(hp1).oper[0]^.val and mask;
  6854. if taicpu(hp1).oper[0]^.val <> mask then
  6855. begin
  6856. DebugMsg(
  6857. SPeepholeOptimization +
  6858. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6859. ' to $' + debug_tostr(mask) +
  6860. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6861. taicpu(hp1).oper[0]^.val := mask;
  6862. end;
  6863. {$else DEBUG_AOPTCPU}
  6864. { If debugging is off, just set the operand even if it's the same }
  6865. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6866. {$endif DEBUG_AOPTCPU}
  6867. end;
  6868. end;
  6869. {
  6870. change
  6871. shl/sal const,reg
  6872. <op> ...(...,reg,1),...
  6873. into
  6874. <op> ...(...,reg,1 shl const),...
  6875. if const in 1..3
  6876. }
  6877. if MatchOpType(taicpu(p), top_const, top_reg) and
  6878. (taicpu(p).oper[0]^.val in [1..3]) and
  6879. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6880. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6881. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6882. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6883. MatchOpType(taicpu(hp1),top_ref))
  6884. ) and
  6885. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6886. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6887. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6888. begin
  6889. TransferUsedRegs(TmpUsedRegs);
  6890. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6891. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6892. begin
  6893. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6894. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6895. RemoveCurrentP(p);
  6896. Result:=true;
  6897. exit;
  6898. end;
  6899. end;
  6900. if MatchOpType(taicpu(p), top_const, top_reg) and
  6901. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6902. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6903. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6904. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6905. begin
  6906. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6907. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6908. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6909. {$ifdef x86_64}
  6910. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6911. {$endif x86_64}
  6912. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6913. begin
  6914. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6915. taicpu(hp1).opcode:=A_MOV;
  6916. taicpu(hp1).oper[0]^.val:=0;
  6917. end
  6918. else
  6919. begin
  6920. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6921. taicpu(hp1).oper[0]^.val:=shiftval;
  6922. end;
  6923. RemoveCurrentP(p);
  6924. Result:=true;
  6925. exit;
  6926. end;
  6927. end;
  6928. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6929. begin
  6930. case shr_size of
  6931. S_B:
  6932. { No valid combinations }
  6933. Result := False;
  6934. S_W:
  6935. Result := (Shift >= 8) and (movz_size = S_BW);
  6936. S_L:
  6937. Result :=
  6938. (Shift >= 24) { Any opsize is valid for this shift } or
  6939. ((Shift >= 16) and (movz_size = S_WL));
  6940. {$ifdef x86_64}
  6941. S_Q:
  6942. Result :=
  6943. (Shift >= 56) { Any opsize is valid for this shift } or
  6944. ((Shift >= 48) and (movz_size = S_WL));
  6945. {$endif x86_64}
  6946. else
  6947. InternalError(2022081510);
  6948. end;
  6949. end;
  6950. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6951. var
  6952. hp1, hp2: tai;
  6953. Shift: TCGInt;
  6954. LimitSize: Topsize;
  6955. DoNotMerge: Boolean;
  6956. begin
  6957. Result := False;
  6958. { All these optimisations work on "shr const,%reg" }
  6959. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6960. Exit;
  6961. DoNotMerge := False;
  6962. Shift := taicpu(p).oper[0]^.val;
  6963. LimitSize := taicpu(p).opsize;
  6964. hp1 := p;
  6965. repeat
  6966. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6967. Exit;
  6968. case taicpu(hp1).opcode of
  6969. A_TEST, A_CMP, A_Jcc:
  6970. { Skip over conditional jumps and relevant comparisons }
  6971. Continue;
  6972. A_MOVZX:
  6973. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6974. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6975. begin
  6976. { Since the original register is being read as is, subsequent
  6977. SHRs must not be merged at this point }
  6978. DoNotMerge := True;
  6979. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6980. begin
  6981. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6982. begin
  6983. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6984. taicpu(hp1).opcode := A_MOV;
  6985. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6986. case taicpu(hp1).opsize of
  6987. S_BW:
  6988. taicpu(hp1).opsize := S_W;
  6989. S_BL, S_WL:
  6990. taicpu(hp1).opsize := S_L;
  6991. else
  6992. InternalError(2022081503);
  6993. end;
  6994. { p itself hasn't changed, so no need to set Result to True }
  6995. Include(OptsToCheck, aoc_ForceNewIteration);
  6996. { See if there's anything afterwards that can be
  6997. optimised, since the input register hasn't changed }
  6998. Continue;
  6999. end;
  7000. { NOTE: If the MOVZX instruction reads and writes the same
  7001. register, defer this to the post-peephole optimisation stage }
  7002. Exit;
  7003. end;
  7004. end;
  7005. A_SHL, A_SAL, A_SHR:
  7006. if (taicpu(hp1).opsize <= LimitSize) and
  7007. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7008. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  7009. begin
  7010. { Make sure the sizes don't exceed the register size limit
  7011. (measured by the shift value falling below the limit) }
  7012. if taicpu(hp1).opsize < LimitSize then
  7013. LimitSize := taicpu(hp1).opsize;
  7014. if taicpu(hp1).opcode = A_SHR then
  7015. Inc(Shift, taicpu(hp1).oper[0]^.val)
  7016. else
  7017. begin
  7018. Dec(Shift, taicpu(hp1).oper[0]^.val);
  7019. DoNotMerge := True;
  7020. end;
  7021. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  7022. Exit;
  7023. { Since we've established that the combined shift is within
  7024. limits, we can actually combine the adjacent SHR
  7025. instructions even if they're different sizes }
  7026. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  7027. begin
  7028. hp2 := tai(hp1.Previous);
  7029. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  7030. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  7031. RemoveInstruction(hp1);
  7032. hp1 := hp2;
  7033. { Though p has changed, only the constant has, and its
  7034. effects can still be detected on the next iteration of
  7035. the repeat..until loop }
  7036. Include(OptsToCheck, aoc_ForceNewIteration);
  7037. end;
  7038. { Move onto the next instruction }
  7039. Continue;
  7040. end;
  7041. else
  7042. ;
  7043. end;
  7044. Break;
  7045. until False;
  7046. end;
  7047. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7048. var
  7049. CurrentRef: TReference;
  7050. FullReg: TRegister;
  7051. hp1, hp2: tai;
  7052. begin
  7053. Result := False;
  7054. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7055. Exit;
  7056. { We assume you've checked if the operand is actually a reference by
  7057. this point. If it isn't, you'll most likely get an access violation }
  7058. CurrentRef := first_mov.oper[1]^.ref^;
  7059. { Memory must be aligned }
  7060. if (CurrentRef.offset mod 4) <> 0 then
  7061. Exit;
  7062. Inc(CurrentRef.offset);
  7063. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7064. if MatchOperand(second_mov.oper[0]^, 0) and
  7065. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7066. GetNextInstruction(second_mov, hp1) and
  7067. (hp1.typ = ait_instruction) and
  7068. (taicpu(hp1).opcode = A_MOV) and
  7069. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7070. (taicpu(hp1).oper[0]^.val = 0) then
  7071. begin
  7072. Inc(CurrentRef.offset);
  7073. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7074. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7075. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7076. begin
  7077. case taicpu(hp1).opsize of
  7078. S_B:
  7079. if GetNextInstruction(hp1, hp2) and
  7080. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7081. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7082. (taicpu(hp2).oper[0]^.val = 0) then
  7083. begin
  7084. Inc(CurrentRef.offset);
  7085. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7086. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7087. (taicpu(hp2).opsize = S_B) then
  7088. begin
  7089. RemoveInstruction(hp1);
  7090. RemoveInstruction(hp2);
  7091. first_mov.opsize := S_L;
  7092. if first_mov.oper[0]^.typ = top_reg then
  7093. begin
  7094. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7095. { Reuse second_mov as a MOVZX instruction }
  7096. second_mov.opcode := A_MOVZX;
  7097. second_mov.opsize := S_BL;
  7098. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7099. second_mov.loadreg(1, FullReg);
  7100. first_mov.oper[0]^.reg := FullReg;
  7101. asml.Remove(second_mov);
  7102. asml.InsertBefore(second_mov, first_mov);
  7103. end
  7104. else
  7105. { It's a value }
  7106. begin
  7107. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7108. RemoveInstruction(second_mov);
  7109. end;
  7110. Result := True;
  7111. Exit;
  7112. end;
  7113. end;
  7114. S_W:
  7115. begin
  7116. RemoveInstruction(hp1);
  7117. first_mov.opsize := S_L;
  7118. if first_mov.oper[0]^.typ = top_reg then
  7119. begin
  7120. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7121. { Reuse second_mov as a MOVZX instruction }
  7122. second_mov.opcode := A_MOVZX;
  7123. second_mov.opsize := S_BL;
  7124. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7125. second_mov.loadreg(1, FullReg);
  7126. first_mov.oper[0]^.reg := FullReg;
  7127. asml.Remove(second_mov);
  7128. asml.InsertBefore(second_mov, first_mov);
  7129. end
  7130. else
  7131. { It's a value }
  7132. begin
  7133. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7134. RemoveInstruction(second_mov);
  7135. end;
  7136. Result := True;
  7137. Exit;
  7138. end;
  7139. else
  7140. ;
  7141. end;
  7142. end;
  7143. end;
  7144. end;
  7145. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7146. { returns true if a "continue" should be done after this optimization }
  7147. var
  7148. hp1, hp2, hp3: tai;
  7149. begin
  7150. Result := false;
  7151. hp3 := nil;
  7152. if MatchOpType(taicpu(p),top_ref) and
  7153. GetNextInstruction(p, hp1) and
  7154. (hp1.typ = ait_instruction) and
  7155. (((taicpu(hp1).opcode = A_FLD) and
  7156. (taicpu(p).opcode = A_FSTP)) or
  7157. ((taicpu(p).opcode = A_FISTP) and
  7158. (taicpu(hp1).opcode = A_FILD))) and
  7159. MatchOpType(taicpu(hp1),top_ref) and
  7160. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7161. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7162. begin
  7163. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7164. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7165. GetNextInstruction(hp1, hp2) and
  7166. (((hp2.typ = ait_instruction) and
  7167. IsExitCode(hp2) and
  7168. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7169. not(assigned(current_procinfo.procdef.funcretsym) and
  7170. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7171. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7172. { fstp <temp>
  7173. fld <temp>
  7174. <dealloc> <temp>
  7175. }
  7176. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7177. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7178. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7179. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7180. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7181. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7182. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7183. )
  7184. )
  7185. ) then
  7186. begin
  7187. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7188. RemoveInstruction(hp1);
  7189. RemoveCurrentP(p, hp2);
  7190. { first case: exit code }
  7191. if hp2.typ = ait_instruction then
  7192. RemoveLastDeallocForFuncRes(p);
  7193. Result := true;
  7194. end
  7195. else
  7196. { we can do this only in fast math mode as fstp is rounding ...
  7197. ... still disabled as it breaks the compiler and/or rtl }
  7198. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7199. { ... or if another fstp equal to the first one follows }
  7200. GetNextInstruction(hp1,hp2) and
  7201. (hp2.typ = ait_instruction) and
  7202. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7203. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7204. begin
  7205. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7206. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7207. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7208. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7209. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7210. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7211. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7212. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7213. ) then
  7214. begin
  7215. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7216. RemoveCurrentP(p,hp2);
  7217. RemoveInstruction(hp1);
  7218. Result := true;
  7219. end
  7220. else if { fst can't store an extended/comp value }
  7221. (taicpu(p).opsize <> S_FX) and
  7222. (taicpu(p).opsize <> S_IQ) then
  7223. begin
  7224. if (taicpu(p).opcode = A_FSTP) then
  7225. taicpu(p).opcode := A_FST
  7226. else
  7227. taicpu(p).opcode := A_FIST;
  7228. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7229. RemoveInstruction(hp1);
  7230. Result := true;
  7231. end;
  7232. end;
  7233. end;
  7234. end;
  7235. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7236. var
  7237. hp1, hp2, hp3: tai;
  7238. begin
  7239. result:=false;
  7240. if MatchOpType(taicpu(p),top_reg) and
  7241. GetNextInstruction(p, hp1) and
  7242. (hp1.typ = Ait_Instruction) and
  7243. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7244. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7245. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7246. { change to
  7247. fld reg fxxx reg,st
  7248. fxxxp st, st1 (hp1)
  7249. Remark: non commutative operations must be reversed!
  7250. }
  7251. begin
  7252. case taicpu(hp1).opcode Of
  7253. A_FMULP,A_FADDP,
  7254. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7255. begin
  7256. case taicpu(hp1).opcode Of
  7257. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7258. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7259. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7260. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7261. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7262. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7263. else
  7264. internalerror(2019050534);
  7265. end;
  7266. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7267. taicpu(hp1).oper[1]^.reg := NR_ST;
  7268. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7269. RemoveCurrentP(p, hp1);
  7270. Result:=true;
  7271. exit;
  7272. end;
  7273. else
  7274. ;
  7275. end;
  7276. end
  7277. else
  7278. if MatchOpType(taicpu(p),top_ref) and
  7279. GetNextInstruction(p, hp2) and
  7280. (hp2.typ = Ait_Instruction) and
  7281. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7282. (taicpu(p).opsize in [S_FS, S_FL]) and
  7283. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7284. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7285. if GetLastInstruction(p, hp1) and
  7286. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7287. MatchOpType(taicpu(hp1),top_ref) and
  7288. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7289. if ((taicpu(hp2).opcode = A_FMULP) or
  7290. (taicpu(hp2).opcode = A_FADDP)) then
  7291. { change to
  7292. fld/fst mem1 (hp1) fld/fst mem1
  7293. fld mem1 (p) fadd/
  7294. faddp/ fmul st, st
  7295. fmulp st, st1 (hp2) }
  7296. begin
  7297. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7298. RemoveCurrentP(p, hp1);
  7299. if (taicpu(hp2).opcode = A_FADDP) then
  7300. taicpu(hp2).opcode := A_FADD
  7301. else
  7302. taicpu(hp2).opcode := A_FMUL;
  7303. taicpu(hp2).oper[1]^.reg := NR_ST;
  7304. end
  7305. else
  7306. { change to
  7307. fld/fst mem1 (hp1) fld/fst mem1
  7308. fld mem1 (p) fld st
  7309. }
  7310. begin
  7311. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7312. taicpu(p).changeopsize(S_FL);
  7313. taicpu(p).loadreg(0,NR_ST);
  7314. end
  7315. else
  7316. begin
  7317. case taicpu(hp2).opcode Of
  7318. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7319. { change to
  7320. fld/fst mem1 (hp1) fld/fst mem1
  7321. fld mem2 (p) fxxx mem2
  7322. fxxxp st, st1 (hp2) }
  7323. begin
  7324. case taicpu(hp2).opcode Of
  7325. A_FADDP: taicpu(p).opcode := A_FADD;
  7326. A_FMULP: taicpu(p).opcode := A_FMUL;
  7327. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7328. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7329. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7330. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7331. else
  7332. internalerror(2019050533);
  7333. end;
  7334. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7335. RemoveInstruction(hp2);
  7336. end
  7337. else
  7338. ;
  7339. end
  7340. end
  7341. end;
  7342. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7343. begin
  7344. Result := condition_in(cond1, cond2) or
  7345. { Not strictly subsets due to the actual flags checked, but because we're
  7346. comparing integers, E is a subset of AE and GE and their aliases }
  7347. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7348. end;
  7349. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7350. var
  7351. v: TCGInt;
  7352. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7353. FirstMatch, TempBool: Boolean;
  7354. NewReg: TRegister;
  7355. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7356. begin
  7357. Result:=false;
  7358. { All these optimisations need a next instruction }
  7359. if not GetNextInstruction(p, hp1) then
  7360. Exit;
  7361. true_hp1 := hp1;
  7362. { Search for:
  7363. cmp ###,###
  7364. j(c1) @lbl1
  7365. ...
  7366. @lbl:
  7367. cmp ###,### (same comparison as above)
  7368. j(c2) @lbl2
  7369. If c1 is a subset of c2, change to:
  7370. cmp ###,###
  7371. j(c1) @lbl2
  7372. (@lbl1 may become a dead label as a result)
  7373. }
  7374. { Also handle cases where there are multiple jumps in a row }
  7375. p_jump := hp1;
  7376. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7377. begin
  7378. Prefetch(p_jump.Next);
  7379. if IsJumpToLabel(taicpu(p_jump)) then
  7380. begin
  7381. { Do jump optimisations first in case the condition becomes
  7382. unnecessary }
  7383. TempBool := True;
  7384. if DoJumpOptimizations(p_jump, TempBool) or
  7385. not TempBool then
  7386. begin
  7387. if Assigned(p_jump) then
  7388. begin
  7389. { CollapseZeroDistJump will be set to the label or an align
  7390. before it after the jump if it optimises, whether or not
  7391. the label is live or dead }
  7392. if (p_jump.typ = ait_align) or
  7393. (
  7394. (p_jump.typ = ait_label) and
  7395. not (tai_label(p_jump).labsym.is_used)
  7396. ) then
  7397. GetNextInstruction(p_jump, p_jump);
  7398. end;
  7399. TransferUsedRegs(TmpUsedRegs);
  7400. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7401. if not Assigned(p_jump) or
  7402. (
  7403. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7404. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7405. ) then
  7406. begin
  7407. { No more conditional jumps; conditional statement is no longer required }
  7408. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7409. RemoveCurrentP(p);
  7410. Result := True;
  7411. Exit;
  7412. end;
  7413. hp1 := p_jump;
  7414. Include(OptsToCheck, aoc_ForceNewIteration);
  7415. Continue;
  7416. end;
  7417. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7418. if GetNextInstruction(p_jump, hp2) and
  7419. (
  7420. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7421. not TempBool
  7422. ) then
  7423. begin
  7424. hp1 := p_jump;
  7425. Include(OptsToCheck, aoc_ForceNewIteration);
  7426. Continue;
  7427. end;
  7428. p_label := nil;
  7429. if Assigned(JumpLabel) then
  7430. p_label := getlabelwithsym(JumpLabel);
  7431. if Assigned(p_label) and
  7432. GetNextInstruction(p_label, p_dist) and
  7433. MatchInstruction(p_dist, A_CMP, []) and
  7434. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7435. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7436. GetNextInstruction(p_dist, hp1_dist) and
  7437. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7438. begin
  7439. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7440. if JumpLabel = JumpLabel_dist then
  7441. { This is an infinite loop }
  7442. Exit;
  7443. { Best optimisation when the first condition is a subset (or equal) of the second }
  7444. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7445. begin
  7446. { Any registers used here will already be allocated }
  7447. if Assigned(JumpLabel) then
  7448. JumpLabel.DecRefs;
  7449. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7450. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7451. Include(OptsToCheck, aoc_ForceNewIteration);
  7452. { Don't exit yet. Since p and p_jump haven't actually been
  7453. removed, we can check for more on this iteration }
  7454. end
  7455. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7456. GetNextInstruction(hp1_dist, hp1_label) and
  7457. (hp1_label.typ = ait_label) then
  7458. begin
  7459. JumpLabel_far := tai_label(hp1_label).labsym;
  7460. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7461. { This is an infinite loop }
  7462. Exit;
  7463. if Assigned(JumpLabel_far) then
  7464. begin
  7465. { In this situation, if the first jump branches, the second one will never,
  7466. branch so change the destination label to after the second jump }
  7467. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7468. if Assigned(JumpLabel) then
  7469. JumpLabel.DecRefs;
  7470. JumpLabel_far.IncRefs;
  7471. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7472. Result := True;
  7473. { Don't exit yet. Since p and p_jump haven't actually been
  7474. removed, we can check for more on this iteration }
  7475. Continue;
  7476. end;
  7477. end;
  7478. end;
  7479. end;
  7480. { Search for:
  7481. cmp ###,###
  7482. j(c1) @lbl1
  7483. cmp ###,### (same as first)
  7484. Remove second cmp
  7485. }
  7486. if GetNextInstruction(p_jump, hp2) and
  7487. (
  7488. (
  7489. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7490. (
  7491. (
  7492. MatchOpType(taicpu(p), top_const, top_reg) and
  7493. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7494. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7495. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7496. ) or (
  7497. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7498. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7499. )
  7500. )
  7501. ) or (
  7502. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7503. MatchOperand(taicpu(p).oper[0]^, 0) and
  7504. (taicpu(p).oper[1]^.typ = top_reg) and
  7505. MatchInstruction(hp2, A_TEST, []) and
  7506. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7507. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7508. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7509. )
  7510. ) then
  7511. begin
  7512. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7513. TransferUsedRegs(TmpUsedRegs);
  7514. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7515. RemoveInstruction(hp2);
  7516. Result := True;
  7517. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7518. end
  7519. else
  7520. begin
  7521. { hp2 is the next instruction, so save time and just set p_jump
  7522. to it instead of calling GetNextInstruction below }
  7523. p_jump := hp2;
  7524. Continue;
  7525. end;
  7526. GetNextInstruction(p_jump, p_jump);
  7527. end;
  7528. if (
  7529. { Don't call GetNextInstruction again if we already have it }
  7530. (true_hp1 = p_jump) or
  7531. GetNextInstruction(p, hp1)
  7532. ) and
  7533. MatchInstruction(hp1, A_Jcc, []) and
  7534. IsJumpToLabel(taicpu(hp1)) and
  7535. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7536. GetNextInstruction(hp1, hp2) then
  7537. begin
  7538. {
  7539. cmp x, y (or "cmp y, x")
  7540. je @lbl
  7541. mov x, y
  7542. @lbl:
  7543. (x and y can be constants, registers or references)
  7544. Change to:
  7545. mov x, y (x and y will always be equal in the end)
  7546. @lbl: (may beceome a dead label)
  7547. Also:
  7548. cmp x, y (or "cmp y, x")
  7549. jne @lbl
  7550. mov x, y
  7551. @lbl:
  7552. (x and y can be constants, registers or references)
  7553. Change to:
  7554. Absolutely nothing! (Except @lbl if it's still live)
  7555. }
  7556. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7557. (
  7558. (
  7559. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7560. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7561. ) or (
  7562. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7563. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7564. )
  7565. ) and
  7566. GetNextInstruction(hp2, hp1_label) and
  7567. (hp1_label.typ = ait_label) and
  7568. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7569. begin
  7570. tai_label(hp1_label).labsym.DecRefs;
  7571. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7572. begin
  7573. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7574. RemoveInstruction(hp2);
  7575. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7576. end
  7577. else
  7578. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7579. RemoveInstruction(hp1);
  7580. RemoveCurrentp(p, hp2);
  7581. Result := True;
  7582. Exit;
  7583. end;
  7584. {
  7585. Try to optimise the following:
  7586. cmp $x,### ($x and $y can be registers or constants)
  7587. je @lbl1 (only reference)
  7588. cmp $y,### (### are identical)
  7589. @Lbl:
  7590. sete %reg1
  7591. Change to:
  7592. cmp $x,###
  7593. sete %reg2 (allocate new %reg2)
  7594. cmp $y,###
  7595. sete %reg1
  7596. orb %reg2,%reg1
  7597. (dealloc %reg2)
  7598. This adds an instruction (so don't perform under -Os), but it removes
  7599. a conditional branch.
  7600. }
  7601. if not (cs_opt_size in current_settings.optimizerswitches) and
  7602. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7603. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7604. { The first operand of CMP instructions can only be a register or
  7605. immediate anyway, so no need to check }
  7606. GetNextInstruction(hp2, p_label) and
  7607. (p_label.typ = ait_label) and
  7608. (tai_label(p_label).labsym.getrefs = 1) and
  7609. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7610. GetNextInstruction(p_label, p_dist) and
  7611. MatchInstruction(p_dist, A_SETcc, []) and
  7612. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7613. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7614. begin
  7615. TransferUsedRegs(TmpUsedRegs);
  7616. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7617. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7618. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7619. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7620. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7621. { Get the instruction after the SETcc instruction so we can
  7622. allocate a new register over the entire range }
  7623. GetNextInstruction(p_dist, hp1_dist) then
  7624. begin
  7625. { Register can appear in p if it's not used afterwards, so only
  7626. allocate between hp1 and hp1_dist }
  7627. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7628. if NewReg <> NR_NO then
  7629. begin
  7630. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7631. { Change the jump instruction into a SETcc instruction }
  7632. taicpu(hp1).opcode := A_SETcc;
  7633. taicpu(hp1).opsize := S_B;
  7634. taicpu(hp1).loadreg(0, NewReg);
  7635. { This is now a dead label }
  7636. tai_label(p_label).labsym.decrefs;
  7637. { Prefer adding before the next instruction so the FLAGS
  7638. register is deallicated first }
  7639. AsmL.InsertBefore(
  7640. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7641. hp1_dist
  7642. );
  7643. Result := True;
  7644. { Don't exit yet, as p wasn't changed and hp1, while
  7645. modified, is still intact and might be optimised by the
  7646. SETcc optimisation below }
  7647. end;
  7648. end;
  7649. end;
  7650. end;
  7651. if (taicpu(p).oper[0]^.typ = top_const) and
  7652. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7653. begin
  7654. if (taicpu(p).oper[0]^.val = 0) and
  7655. (taicpu(p).oper[1]^.typ = top_reg) then
  7656. begin
  7657. hp2 := p;
  7658. FirstMatch := True;
  7659. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7660. anything meaningful once it's converted to "test %reg,%reg";
  7661. additionally, some jumps will always (or never) branch, so
  7662. evaluate every jump immediately following the
  7663. comparison, optimising the conditions if possible.
  7664. Similarly with SETcc... those that are always set to 0 or 1
  7665. are changed to MOV instructions }
  7666. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7667. (
  7668. GetNextInstruction(hp2, hp1) and
  7669. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7670. ) do
  7671. begin
  7672. Prefetch(hp1.Next);
  7673. FirstMatch := False;
  7674. case taicpu(hp1).condition of
  7675. C_B, C_C, C_NAE, C_O:
  7676. { For B/NAE:
  7677. Will never branch since an unsigned integer can never be below zero
  7678. For C/O:
  7679. Result cannot overflow because 0 is being subtracted
  7680. }
  7681. begin
  7682. if taicpu(hp1).opcode = A_Jcc then
  7683. begin
  7684. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7685. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7686. RemoveInstruction(hp1);
  7687. { Since hp1 was deleted, hp2 must not be updated }
  7688. Continue;
  7689. end
  7690. else
  7691. begin
  7692. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7693. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7694. taicpu(hp1).opcode := A_MOV;
  7695. taicpu(hp1).ops := 2;
  7696. taicpu(hp1).condition := C_None;
  7697. taicpu(hp1).opsize := S_B;
  7698. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7699. taicpu(hp1).loadconst(0, 0);
  7700. end;
  7701. end;
  7702. C_BE, C_NA:
  7703. begin
  7704. { Will only branch if equal to zero }
  7705. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7706. taicpu(hp1).condition := C_E;
  7707. end;
  7708. C_A, C_NBE:
  7709. begin
  7710. { Will only branch if not equal to zero }
  7711. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7712. taicpu(hp1).condition := C_NE;
  7713. end;
  7714. C_AE, C_NB, C_NC, C_NO:
  7715. begin
  7716. { Will always branch }
  7717. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7718. if taicpu(hp1).opcode = A_Jcc then
  7719. begin
  7720. MakeUnconditional(taicpu(hp1));
  7721. { Any jumps/set that follow will now be dead code }
  7722. RemoveDeadCodeAfterJump(taicpu(hp1));
  7723. Break;
  7724. end
  7725. else
  7726. begin
  7727. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7728. taicpu(hp1).opcode := A_MOV;
  7729. taicpu(hp1).ops := 2;
  7730. taicpu(hp1).condition := C_None;
  7731. taicpu(hp1).opsize := S_B;
  7732. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7733. taicpu(hp1).loadconst(0, 1);
  7734. end;
  7735. end;
  7736. C_None:
  7737. InternalError(2020012201);
  7738. C_P, C_PE, C_NP, C_PO:
  7739. { We can't handle parity checks and they should never be generated
  7740. after a general-purpose CMP (it's used in some floating-point
  7741. comparisons that don't use CMP) }
  7742. InternalError(2020012202);
  7743. else
  7744. { Zero/Equality, Sign, their complements and all of the
  7745. signed comparisons do not need to be converted };
  7746. end;
  7747. hp2 := hp1;
  7748. end;
  7749. { Convert the instruction to a TEST }
  7750. taicpu(p).opcode := A_TEST;
  7751. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7752. Result := True;
  7753. Exit;
  7754. end
  7755. else
  7756. begin
  7757. TransferUsedRegs(TmpUsedRegs);
  7758. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7759. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7760. begin
  7761. if (taicpu(p).oper[0]^.val = 1) and
  7762. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7763. begin
  7764. { Convert; To:
  7765. cmp $1,r/m cmp $0,r/m
  7766. jl @lbl jle @lbl
  7767. (Also do inverted conditions)
  7768. }
  7769. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7770. taicpu(p).oper[0]^.val := 0;
  7771. if taicpu(hp1).condition in [C_L, C_NGE] then
  7772. taicpu(hp1).condition := C_LE
  7773. else
  7774. taicpu(hp1).condition := C_NLE;
  7775. { If the instruction is now "cmp $0,%reg", convert it to a
  7776. TEST (and effectively do the work of the "cmp $0,%reg" in
  7777. the block above)
  7778. }
  7779. if (taicpu(p).oper[1]^.typ = top_reg) then
  7780. begin
  7781. taicpu(p).opcode := A_TEST;
  7782. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7783. end;
  7784. Result := True;
  7785. Exit;
  7786. end
  7787. else if (taicpu(p).oper[1]^.typ = top_reg)
  7788. {$ifdef x86_64}
  7789. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7790. {$endif x86_64}
  7791. then
  7792. begin
  7793. { cmp register,$8000 neg register
  7794. je target --> jo target
  7795. .... only if register is deallocated before jump.}
  7796. case Taicpu(p).opsize of
  7797. S_B: v:=$80;
  7798. S_W: v:=$8000;
  7799. S_L: v:=qword($80000000);
  7800. else
  7801. internalerror(2013112905);
  7802. end;
  7803. if (taicpu(p).oper[0]^.val=v) and
  7804. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7805. begin
  7806. TransferUsedRegs(TmpUsedRegs);
  7807. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7808. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7809. begin
  7810. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7811. Taicpu(p).opcode:=A_NEG;
  7812. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7813. Taicpu(p).clearop(1);
  7814. Taicpu(p).ops:=1;
  7815. if Taicpu(hp1).condition=C_E then
  7816. Taicpu(hp1).condition:=C_O
  7817. else
  7818. Taicpu(hp1).condition:=C_NO;
  7819. Result:=true;
  7820. exit;
  7821. end;
  7822. end;
  7823. end;
  7824. end;
  7825. end;
  7826. end;
  7827. if TrySwapMovCmp(p, hp1) then
  7828. begin
  7829. Result := True;
  7830. Exit;
  7831. end;
  7832. end;
  7833. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7834. var
  7835. hp1: tai;
  7836. begin
  7837. {
  7838. remove the second (v)pxor from
  7839. pxor reg,reg
  7840. ...
  7841. pxor reg,reg
  7842. }
  7843. Result:=false;
  7844. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7845. MatchOpType(taicpu(p),top_reg,top_reg) and
  7846. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7847. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7848. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7849. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7850. begin
  7851. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7852. RemoveInstruction(hp1);
  7853. Result:=true;
  7854. Exit;
  7855. end
  7856. {
  7857. replace
  7858. pxor reg1,reg1
  7859. movapd/s reg1,reg2
  7860. dealloc reg1
  7861. by
  7862. pxor reg2,reg2
  7863. }
  7864. else if GetNextInstruction(p,hp1) and
  7865. { we mix single and double opperations here because we assume that the compiler
  7866. generates vmovapd only after double operations and vmovaps only after single operations }
  7867. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7868. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7869. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7870. (taicpu(p).oper[0]^.typ=top_reg) then
  7871. begin
  7872. TransferUsedRegs(TmpUsedRegs);
  7873. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7874. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7875. begin
  7876. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7877. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7878. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7879. RemoveInstruction(hp1);
  7880. result:=true;
  7881. end;
  7882. end;
  7883. end;
  7884. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7885. var
  7886. hp1: tai;
  7887. begin
  7888. {
  7889. remove the second (v)pxor from
  7890. (v)pxor reg,reg
  7891. ...
  7892. (v)pxor reg,reg
  7893. }
  7894. Result:=false;
  7895. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7896. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7897. begin
  7898. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7899. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7900. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7901. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7902. begin
  7903. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7904. RemoveInstruction(hp1);
  7905. Result:=true;
  7906. Exit;
  7907. end;
  7908. {$ifdef x86_64}
  7909. {
  7910. replace
  7911. vpxor reg1,reg1,reg1
  7912. vmov reg,mem
  7913. by
  7914. movq $0,mem
  7915. }
  7916. if GetNextInstruction(p,hp1) and
  7917. MatchInstruction(hp1,A_VMOVSD,[]) and
  7918. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7919. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7920. begin
  7921. TransferUsedRegs(TmpUsedRegs);
  7922. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7923. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7924. begin
  7925. taicpu(hp1).loadconst(0,0);
  7926. taicpu(hp1).opcode:=A_MOV;
  7927. taicpu(hp1).opsize:=S_Q;
  7928. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7929. RemoveCurrentP(p);
  7930. result:=true;
  7931. Exit;
  7932. end;
  7933. end;
  7934. {$endif x86_64}
  7935. end
  7936. {
  7937. replace
  7938. vpxor reg1,reg1,reg2
  7939. by
  7940. vpxor reg2,reg2,reg2
  7941. to avoid unncessary data dependencies
  7942. }
  7943. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7944. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7945. begin
  7946. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7947. { avoid unncessary data dependency }
  7948. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7949. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7950. result:=true;
  7951. exit;
  7952. end;
  7953. Result:=OptPass1VOP(p);
  7954. end;
  7955. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7956. var
  7957. hp1 : tai;
  7958. begin
  7959. result:=false;
  7960. { replace
  7961. IMul const,%mreg1,%mreg2
  7962. Mov %reg2,%mreg3
  7963. dealloc %mreg3
  7964. by
  7965. Imul const,%mreg1,%mreg23
  7966. }
  7967. if (taicpu(p).ops=3) and
  7968. GetNextInstruction(p,hp1) and
  7969. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7970. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7971. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7972. begin
  7973. TransferUsedRegs(TmpUsedRegs);
  7974. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7975. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7976. begin
  7977. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7978. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7979. RemoveInstruction(hp1);
  7980. result:=true;
  7981. end;
  7982. end;
  7983. end;
  7984. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7985. var
  7986. hp1 : tai;
  7987. begin
  7988. result:=false;
  7989. { replace
  7990. IMul %reg0,%reg1,%reg2
  7991. Mov %reg2,%reg3
  7992. dealloc %reg2
  7993. by
  7994. Imul %reg0,%reg1,%reg3
  7995. }
  7996. if GetNextInstruction(p,hp1) and
  7997. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7998. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7999. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8000. begin
  8001. TransferUsedRegs(TmpUsedRegs);
  8002. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8003. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8004. begin
  8005. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8006. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  8007. RemoveInstruction(hp1);
  8008. result:=true;
  8009. end;
  8010. end;
  8011. end;
  8012. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  8013. var
  8014. hp1: tai;
  8015. begin
  8016. Result:=false;
  8017. { get rid of
  8018. (v)cvtss2sd reg0,<reg1,>reg2
  8019. (v)cvtss2sd reg2,<reg2,>reg0
  8020. }
  8021. if GetNextInstruction(p,hp1) and
  8022. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  8023. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  8024. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  8025. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  8026. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  8027. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8028. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8029. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  8030. )
  8031. ) then
  8032. begin
  8033. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8034. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8035. begin
  8036. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8037. RemoveCurrentP(p);
  8038. RemoveInstruction(hp1);
  8039. end
  8040. else
  8041. begin
  8042. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8043. if taicpu(hp1).opcode=A_CVTSD2SS then
  8044. begin
  8045. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8046. taicpu(p).opcode:=A_MOVAPS;
  8047. end
  8048. else
  8049. begin
  8050. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8051. taicpu(p).opcode:=A_VMOVAPS;
  8052. end;
  8053. taicpu(p).ops:=2;
  8054. RemoveInstruction(hp1);
  8055. end;
  8056. Result:=true;
  8057. Exit;
  8058. end;
  8059. end;
  8060. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8061. var
  8062. hp1, hp2, hp3, hp4, hp5: tai;
  8063. ThisReg: TRegister;
  8064. begin
  8065. Result := False;
  8066. if not GetNextInstruction(p,hp1) then
  8067. Exit;
  8068. {
  8069. convert
  8070. j<c> .L1
  8071. mov 1,reg
  8072. jmp .L2
  8073. .L1
  8074. mov 0,reg
  8075. .L2
  8076. into
  8077. mov 0,reg
  8078. set<not(c)> reg
  8079. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8080. would destroy the flag contents
  8081. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8082. executed at the same time as a previous comparison.
  8083. set<not(c)> reg
  8084. movzx reg, reg
  8085. }
  8086. if MatchInstruction(hp1,A_MOV,[]) and
  8087. (taicpu(hp1).oper[0]^.typ = top_const) and
  8088. (
  8089. (
  8090. (taicpu(hp1).oper[1]^.typ = top_reg)
  8091. {$ifdef i386}
  8092. { Under i386, ESI, EDI, EBP and ESP
  8093. don't have an 8-bit representation }
  8094. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8095. {$endif i386}
  8096. ) or (
  8097. {$ifdef i386}
  8098. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8099. {$endif i386}
  8100. (taicpu(hp1).opsize = S_B)
  8101. )
  8102. ) and
  8103. GetNextInstruction(hp1,hp2) and
  8104. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8105. GetNextInstruction(hp2,hp3) and
  8106. (hp3.typ=ait_label) and
  8107. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  8108. GetNextInstruction(hp3,hp4) and
  8109. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8110. (taicpu(hp4).oper[0]^.typ = top_const) and
  8111. (
  8112. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8113. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8114. ) and
  8115. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8116. GetNextInstruction(hp4,hp5) and
  8117. (hp5.typ=ait_label) and
  8118. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  8119. begin
  8120. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8121. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8122. tai_label(hp3).labsym.DecRefs;
  8123. { If this isn't the only reference to the middle label, we can
  8124. still make a saving - only that the first jump and everything
  8125. that follows will remain. }
  8126. if (tai_label(hp3).labsym.getrefs = 0) then
  8127. begin
  8128. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8129. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8130. else
  8131. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8132. { remove jump, first label and second MOV (also catching any aligns) }
  8133. repeat
  8134. if not GetNextInstruction(hp2, hp3) then
  8135. InternalError(2021040810);
  8136. RemoveInstruction(hp2);
  8137. hp2 := hp3;
  8138. until hp2 = hp5;
  8139. { Don't decrement reference count before the removal loop
  8140. above, otherwise GetNextInstruction won't stop on the
  8141. the label }
  8142. tai_label(hp5).labsym.DecRefs;
  8143. end
  8144. else
  8145. begin
  8146. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8147. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8148. else
  8149. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8150. end;
  8151. taicpu(p).opcode:=A_SETcc;
  8152. taicpu(p).opsize:=S_B;
  8153. taicpu(p).is_jmp:=False;
  8154. if taicpu(hp1).opsize=S_B then
  8155. begin
  8156. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8157. if taicpu(hp1).oper[1]^.typ = top_reg then
  8158. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8159. RemoveInstruction(hp1);
  8160. end
  8161. else
  8162. begin
  8163. { Will be a register because the size can't be S_B otherwise }
  8164. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8165. taicpu(p).loadreg(0, ThisReg);
  8166. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8167. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8168. begin
  8169. case taicpu(hp1).opsize of
  8170. S_W:
  8171. taicpu(hp1).opsize := S_BW;
  8172. S_L:
  8173. taicpu(hp1).opsize := S_BL;
  8174. {$ifdef x86_64}
  8175. S_Q:
  8176. begin
  8177. taicpu(hp1).opsize := S_BL;
  8178. { Change the destination register to 32-bit }
  8179. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8180. end;
  8181. {$endif x86_64}
  8182. else
  8183. InternalError(2021040820);
  8184. end;
  8185. taicpu(hp1).opcode := A_MOVZX;
  8186. taicpu(hp1).loadreg(0, ThisReg);
  8187. end
  8188. else
  8189. begin
  8190. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8191. { hp1 is already a MOV instruction with the correct register }
  8192. taicpu(hp1).loadconst(0, 0);
  8193. { Inserting it right before p will guarantee that the flags are also tracked }
  8194. asml.Remove(hp1);
  8195. asml.InsertBefore(hp1, p);
  8196. end;
  8197. end;
  8198. Result:=true;
  8199. exit;
  8200. end
  8201. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8202. Result := TryJccStcClcOpt(p, hp1)
  8203. else if (hp1.typ = ait_label) then
  8204. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8205. end;
  8206. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8207. var
  8208. hp1, hp2, hp3: tai;
  8209. SourceRef, TargetRef: TReference;
  8210. CurrentReg: TRegister;
  8211. begin
  8212. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8213. if not UseAVX then
  8214. InternalError(2021100501);
  8215. Result := False;
  8216. { Look for the following to simplify:
  8217. vmovdqa/u x(mem1), %xmmreg
  8218. vmovdqa/u %xmmreg, y(mem2)
  8219. vmovdqa/u x+16(mem1), %xmmreg
  8220. vmovdqa/u %xmmreg, y+16(mem2)
  8221. Change to:
  8222. vmovdqa/u x(mem1), %ymmreg
  8223. vmovdqa/u %ymmreg, y(mem2)
  8224. vpxor %ymmreg, %ymmreg, %ymmreg
  8225. ( The VPXOR instruction is to zero the upper half, thus removing the
  8226. need to call the potentially expensive VZEROUPPER instruction. Other
  8227. peephole optimisations can remove VPXOR if it's unnecessary )
  8228. }
  8229. TransferUsedRegs(TmpUsedRegs);
  8230. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8231. { NOTE: In the optimisations below, if the references dictate that an
  8232. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8233. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8234. if (taicpu(p).opsize = S_XMM) and
  8235. MatchOpType(taicpu(p), top_ref, top_reg) and
  8236. GetNextInstruction(p, hp1) and
  8237. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8238. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8239. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8240. begin
  8241. SourceRef := taicpu(p).oper[0]^.ref^;
  8242. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8243. if GetNextInstruction(hp1, hp2) and
  8244. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8245. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8246. begin
  8247. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8248. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8249. Inc(SourceRef.offset, 16);
  8250. { Reuse the register in the first block move }
  8251. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8252. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8253. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8254. begin
  8255. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8256. Inc(TargetRef.offset, 16);
  8257. if GetNextInstruction(hp2, hp3) and
  8258. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8259. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8260. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8261. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8262. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8263. begin
  8264. { Update the register tracking to the new size }
  8265. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8266. { Remember that the offsets are 16 ahead }
  8267. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8268. if not (
  8269. ((SourceRef.offset mod 32) = 16) and
  8270. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8271. ) then
  8272. taicpu(p).opcode := A_VMOVDQU;
  8273. taicpu(p).opsize := S_YMM;
  8274. taicpu(p).oper[1]^.reg := CurrentReg;
  8275. if not (
  8276. ((TargetRef.offset mod 32) = 16) and
  8277. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8278. ) then
  8279. taicpu(hp1).opcode := A_VMOVDQU;
  8280. taicpu(hp1).opsize := S_YMM;
  8281. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8282. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8283. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8284. if (pi_uses_ymm in current_procinfo.flags) then
  8285. RemoveInstruction(hp2)
  8286. else
  8287. begin
  8288. taicpu(hp2).opcode := A_VPXOR;
  8289. taicpu(hp2).opsize := S_YMM;
  8290. taicpu(hp2).loadreg(0, CurrentReg);
  8291. taicpu(hp2).loadreg(1, CurrentReg);
  8292. taicpu(hp2).loadreg(2, CurrentReg);
  8293. taicpu(hp2).ops := 3;
  8294. end;
  8295. RemoveInstruction(hp3);
  8296. Result := True;
  8297. Exit;
  8298. end;
  8299. end
  8300. else
  8301. begin
  8302. { See if the next references are 16 less rather than 16 greater }
  8303. Dec(SourceRef.offset, 32); { -16 the other way }
  8304. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8305. begin
  8306. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8307. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8308. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8309. GetNextInstruction(hp2, hp3) and
  8310. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8311. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8312. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8313. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8314. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8315. begin
  8316. { Update the register tracking to the new size }
  8317. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8318. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8319. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8320. if not(
  8321. ((SourceRef.offset mod 32) = 0) and
  8322. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8323. ) then
  8324. taicpu(hp2).opcode := A_VMOVDQU;
  8325. taicpu(hp2).opsize := S_YMM;
  8326. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8327. if not (
  8328. ((TargetRef.offset mod 32) = 0) and
  8329. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8330. ) then
  8331. taicpu(hp3).opcode := A_VMOVDQU;
  8332. taicpu(hp3).opsize := S_YMM;
  8333. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8334. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8335. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8336. if (pi_uses_ymm in current_procinfo.flags) then
  8337. RemoveInstruction(hp1)
  8338. else
  8339. begin
  8340. taicpu(hp1).opcode := A_VPXOR;
  8341. taicpu(hp1).opsize := S_YMM;
  8342. taicpu(hp1).loadreg(0, CurrentReg);
  8343. taicpu(hp1).loadreg(1, CurrentReg);
  8344. taicpu(hp1).loadreg(2, CurrentReg);
  8345. taicpu(hp1).ops := 3;
  8346. Asml.Remove(hp1);
  8347. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8348. end;
  8349. RemoveCurrentP(p, hp2);
  8350. Result := True;
  8351. Exit;
  8352. end;
  8353. end;
  8354. end;
  8355. end;
  8356. end;
  8357. end;
  8358. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8359. var
  8360. hp2, hp3, first_assignment: tai;
  8361. IncCount, OperIdx: Integer;
  8362. OrigLabel: TAsmLabel;
  8363. begin
  8364. Count := 0;
  8365. Result := False;
  8366. first_assignment := nil;
  8367. if (LoopCount >= 20) then
  8368. begin
  8369. { Guard against infinite loops }
  8370. Exit;
  8371. end;
  8372. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8373. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8374. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8375. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8376. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8377. Exit;
  8378. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8379. {
  8380. change
  8381. jmp .L1
  8382. ...
  8383. .L1:
  8384. mov ##, ## ( multiple movs possible )
  8385. jmp/ret
  8386. into
  8387. mov ##, ##
  8388. jmp/ret
  8389. }
  8390. if not Assigned(hp1) then
  8391. begin
  8392. hp1 := GetLabelWithSym(OrigLabel);
  8393. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8394. Exit;
  8395. end;
  8396. hp2 := hp1;
  8397. while Assigned(hp2) do
  8398. begin
  8399. if Assigned(hp2) and (hp2.typ = ait_label) then
  8400. SkipLabels(hp2,hp2);
  8401. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8402. Break;
  8403. case taicpu(hp2).opcode of
  8404. A_MOVSD:
  8405. begin
  8406. if taicpu(hp2).ops = 0 then
  8407. { Wrong MOVSD }
  8408. Break;
  8409. Inc(Count);
  8410. if Count >= 5 then
  8411. { Too many to be worthwhile }
  8412. Break;
  8413. GetNextInstruction(hp2, hp2);
  8414. Continue;
  8415. end;
  8416. A_MOV,
  8417. A_MOVD,
  8418. A_MOVQ,
  8419. A_MOVSX,
  8420. {$ifdef x86_64}
  8421. A_MOVSXD,
  8422. {$endif x86_64}
  8423. A_MOVZX,
  8424. A_MOVAPS,
  8425. A_MOVUPS,
  8426. A_MOVSS,
  8427. A_MOVAPD,
  8428. A_MOVUPD,
  8429. A_MOVDQA,
  8430. A_MOVDQU,
  8431. A_VMOVSS,
  8432. A_VMOVAPS,
  8433. A_VMOVUPS,
  8434. A_VMOVSD,
  8435. A_VMOVAPD,
  8436. A_VMOVUPD,
  8437. A_VMOVDQA,
  8438. A_VMOVDQU:
  8439. begin
  8440. Inc(Count);
  8441. if Count >= 5 then
  8442. { Too many to be worthwhile }
  8443. Break;
  8444. GetNextInstruction(hp2, hp2);
  8445. Continue;
  8446. end;
  8447. A_JMP:
  8448. begin
  8449. { Guard against infinite loops }
  8450. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8451. Exit;
  8452. { Analyse this jump first in case it also duplicates assignments }
  8453. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8454. begin
  8455. { Something did change! }
  8456. Result := True;
  8457. Inc(Count, IncCount);
  8458. if Count >= 5 then
  8459. begin
  8460. { Too many to be worthwhile }
  8461. Exit;
  8462. end;
  8463. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8464. Break;
  8465. end;
  8466. Result := True;
  8467. Break;
  8468. end;
  8469. A_RET:
  8470. begin
  8471. Result := True;
  8472. Break;
  8473. end;
  8474. else
  8475. Break;
  8476. end;
  8477. end;
  8478. if Result then
  8479. begin
  8480. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8481. if Count = 0 then
  8482. begin
  8483. Result := False;
  8484. Exit;
  8485. end;
  8486. TransferUsedRegs(TmpUsedRegs);
  8487. hp3 := p;
  8488. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8489. while True do
  8490. begin
  8491. if Assigned(hp1) and (hp1.typ = ait_label) then
  8492. SkipLabels(hp1,hp1);
  8493. case hp1.typ of
  8494. ait_regalloc:
  8495. if tai_regalloc(hp1).ratype = ra_dealloc then
  8496. begin
  8497. { Duplicate the register deallocation... }
  8498. hp3:=tai(hp1.getcopy);
  8499. if first_assignment = nil then
  8500. first_assignment := hp3;
  8501. asml.InsertBefore(hp3, p);
  8502. { ... but also reallocate it after the jump }
  8503. hp3:=tai(hp1.getcopy);
  8504. tai_regalloc(hp3).ratype := ra_alloc;
  8505. asml.InsertAfter(hp3, p);
  8506. end;
  8507. ait_instruction:
  8508. case taicpu(hp1).opcode of
  8509. A_JMP:
  8510. begin
  8511. { Change the original jump to the new destination }
  8512. OrigLabel.decrefs;
  8513. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8514. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8515. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8516. if not Assigned(first_assignment) then
  8517. InternalError(2021040810)
  8518. else
  8519. p := first_assignment;
  8520. Exit;
  8521. end;
  8522. A_RET:
  8523. begin
  8524. { Now change the jump into a RET instruction }
  8525. ConvertJumpToRET(p, hp1);
  8526. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8527. if not Assigned(first_assignment) then
  8528. InternalError(2021040811)
  8529. else
  8530. p := first_assignment;
  8531. Exit;
  8532. end;
  8533. else
  8534. begin
  8535. { Duplicate the MOV instruction }
  8536. hp3:=tai(hp1.getcopy);
  8537. if first_assignment = nil then
  8538. first_assignment := hp3;
  8539. asml.InsertBefore(hp3, p);
  8540. { Make sure the compiler knows about any final registers written here }
  8541. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8542. with taicpu(hp3).oper[OperIdx]^ do
  8543. begin
  8544. case typ of
  8545. top_ref:
  8546. begin
  8547. if (ref^.base <> NR_NO) and
  8548. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8549. (
  8550. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8551. (
  8552. { Allow the frame pointer if it's not being used by the procedure as such }
  8553. Assigned(current_procinfo) and
  8554. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8555. )
  8556. )
  8557. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8558. then
  8559. begin
  8560. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8561. if not Assigned(first_assignment) then
  8562. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8563. end;
  8564. if (ref^.index <> NR_NO) and
  8565. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8566. (
  8567. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8568. (
  8569. { Allow the frame pointer if it's not being used by the procedure as such }
  8570. Assigned(current_procinfo) and
  8571. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8572. )
  8573. )
  8574. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8575. (ref^.index <> ref^.base) then
  8576. begin
  8577. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8578. if not Assigned(first_assignment) then
  8579. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8580. end;
  8581. end;
  8582. top_reg:
  8583. begin
  8584. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8585. if not Assigned(first_assignment) then
  8586. IncludeRegInUsedRegs(reg, UsedRegs);
  8587. end;
  8588. else
  8589. ;
  8590. end;
  8591. end;
  8592. end;
  8593. end;
  8594. else
  8595. InternalError(2021040720);
  8596. end;
  8597. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  8598. { Should have dropped out earlier }
  8599. InternalError(2021040710);
  8600. end;
  8601. end;
  8602. end;
  8603. const
  8604. WriteOp: array[0..3] of set of TInsChange = (
  8605. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8606. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8607. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8608. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8609. RegWriteFlags: array[0..7] of set of TInsChange = (
  8610. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8611. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8612. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8613. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8614. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8615. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8616. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8617. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8618. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8619. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8620. var
  8621. hp2: tai;
  8622. X: Integer;
  8623. begin
  8624. { If we have something like:
  8625. op ###,###
  8626. mov ###,###
  8627. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8628. interfere in regards to what they write to.
  8629. NOTE: p must be a 2-operand instruction
  8630. }
  8631. Result := False;
  8632. if (hp1.typ <> ait_instruction) or
  8633. taicpu(hp1).is_jmp or
  8634. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8635. Exit;
  8636. { NOP is a pipeline fence, likely marking the beginning of the function
  8637. epilogue, so drop out. Similarly, drop out if POP or RET are
  8638. encountered }
  8639. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8640. Exit;
  8641. if (taicpu(hp1).opcode = A_MOVSD) and
  8642. (taicpu(hp1).ops = 0) then
  8643. { Wrong MOVSD }
  8644. Exit;
  8645. { Check for writes to specific registers first }
  8646. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8647. for X := 0 to 7 do
  8648. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8649. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8650. Exit;
  8651. for X := 0 to taicpu(hp1).ops - 1 do
  8652. begin
  8653. { Check to see if this operand writes to something }
  8654. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8655. { And matches something in the CMP/TEST instruction }
  8656. (
  8657. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8658. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8659. (
  8660. { If it's a register, make sure the register written to doesn't
  8661. appear in the cmp instruction as part of a reference }
  8662. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8663. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8664. )
  8665. ) then
  8666. Exit;
  8667. end;
  8668. { Check p to make sure it doesn't write to something that affects hp1 }
  8669. { Check for writes to specific registers first }
  8670. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8671. for X := 0 to 7 do
  8672. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8673. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8674. Exit;
  8675. for X := 0 to taicpu(p).ops - 1 do
  8676. begin
  8677. { Check to see if this operand writes to something }
  8678. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8679. { And matches something in hp1 }
  8680. (taicpu(p).oper[X]^.typ = top_reg) and
  8681. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8682. Exit;
  8683. end;
  8684. { The instruction can be safely moved }
  8685. asml.Remove(hp1);
  8686. { Try to insert after the last instructions where the FLAGS register is not
  8687. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8688. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8689. asml.InsertBefore(hp1, hp2)
  8690. { Failing that, try to insert after the last instructions where the
  8691. FLAGS register is not yet in use }
  8692. else if GetLastInstruction(p, hp2) and
  8693. (
  8694. (hp2.typ <> ait_instruction) or
  8695. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8696. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8697. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8698. ) then
  8699. asml.InsertAfter(hp1, hp2)
  8700. else
  8701. { Note, if p.Previous is nil (even if it should logically never be the
  8702. case), FindRegAllocBackward immediately exits with False and so we
  8703. safely land here (we can't just pass p because FindRegAllocBackward
  8704. immediately exits on an instruction). [Kit] }
  8705. asml.InsertBefore(hp1, p);
  8706. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8707. { We can't trust UsedRegs because we're looking backwards, although we
  8708. know the registers are allocated after p at the very least, so manually
  8709. create tai_regalloc objects if needed }
  8710. for X := 0 to taicpu(hp1).ops - 1 do
  8711. case taicpu(hp1).oper[X]^.typ of
  8712. top_reg:
  8713. begin
  8714. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8715. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8716. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8717. end;
  8718. top_ref:
  8719. begin
  8720. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8721. begin
  8722. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8723. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8724. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8725. end;
  8726. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8727. begin
  8728. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8729. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8730. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8731. end;
  8732. end;
  8733. else
  8734. ;
  8735. end;
  8736. Result := True;
  8737. end;
  8738. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8739. var
  8740. hp2: tai;
  8741. X: Integer;
  8742. begin
  8743. { If we have something like:
  8744. cmp ###,%reg1
  8745. mov 0,%reg2
  8746. And no modified registers are shared, move the instruction to before
  8747. the comparison as this means it can be optimised without worrying
  8748. about the FLAGS register. (CMP/MOV is generated by
  8749. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8750. As long as the second instruction doesn't use the flags or one of the
  8751. registers used by CMP or TEST (also check any references that use the
  8752. registers), then it can be moved prior to the comparison.
  8753. }
  8754. Result := False;
  8755. if not TrySwapMovOp(p, hp1) then
  8756. Exit;
  8757. if taicpu(hp1).opcode = A_LEA then
  8758. { The flags will be overwritten by the CMP/TEST instruction }
  8759. ConvertLEA(taicpu(hp1));
  8760. Result := True;
  8761. { Can we move it one further back? }
  8762. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8763. { Check to see if CMP/TEST is a comparison against zero }
  8764. (
  8765. (
  8766. (taicpu(p).opcode = A_CMP) and
  8767. MatchOperand(taicpu(p).oper[0]^, 0)
  8768. ) or
  8769. (
  8770. (taicpu(p).opcode = A_TEST) and
  8771. (
  8772. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8773. MatchOperand(taicpu(p).oper[0]^, -1)
  8774. )
  8775. )
  8776. ) and
  8777. { These instructions set the zero flag if the result is zero }
  8778. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8779. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8780. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8781. TrySwapMovOp(hp2, hp1);
  8782. end;
  8783. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8784. var
  8785. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8786. JumpLabel: TAsmLabel;
  8787. TmpBool: Boolean;
  8788. begin
  8789. Result := False;
  8790. { Look for:
  8791. stc/clc
  8792. j(c) .L1
  8793. ...
  8794. .L1:
  8795. set(n)cb %reg
  8796. (flags deallocated)
  8797. j(c) .L2
  8798. Change to:
  8799. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8800. j(c) .L2
  8801. }
  8802. p_last := p;
  8803. while GetNextInstruction(p_last, hp1) and
  8804. (hp1.typ = ait_instruction) and
  8805. IsJumpToLabel(taicpu(hp1)) do
  8806. begin
  8807. if DoJumpOptimizations(hp1, TmpBool) then
  8808. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8809. Continue;
  8810. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8811. if not Assigned(JumpLabel) then
  8812. InternalError(2024012801);
  8813. { Optimise the J(c); stc/clc optimisation first since this will
  8814. get missed if the main optimisation takes place }
  8815. if (taicpu(hp1).opcode = A_JCC) then
  8816. begin
  8817. if GetNextInstruction(hp1, hp2) and
  8818. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8819. TryJccStcClcOpt(hp1, hp2) then
  8820. begin
  8821. Result := True;
  8822. Exit;
  8823. end;
  8824. hp2 := nil; { Suppress compiler warning }
  8825. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8826. { Make sure the flags aren't used again }
  8827. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8828. begin
  8829. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8830. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8831. begin
  8832. if (taicpu(p).opcode = A_STC) then
  8833. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8834. else
  8835. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8836. MakeUnconditional(taicpu(hp1));
  8837. { Move the jump to after the flag deallocations }
  8838. Asml.Remove(hp1);
  8839. Asml.InsertAfter(hp1, hp2);
  8840. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8841. Result := True;
  8842. Exit;
  8843. end
  8844. else
  8845. begin
  8846. if (taicpu(p).opcode = A_STC) then
  8847. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8848. else
  8849. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8850. { In this case, the jump is deterministic in that it will never be taken }
  8851. JumpLabel.DecRefs;
  8852. RemoveInstruction(hp1);
  8853. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8854. Result := True;
  8855. Exit;
  8856. end;
  8857. end;
  8858. end;
  8859. hp2 := nil; { Suppress compiler warning }
  8860. if
  8861. { Make sure the carry flag doesn't appear in the jump conditions }
  8862. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8863. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8864. GetNextInstruction(hp2, p_dist) and
  8865. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8866. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8867. begin
  8868. case taicpu(p_dist).opcode of
  8869. A_Jcc:
  8870. begin
  8871. if DoJumpOptimizations(p_dist, TmpBool) then
  8872. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8873. Continue;
  8874. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8875. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8876. begin
  8877. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8878. JumpLabel.decrefs;
  8879. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8880. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8881. Result := True;
  8882. Exit;
  8883. end
  8884. else if GetNextInstruction(p_dist, hp1_dist) and
  8885. (hp1_dist.typ = ait_label) then
  8886. begin
  8887. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8888. JumpLabel.decrefs;
  8889. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8890. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8891. Result := True;
  8892. Exit;
  8893. end;
  8894. end;
  8895. A_SETcc:
  8896. if { Make sure the flags aren't used again }
  8897. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8898. GetNextInstruction(hp2, hp1_dist) and
  8899. (hp1_dist.typ = ait_instruction) and
  8900. IsJumpToLabel(taicpu(hp1_dist)) and
  8901. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8902. { This works if hp1_dist or both are regular JMP instructions }
  8903. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  8904. (
  8905. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  8906. { Make sure the register isn't still in use, otherwise it
  8907. may get corrupted (fixes #40659) }
  8908. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  8909. ) then
  8910. begin
  8911. taicpu(p).allocate_oper(2);
  8912. taicpu(p).ops := 2;
  8913. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8914. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8915. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8916. taicpu(p).opcode := A_MOV;
  8917. taicpu(p).opsize := S_B;
  8918. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8919. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8920. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8921. JumpLabel.decrefs;
  8922. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8923. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8924. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  8925. (tai_regalloc(hp2).ratype = ra_alloc) then
  8926. begin
  8927. Asml.Remove(hp2);
  8928. Asml.InsertAfter(hp2, p);
  8929. end;
  8930. Result := True;
  8931. Exit;
  8932. end;
  8933. else
  8934. ;
  8935. end;
  8936. end;
  8937. p_last := hp1;
  8938. end;
  8939. end;
  8940. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8941. var
  8942. hp2, hp3: tai;
  8943. TempBool: Boolean;
  8944. begin
  8945. Result := False;
  8946. {
  8947. j(c) .L1
  8948. stc/clc
  8949. .L1:
  8950. jc/jnc .L2
  8951. (Flags deallocated)
  8952. Change to:
  8953. j)c) .L1
  8954. jmp .L2
  8955. .L1:
  8956. jc/jnc .L2
  8957. Then call DoJumpOptimizations to convert to:
  8958. j(nc) .L2
  8959. .L1: (may become a dead label)
  8960. jc/jnc .L2
  8961. }
  8962. if GetNextInstruction(hp1, hp2) and
  8963. (hp2.typ = ait_label) and
  8964. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8965. GetNextInstruction(hp2, hp3) and
  8966. MatchInstruction(hp3, A_Jcc, []) and
  8967. (
  8968. (
  8969. (taicpu(hp3).condition = C_C) and
  8970. (taicpu(hp1).opcode = A_STC)
  8971. ) or (
  8972. (taicpu(hp3).condition = C_NC) and
  8973. (taicpu(hp1).opcode = A_CLC)
  8974. )
  8975. ) and
  8976. { Make sure the flags aren't used again }
  8977. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  8978. begin
  8979. taicpu(hp1).allocate_oper(1);
  8980. taicpu(hp1).ops := 1;
  8981. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  8982. taicpu(hp1).opcode := A_JMP;
  8983. taicpu(hp1).is_jmp := True;
  8984. TempBool := True; { Prevent compiler warnings }
  8985. if DoJumpOptimizations(p, TempBool) then
  8986. Result := True
  8987. else
  8988. Include(OptsToCheck, aoc_ForceNewIteration);
  8989. end;
  8990. end;
  8991. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  8992. begin
  8993. { This generally only executes under -O3 and above }
  8994. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  8995. end;
  8996. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  8997. var
  8998. hp1, hp2: tai;
  8999. FoundComparison: Boolean;
  9000. begin
  9001. { Run the pass 1 optimisations as well, since they may have some effect
  9002. after the CMOV blocks are created in OptPass2Jcc }
  9003. Result := False;
  9004. { Result := OptPass1CMOVcc(p);
  9005. if Result then
  9006. Exit;}
  9007. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  9008. and make a slightly inefficent result on branching-type blocks, notably
  9009. when setting a function result then jumping to the function epilogue.
  9010. In this case, change:
  9011. cmov(c) %reg1,%reg2
  9012. j(c) @lbl
  9013. (%reg2 deallocated)
  9014. To:
  9015. mov %reg11,%reg2
  9016. j(c) @lbl
  9017. Note, we can't use GetNextInstructionUsingReg to find the conditional
  9018. jump because if it's not present, we may end up with a jump that's
  9019. completely unrelated.
  9020. }
  9021. hp1 := p;
  9022. while GetNextInstruction(hp1, hp1) and
  9023. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  9024. if (hp1.typ = ait_instruction) and
  9025. (taicpu(hp1).opcode = A_Jcc) and
  9026. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  9027. begin
  9028. TransferUsedRegs(TmpUsedRegs);
  9029. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  9030. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  9031. (
  9032. { See if we can find a more distant instruction that overwrites
  9033. the destination register }
  9034. (cs_opt_level3 in current_settings.optimizerswitches) and
  9035. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9036. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9037. ) then
  9038. begin
  9039. if (taicpu(p).oper[0]^.typ = top_reg) then
  9040. begin
  9041. { Search backwards to see if the source register is set to a
  9042. constant }
  9043. FoundComparison := False;
  9044. hp1 := p;
  9045. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9046. begin
  9047. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9048. begin
  9049. FoundComparison := True;
  9050. Continue;
  9051. end;
  9052. { Once we find the CMP, TEST or similar instruction, we
  9053. have to stop if we find anything other than a MOV }
  9054. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9055. Break;
  9056. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9057. { Destination register was modified }
  9058. Break;
  9059. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9060. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9061. begin
  9062. { Found a constant! }
  9063. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9064. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9065. { The source register is no longer in use }
  9066. RemoveInstruction(hp1);
  9067. Break;
  9068. end;
  9069. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9070. { Some other instruction has modified the source register }
  9071. Break;
  9072. end;
  9073. end;
  9074. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9075. taicpu(p).opcode := A_MOV;
  9076. taicpu(p).condition := C_None;
  9077. { Rely on the post peephole stage to put the MOV before the
  9078. CMP/TEST instruction that appears prior }
  9079. Result := True;
  9080. Exit;
  9081. end;
  9082. end;
  9083. end;
  9084. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9085. function IsXCHGAcceptable: Boolean; inline;
  9086. begin
  9087. { Always accept if optimising for size }
  9088. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9089. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9090. than 3, so it becomes a saving compared to three MOVs with two of
  9091. them able to execute simultaneously. [Kit] }
  9092. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9093. end;
  9094. var
  9095. NewRef: TReference;
  9096. hp1, hp2, hp3, hp4: Tai;
  9097. {$ifndef x86_64}
  9098. OperIdx: Integer;
  9099. {$endif x86_64}
  9100. NewInstr : Taicpu;
  9101. NewAligh : Tai_align;
  9102. DestLabel: TAsmLabel;
  9103. TempTracking: TAllUsedRegs;
  9104. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9105. var
  9106. NextInstr: tai;
  9107. begin
  9108. Result := False;
  9109. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9110. if not GetNextInstruction(InputInstr, NextInstr) or
  9111. (
  9112. { The FLAGS register isn't always tracked properly, so do not
  9113. perform this optimisation if a conditional statement follows }
  9114. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9115. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9116. ) then
  9117. begin
  9118. reference_reset(NewRef, 1, []);
  9119. NewRef.base := taicpu(p).oper[0]^.reg;
  9120. NewRef.scalefactor := 1;
  9121. if taicpu(InputInstr).opcode = A_ADD then
  9122. begin
  9123. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9124. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9125. end
  9126. else
  9127. begin
  9128. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9129. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9130. end;
  9131. taicpu(p).opcode := A_LEA;
  9132. taicpu(p).loadref(0, NewRef);
  9133. { For the sake of debugging, have the line info match the
  9134. arithmetic instruction rather than the MOV instruction }
  9135. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9136. RemoveInstruction(InputInstr);
  9137. Result := True;
  9138. end;
  9139. end;
  9140. begin
  9141. Result:=false;
  9142. { This optimisation adds an instruction, so only do it for speed }
  9143. if not (cs_opt_size in current_settings.optimizerswitches) and
  9144. MatchOpType(taicpu(p), top_const, top_reg) and
  9145. (taicpu(p).oper[0]^.val = 0) then
  9146. begin
  9147. { To avoid compiler warning }
  9148. DestLabel := nil;
  9149. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9150. InternalError(2021040750);
  9151. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9152. Exit;
  9153. case hp1.typ of
  9154. ait_label:
  9155. begin
  9156. { Change:
  9157. mov $0,%reg mov $0,%reg
  9158. @Lbl1: @Lbl1:
  9159. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9160. je @Lbl2 jne @Lbl2
  9161. To: To:
  9162. mov $0,%reg mov $0,%reg
  9163. jmp @Lbl2 jmp @Lbl3
  9164. (align) (align)
  9165. @Lbl1: @Lbl1:
  9166. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9167. je @Lbl2 je @Lbl2
  9168. @Lbl3: <-- Only if label exists
  9169. (Not if it's optimised for size)
  9170. }
  9171. if not GetNextInstruction(hp1, hp2) then
  9172. Exit;
  9173. if (hp2.typ = ait_instruction) and
  9174. (
  9175. { Register sizes must exactly match }
  9176. (
  9177. (taicpu(hp2).opcode = A_CMP) and
  9178. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9179. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9180. ) or (
  9181. (taicpu(hp2).opcode = A_TEST) and
  9182. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9183. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9184. )
  9185. ) and GetNextInstruction(hp2, hp3) and
  9186. (hp3.typ = ait_instruction) and
  9187. (taicpu(hp3).opcode = A_JCC) and
  9188. (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
  9189. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9190. begin
  9191. { Check condition of jump }
  9192. { Always true? }
  9193. if condition_in(C_E, taicpu(hp3).condition) then
  9194. begin
  9195. { Copy label symbol and obtain matching label entry for the
  9196. conditional jump, as this will be our destination}
  9197. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9198. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9199. Result := True;
  9200. end
  9201. { Always false? }
  9202. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9203. begin
  9204. { This is only worth it if there's a jump to take }
  9205. case hp2.typ of
  9206. ait_instruction:
  9207. begin
  9208. if taicpu(hp2).opcode = A_JMP then
  9209. begin
  9210. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9211. { An unconditional jump follows the conditional jump which will always be false,
  9212. so use this jump's destination for the new jump }
  9213. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9214. Result := True;
  9215. end
  9216. else if taicpu(hp2).opcode = A_JCC then
  9217. begin
  9218. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9219. if condition_in(C_E, taicpu(hp2).condition) then
  9220. begin
  9221. { A second conditional jump follows the conditional jump which will always be false,
  9222. while the second jump is always True, so use this jump's destination for the new jump }
  9223. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9224. Result := True;
  9225. end;
  9226. { Don't risk it if the jump isn't always true (Result remains False) }
  9227. end;
  9228. end;
  9229. else
  9230. { If anything else don't optimise };
  9231. end;
  9232. end;
  9233. if Result then
  9234. begin
  9235. { Just so we have something to insert as a paremeter}
  9236. reference_reset(NewRef, 1, []);
  9237. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9238. { Now actually load the correct parameter (this also
  9239. increases the reference count) }
  9240. NewInstr.loadsymbol(0, DestLabel, 0);
  9241. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9242. begin
  9243. { Get instruction before original label (may not be p under -O3) }
  9244. if not GetLastInstruction(hp1, hp2) then
  9245. { Shouldn't fail here }
  9246. InternalError(2021040701);
  9247. end
  9248. else
  9249. hp2 := p;
  9250. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9251. AsmL.InsertAfter(NewInstr, hp2);
  9252. { Add new alignment field }
  9253. (* AsmL.InsertAfter(
  9254. cai_align.create_max(
  9255. current_settings.alignment.jumpalign,
  9256. current_settings.alignment.jumpalignskipmax
  9257. ),
  9258. NewInstr
  9259. ); *)
  9260. end;
  9261. Exit;
  9262. end;
  9263. end;
  9264. else
  9265. ;
  9266. end;
  9267. end;
  9268. if not GetNextInstruction(p, hp1) then
  9269. Exit;
  9270. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9271. begin
  9272. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9273. begin
  9274. Result := True;
  9275. Exit;
  9276. end;
  9277. { This optimisation is only effective on a second run of Pass 2,
  9278. hence -O3 or above.
  9279. Change:
  9280. mov %reg1,%reg2
  9281. cmp/test (contains %reg1)
  9282. mov x, %reg1
  9283. (another mov or a j(c))
  9284. To:
  9285. mov %reg1,%reg2
  9286. mov x, %reg1
  9287. cmp (%reg1 replaced with %reg2)
  9288. (another mov or a j(c))
  9289. The requirement of an additional MOV or a jump ensures there
  9290. isn't performance loss, since a j(c) will permit macro-fusion
  9291. with the cmp instruction, while another MOV likely means it's
  9292. not all being executed in a single cycle due to parallelisation.
  9293. }
  9294. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9295. MatchOpType(taicpu(p), top_reg, top_reg) and
  9296. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9297. GetNextInstruction(hp1, hp2) and
  9298. MatchInstruction(hp2, A_MOV, []) and
  9299. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9300. { Registers don't have to be the same size in this case }
  9301. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9302. GetNextInstruction(hp2, hp3) and
  9303. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9304. { Make sure the operands in the camparison can be safely replaced }
  9305. (
  9306. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9307. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9308. ) and
  9309. (
  9310. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9311. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9312. ) then
  9313. begin
  9314. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9315. AsmL.Remove(hp2);
  9316. AsmL.InsertAfter(hp2, p);
  9317. Result := True;
  9318. Exit;
  9319. end;
  9320. end;
  9321. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9322. begin
  9323. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9324. further, but we can't just put this jump optimisation in pass 1
  9325. because it tends to perform worse when conditional jumps are
  9326. nearby (e.g. when converting CMOV instructions). [Kit] }
  9327. CopyUsedRegs(TempTracking);
  9328. UpdateUsedRegs(tai(p.Next));
  9329. if OptPass2JMP(hp1) then
  9330. begin
  9331. { Restore register state }
  9332. RestoreUsedRegs(TempTracking);
  9333. ReleaseUsedRegs(TempTracking);
  9334. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9335. OptPass1MOV(p);
  9336. Result := True;
  9337. Exit;
  9338. end;
  9339. { If OptPass2JMP returned False, no optimisations were done to
  9340. the jump and there are no further optimisations that can be done
  9341. to the MOV instruction on this pass other than FuncMov2Func }
  9342. { Restore register state }
  9343. RestoreUsedRegs(TempTracking);
  9344. ReleaseUsedRegs(TempTracking);
  9345. Result := FuncMov2Func(p, hp1);
  9346. Exit;
  9347. end;
  9348. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9349. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9350. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9351. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9352. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9353. begin
  9354. { Change:
  9355. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9356. addl/q $x,%reg2 subl/q $x,%reg2
  9357. To:
  9358. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9359. }
  9360. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9361. { be lazy, checking separately for sub would be slightly better }
  9362. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9363. begin
  9364. TransferUsedRegs(TmpUsedRegs);
  9365. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9366. if TryMovArith2Lea(hp1) then
  9367. begin
  9368. Result := True;
  9369. Exit;
  9370. end
  9371. end
  9372. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9373. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9374. { Same as above, but also adds or subtracts to %reg2 in between.
  9375. It's still valid as long as the flags aren't in use }
  9376. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9377. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9378. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9379. { be lazy, checking separately for sub would be slightly better }
  9380. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9381. begin
  9382. TransferUsedRegs(TmpUsedRegs);
  9383. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9384. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9385. if TryMovArith2Lea(hp2) then
  9386. begin
  9387. Result := True;
  9388. Exit;
  9389. end;
  9390. end;
  9391. end;
  9392. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9393. {$ifdef x86_64}
  9394. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9395. {$else x86_64}
  9396. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9397. {$endif x86_64}
  9398. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9399. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9400. { mov reg1, reg2 mov reg1, reg2
  9401. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9402. begin
  9403. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9404. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9405. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9406. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9407. TransferUsedRegs(TmpUsedRegs);
  9408. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9409. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9410. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9411. then
  9412. begin
  9413. RemoveCurrentP(p, hp1);
  9414. Result:=true;
  9415. end;
  9416. Exit;
  9417. end;
  9418. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9419. IsXCHGAcceptable and
  9420. { XCHG doesn't support 8-bit registers }
  9421. (taicpu(p).opsize <> S_B) and
  9422. MatchInstruction(hp1, A_MOV, []) and
  9423. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9424. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9425. GetNextInstruction(hp1, hp2) and
  9426. MatchInstruction(hp2, A_MOV, []) and
  9427. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9428. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9429. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9430. begin
  9431. { mov %reg1,%reg2
  9432. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9433. mov %reg2,%reg3
  9434. (%reg2 not used afterwards)
  9435. Note that xchg takes 3 cycles to execute, and generally mov's take
  9436. only one cycle apiece, but the first two mov's can be executed in
  9437. parallel, only taking 2 cycles overall. Older processors should
  9438. therefore only optimise for size. [Kit]
  9439. }
  9440. TransferUsedRegs(TmpUsedRegs);
  9441. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9442. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9443. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9444. begin
  9445. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9446. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9447. taicpu(hp1).opcode := A_XCHG;
  9448. RemoveCurrentP(p, hp1);
  9449. RemoveInstruction(hp2);
  9450. Result := True;
  9451. Exit;
  9452. end;
  9453. end;
  9454. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9455. MatchInstruction(hp1, A_SAR, []) then
  9456. begin
  9457. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9458. begin
  9459. { the use of %edx also covers the opsize being S_L }
  9460. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9461. begin
  9462. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9463. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9464. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9465. begin
  9466. { Change:
  9467. movl %eax,%edx
  9468. sarl $31,%edx
  9469. To:
  9470. cltd
  9471. }
  9472. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9473. RemoveInstruction(hp1);
  9474. taicpu(p).opcode := A_CDQ;
  9475. taicpu(p).opsize := S_NO;
  9476. taicpu(p).clearop(1);
  9477. taicpu(p).clearop(0);
  9478. taicpu(p).ops:=0;
  9479. Result := True;
  9480. Exit;
  9481. end
  9482. else if (cs_opt_size in current_settings.optimizerswitches) and
  9483. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9484. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9485. begin
  9486. { Change:
  9487. movl %edx,%eax
  9488. sarl $31,%edx
  9489. To:
  9490. movl %edx,%eax
  9491. cltd
  9492. Note that this creates a dependency between the two instructions,
  9493. so only perform if optimising for size.
  9494. }
  9495. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9496. taicpu(hp1).opcode := A_CDQ;
  9497. taicpu(hp1).opsize := S_NO;
  9498. taicpu(hp1).clearop(1);
  9499. taicpu(hp1).clearop(0);
  9500. taicpu(hp1).ops:=0;
  9501. Include(OptsToCheck, aoc_ForceNewIteration);
  9502. Exit;
  9503. end;
  9504. {$ifndef x86_64}
  9505. end
  9506. { Don't bother if CMOV is supported, because a more optimal
  9507. sequence would have been generated for the Abs() intrinsic }
  9508. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9509. { the use of %eax also covers the opsize being S_L }
  9510. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9511. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9512. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9513. GetNextInstruction(hp1, hp2) and
  9514. MatchInstruction(hp2, A_XOR, [S_L]) and
  9515. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9516. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9517. GetNextInstruction(hp2, hp3) and
  9518. MatchInstruction(hp3, A_SUB, [S_L]) and
  9519. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9520. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9521. begin
  9522. { Change:
  9523. movl %eax,%edx
  9524. sarl $31,%eax
  9525. xorl %eax,%edx
  9526. subl %eax,%edx
  9527. (Instruction that uses %edx)
  9528. (%eax deallocated)
  9529. (%edx deallocated)
  9530. To:
  9531. cltd
  9532. xorl %edx,%eax <-- Note the registers have swapped
  9533. subl %edx,%eax
  9534. (Instruction that uses %eax) <-- %eax rather than %edx
  9535. }
  9536. TransferUsedRegs(TmpUsedRegs);
  9537. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9538. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9539. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9540. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9541. begin
  9542. if GetNextInstruction(hp3, hp4) and
  9543. not RegModifiedByInstruction(NR_EDX, hp4) and
  9544. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9545. begin
  9546. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9547. taicpu(p).opcode := A_CDQ;
  9548. taicpu(p).clearop(1);
  9549. taicpu(p).clearop(0);
  9550. taicpu(p).ops:=0;
  9551. RemoveInstruction(hp1);
  9552. taicpu(hp2).loadreg(0, NR_EDX);
  9553. taicpu(hp2).loadreg(1, NR_EAX);
  9554. taicpu(hp3).loadreg(0, NR_EDX);
  9555. taicpu(hp3).loadreg(1, NR_EAX);
  9556. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9557. { Convert references in the following instruction (hp4) from %edx to %eax }
  9558. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9559. with taicpu(hp4).oper[OperIdx]^ do
  9560. case typ of
  9561. top_reg:
  9562. if getsupreg(reg) = RS_EDX then
  9563. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9564. top_ref:
  9565. begin
  9566. if getsupreg(reg) = RS_EDX then
  9567. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9568. if getsupreg(reg) = RS_EDX then
  9569. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9570. end;
  9571. else
  9572. ;
  9573. end;
  9574. Result := True;
  9575. Exit;
  9576. end;
  9577. end;
  9578. {$else x86_64}
  9579. end;
  9580. end
  9581. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9582. { the use of %rdx also covers the opsize being S_Q }
  9583. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9584. begin
  9585. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9586. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9587. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9588. begin
  9589. { Change:
  9590. movq %rax,%rdx
  9591. sarq $63,%rdx
  9592. To:
  9593. cqto
  9594. }
  9595. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9596. RemoveInstruction(hp1);
  9597. taicpu(p).opcode := A_CQO;
  9598. taicpu(p).opsize := S_NO;
  9599. taicpu(p).clearop(1);
  9600. taicpu(p).clearop(0);
  9601. taicpu(p).ops:=0;
  9602. Result := True;
  9603. Exit;
  9604. end
  9605. else if (cs_opt_size in current_settings.optimizerswitches) and
  9606. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9607. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9608. begin
  9609. { Change:
  9610. movq %rdx,%rax
  9611. sarq $63,%rdx
  9612. To:
  9613. movq %rdx,%rax
  9614. cqto
  9615. Note that this creates a dependency between the two instructions,
  9616. so only perform if optimising for size.
  9617. }
  9618. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9619. taicpu(hp1).opcode := A_CQO;
  9620. taicpu(hp1).opsize := S_NO;
  9621. taicpu(hp1).clearop(1);
  9622. taicpu(hp1).clearop(0);
  9623. taicpu(hp1).ops:=0;
  9624. Include(OptsToCheck, aoc_ForceNewIteration);
  9625. Exit;
  9626. {$endif x86_64}
  9627. end;
  9628. end;
  9629. end;
  9630. if MatchInstruction(hp1, A_MOV, []) and
  9631. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9632. { Though "GetNextInstruction" could be factored out, along with
  9633. the instructions that depend on hp2, it is an expensive call that
  9634. should be delayed for as long as possible, hence we do cheaper
  9635. checks first that are likely to be False. [Kit] }
  9636. begin
  9637. if (
  9638. (
  9639. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9640. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9641. (
  9642. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9643. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9644. )
  9645. ) or
  9646. (
  9647. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9648. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9649. (
  9650. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9651. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9652. )
  9653. )
  9654. ) and
  9655. GetNextInstruction(hp1, hp2) and
  9656. MatchInstruction(hp2, A_SAR, []) and
  9657. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9658. begin
  9659. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9660. begin
  9661. { Change:
  9662. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9663. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9664. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9665. To:
  9666. movl r/m,%eax <- Note the change in register
  9667. cltd
  9668. }
  9669. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9670. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9671. taicpu(p).loadreg(1, NR_EAX);
  9672. taicpu(hp1).opcode := A_CDQ;
  9673. taicpu(hp1).clearop(1);
  9674. taicpu(hp1).clearop(0);
  9675. taicpu(hp1).ops:=0;
  9676. RemoveInstruction(hp2);
  9677. Include(OptsToCheck, aoc_ForceNewIteration);
  9678. (*
  9679. {$ifdef x86_64}
  9680. end
  9681. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9682. { This code sequence does not get generated - however it might become useful
  9683. if and when 128-bit signed integer types make an appearance, so the code
  9684. is kept here for when it is eventually needed. [Kit] }
  9685. (
  9686. (
  9687. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9688. (
  9689. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9690. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9691. )
  9692. ) or
  9693. (
  9694. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9695. (
  9696. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9697. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9698. )
  9699. )
  9700. ) and
  9701. GetNextInstruction(hp1, hp2) and
  9702. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9703. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9704. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9705. begin
  9706. { Change:
  9707. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9708. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9709. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9710. To:
  9711. movq r/m,%rax <- Note the change in register
  9712. cqto
  9713. }
  9714. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9715. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9716. taicpu(p).loadreg(1, NR_RAX);
  9717. taicpu(hp1).opcode := A_CQO;
  9718. taicpu(hp1).clearop(1);
  9719. taicpu(hp1).clearop(0);
  9720. taicpu(hp1).ops:=0;
  9721. RemoveInstruction(hp2);
  9722. Include(OptsToCheck, aoc_ForceNewIteration);
  9723. {$endif x86_64}
  9724. *)
  9725. end;
  9726. end;
  9727. {$ifdef x86_64}
  9728. end;
  9729. if (taicpu(p).opsize = S_L) and
  9730. (taicpu(p).oper[1]^.typ = top_reg) and
  9731. (
  9732. MatchInstruction(hp1, A_MOV,[]) and
  9733. (taicpu(hp1).opsize = S_L) and
  9734. (taicpu(hp1).oper[1]^.typ = top_reg)
  9735. ) and (
  9736. GetNextInstruction(hp1, hp2) and
  9737. (tai(hp2).typ=ait_instruction) and
  9738. (taicpu(hp2).opsize = S_Q) and
  9739. (
  9740. (
  9741. MatchInstruction(hp2, A_ADD,[]) and
  9742. (taicpu(hp2).opsize = S_Q) and
  9743. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9744. (
  9745. (
  9746. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9747. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9748. ) or (
  9749. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9750. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9751. )
  9752. )
  9753. ) or (
  9754. MatchInstruction(hp2, A_LEA,[]) and
  9755. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9756. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9757. (
  9758. (
  9759. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9760. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9761. ) or (
  9762. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9763. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9764. )
  9765. ) and (
  9766. (
  9767. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9768. ) or (
  9769. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9770. )
  9771. )
  9772. )
  9773. )
  9774. ) and (
  9775. GetNextInstruction(hp2, hp3) and
  9776. MatchInstruction(hp3, A_SHR,[]) and
  9777. (taicpu(hp3).opsize = S_Q) and
  9778. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9779. (taicpu(hp3).oper[0]^.val = 1) and
  9780. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9781. ) then
  9782. begin
  9783. { Change movl x, reg1d movl x, reg1d
  9784. movl y, reg2d movl y, reg2d
  9785. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9786. shrq $1, reg1q shrq $1, reg1q
  9787. ( reg1d and reg2d can be switched around in the first two instructions )
  9788. To movl x, reg1d
  9789. addl y, reg1d
  9790. rcrl $1, reg1d
  9791. This corresponds to the common expression (x + y) shr 1, where
  9792. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9793. smaller code, but won't account for x + y causing an overflow). [Kit]
  9794. }
  9795. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9796. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9797. begin
  9798. { Change first MOV command to have the same register as the final output }
  9799. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9800. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  9801. Result := True;
  9802. end
  9803. else
  9804. begin
  9805. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9806. Include(OptsToCheck, aoc_ForceNewIteration);
  9807. end;
  9808. { Change second MOV command to an ADD command. This is easier than
  9809. converting the existing command because it means we don't have to
  9810. touch 'y', which might be a complicated reference, and also the
  9811. fact that the third command might either be ADD or LEA. [Kit] }
  9812. taicpu(hp1).opcode := A_ADD;
  9813. { Delete old ADD/LEA instruction }
  9814. RemoveInstruction(hp2);
  9815. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9816. taicpu(hp3).opcode := A_RCR;
  9817. taicpu(hp3).changeopsize(S_L);
  9818. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9819. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  9820. called, so FuncMov2Func below is safe to call }
  9821. {$endif x86_64}
  9822. end;
  9823. if FuncMov2Func(p, hp1) then
  9824. begin
  9825. Result := True;
  9826. Exit;
  9827. end;
  9828. end;
  9829. {$push}
  9830. {$q-}{$r-}
  9831. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9832. var
  9833. ThisReg: TRegister;
  9834. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9835. TargetSubReg: TSubRegister;
  9836. hp1, hp2: tai;
  9837. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9838. { Store list of found instructions so we don't have to call
  9839. GetNextInstructionUsingReg multiple times }
  9840. InstrList: array of taicpu;
  9841. InstrMax, Index: Integer;
  9842. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9843. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9844. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9845. WorkingValue: TCgInt;
  9846. PreMessage: string;
  9847. { Data flow analysis }
  9848. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9849. BitwiseOnly, OrXorUsed,
  9850. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9851. function CheckOverflowConditions: Boolean;
  9852. begin
  9853. Result := True;
  9854. if (TestValSignedMax > SignedUpperLimit) then
  9855. UpperSignedOverflow := True;
  9856. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9857. LowerSignedOverflow := True;
  9858. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9859. LowerUnsignedOverflow := True;
  9860. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9861. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9862. begin
  9863. { Absolute overflow }
  9864. Result := False;
  9865. Exit;
  9866. end;
  9867. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9868. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9869. ShiftDownOverflow := True;
  9870. if (TestValMin < 0) or (TestValMax < 0) then
  9871. begin
  9872. LowerUnsignedOverflow := True;
  9873. UpperUnsignedOverflow := True;
  9874. end;
  9875. end;
  9876. function AdjustInitialLoadAndSize: Boolean;
  9877. begin
  9878. Result := False;
  9879. if not p_removed then
  9880. begin
  9881. if TargetSize = MinSize then
  9882. begin
  9883. { Convert the input MOVZX to a MOV }
  9884. if (taicpu(p).oper[0]^.typ = top_reg) and
  9885. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9886. begin
  9887. { Or remove it completely! }
  9888. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9889. RemoveCurrentP(p);
  9890. p_removed := True;
  9891. end
  9892. else
  9893. begin
  9894. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9895. taicpu(p).opcode := A_MOV;
  9896. taicpu(p).oper[1]^.reg := ThisReg;
  9897. taicpu(p).opsize := TargetSize;
  9898. end;
  9899. Result := True;
  9900. end
  9901. else if TargetSize <> MaxSize then
  9902. begin
  9903. case MaxSize of
  9904. S_L:
  9905. if TargetSize = S_W then
  9906. begin
  9907. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9908. taicpu(p).opsize := S_BW;
  9909. taicpu(p).oper[1]^.reg := ThisReg;
  9910. Result := True;
  9911. end
  9912. else
  9913. InternalError(2020112341);
  9914. S_W:
  9915. if TargetSize = S_L then
  9916. begin
  9917. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9918. taicpu(p).opsize := S_BL;
  9919. taicpu(p).oper[1]^.reg := ThisReg;
  9920. Result := True;
  9921. end
  9922. else
  9923. InternalError(2020112342);
  9924. else
  9925. ;
  9926. end;
  9927. end
  9928. else if not hp1_removed and not RegInUse then
  9929. begin
  9930. { If we have something like:
  9931. movzbl (oper),%regd
  9932. add x, %regd
  9933. movzbl %regb, %regd
  9934. We can reduce the register size to the input of the final
  9935. movzbl instruction. Overflows won't have any effect.
  9936. }
  9937. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9938. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9939. begin
  9940. TargetSize := S_B;
  9941. setsubreg(ThisReg, R_SUBL);
  9942. Result := True;
  9943. end
  9944. else if (taicpu(p).opsize = S_WL) and
  9945. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9946. begin
  9947. TargetSize := S_W;
  9948. setsubreg(ThisReg, R_SUBW);
  9949. Result := True;
  9950. end;
  9951. if Result then
  9952. begin
  9953. { Convert the input MOVZX to a MOV }
  9954. if (taicpu(p).oper[0]^.typ = top_reg) and
  9955. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9956. begin
  9957. { Or remove it completely! }
  9958. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9959. RemoveCurrentP(p);
  9960. p_removed := True;
  9961. end
  9962. else
  9963. begin
  9964. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9965. taicpu(p).opcode := A_MOV;
  9966. taicpu(p).oper[1]^.reg := ThisReg;
  9967. taicpu(p).opsize := TargetSize;
  9968. end;
  9969. end;
  9970. end;
  9971. end;
  9972. end;
  9973. procedure AdjustFinalLoad;
  9974. begin
  9975. if not LowerUnsignedOverflow then
  9976. begin
  9977. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9978. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9979. begin
  9980. { Convert the output MOVZX to a MOV }
  9981. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9982. begin
  9983. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9984. if (MinSize = S_B) or
  9985. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9986. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9987. begin
  9988. { Remove it completely! }
  9989. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9990. { Be careful; if p = hp1 and p was also removed, p
  9991. will become a dangling pointer }
  9992. if p = hp1 then
  9993. begin
  9994. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9995. p_removed := True;
  9996. end
  9997. else
  9998. RemoveInstruction(hp1);
  9999. hp1_removed := True;
  10000. end;
  10001. end
  10002. else
  10003. begin
  10004. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  10005. taicpu(hp1).opcode := A_MOV;
  10006. taicpu(hp1).oper[0]^.reg := ThisReg;
  10007. taicpu(hp1).opsize := TargetSize;
  10008. end;
  10009. end
  10010. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  10011. begin
  10012. { Need to change the size of the output }
  10013. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  10014. taicpu(hp1).oper[0]^.reg := ThisReg;
  10015. taicpu(hp1).opsize := S_BL;
  10016. end;
  10017. end;
  10018. end;
  10019. function CompressInstructions: Boolean;
  10020. var
  10021. LocalIndex: Integer;
  10022. begin
  10023. Result := False;
  10024. { The objective here is to try to find a combination that
  10025. removes one of the MOV/Z instructions. }
  10026. if (
  10027. (taicpu(p).oper[0]^.typ <> top_reg) or
  10028. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  10029. ) and
  10030. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10031. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10032. begin
  10033. { Make a preference to remove the second MOVZX instruction }
  10034. case taicpu(hp1).opsize of
  10035. S_BL, S_WL:
  10036. begin
  10037. TargetSize := S_L;
  10038. TargetSubReg := R_SUBD;
  10039. end;
  10040. S_BW:
  10041. begin
  10042. TargetSize := S_W;
  10043. TargetSubReg := R_SUBW;
  10044. end;
  10045. else
  10046. InternalError(2020112302);
  10047. end;
  10048. end
  10049. else
  10050. begin
  10051. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10052. begin
  10053. { Exceeded lower bound but not upper bound }
  10054. TargetSize := MaxSize;
  10055. end
  10056. else if not LowerUnsignedOverflow then
  10057. begin
  10058. { Size didn't exceed lower bound }
  10059. TargetSize := MinSize;
  10060. end
  10061. else
  10062. Exit;
  10063. end;
  10064. case TargetSize of
  10065. S_B:
  10066. TargetSubReg := R_SUBL;
  10067. S_W:
  10068. TargetSubReg := R_SUBW;
  10069. S_L:
  10070. TargetSubReg := R_SUBD;
  10071. else
  10072. InternalError(2020112350);
  10073. end;
  10074. { Update the register to its new size }
  10075. setsubreg(ThisReg, TargetSubReg);
  10076. RegInUse := False;
  10077. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10078. begin
  10079. { Check to see if the active register is used afterwards;
  10080. if not, we can change it and make a saving. }
  10081. TransferUsedRegs(TmpUsedRegs);
  10082. { The target register may be marked as in use to cross
  10083. a jump to a distant label, so exclude it }
  10084. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10085. hp2 := p;
  10086. repeat
  10087. { Explicitly check for the excluded register (don't include the first
  10088. instruction as it may be reading from here }
  10089. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10090. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10091. begin
  10092. RegInUse := True;
  10093. Break;
  10094. end;
  10095. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10096. if not GetNextInstruction(hp2, hp2) then
  10097. InternalError(2020112340);
  10098. until (hp2 = hp1);
  10099. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10100. { We might still be able to get away with this }
  10101. RegInUse := not
  10102. (
  10103. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10104. (hp2.typ = ait_instruction) and
  10105. (
  10106. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10107. instruction that doesn't actually contain ThisReg }
  10108. (cs_opt_level3 in current_settings.optimizerswitches) or
  10109. RegInInstruction(ThisReg, hp2)
  10110. ) and
  10111. RegLoadedWithNewValue(ThisReg, hp2)
  10112. );
  10113. if not RegInUse then
  10114. begin
  10115. { Force the register size to the same as this instruction so it can be removed}
  10116. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10117. begin
  10118. TargetSize := S_L;
  10119. TargetSubReg := R_SUBD;
  10120. end
  10121. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10122. begin
  10123. TargetSize := S_W;
  10124. TargetSubReg := R_SUBW;
  10125. end;
  10126. ThisReg := taicpu(hp1).oper[1]^.reg;
  10127. setsubreg(ThisReg, TargetSubReg);
  10128. RegChanged := True;
  10129. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10130. TransferUsedRegs(TmpUsedRegs);
  10131. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10132. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10133. if p = hp1 then
  10134. begin
  10135. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10136. p_removed := True;
  10137. end
  10138. else
  10139. RemoveInstruction(hp1);
  10140. hp1_removed := True;
  10141. { Instruction will become "mov %reg,%reg" }
  10142. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10143. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10144. begin
  10145. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10146. RemoveCurrentP(p);
  10147. p_removed := True;
  10148. end
  10149. else
  10150. taicpu(p).oper[1]^.reg := ThisReg;
  10151. Result := True;
  10152. end
  10153. else
  10154. begin
  10155. if TargetSize <> MaxSize then
  10156. begin
  10157. { Since the register is in use, we have to force it to
  10158. MaxSize otherwise part of it may become undefined later on }
  10159. TargetSize := MaxSize;
  10160. case TargetSize of
  10161. S_B:
  10162. TargetSubReg := R_SUBL;
  10163. S_W:
  10164. TargetSubReg := R_SUBW;
  10165. S_L:
  10166. TargetSubReg := R_SUBD;
  10167. else
  10168. InternalError(2020112351);
  10169. end;
  10170. setsubreg(ThisReg, TargetSubReg);
  10171. end;
  10172. AdjustFinalLoad;
  10173. end;
  10174. end
  10175. else
  10176. AdjustFinalLoad;
  10177. Result := AdjustInitialLoadAndSize or Result;
  10178. { Now go through every instruction we found and change the
  10179. size. If TargetSize = MaxSize, then almost no changes are
  10180. needed and Result can remain False if it hasn't been set
  10181. yet.
  10182. If RegChanged is True, then the register requires changing
  10183. and so the point about TargetSize = MaxSize doesn't apply. }
  10184. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10185. begin
  10186. for LocalIndex := 0 to InstrMax do
  10187. begin
  10188. { If p_removed is true, then the original MOV/Z was removed
  10189. and removing the AND instruction may not be safe if it
  10190. appears first }
  10191. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10192. InternalError(2020112310);
  10193. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10194. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10195. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10196. InstrList[LocalIndex].opsize := TargetSize;
  10197. end;
  10198. Result := True;
  10199. end;
  10200. end;
  10201. begin
  10202. Result := False;
  10203. p_removed := False;
  10204. hp1_removed := False;
  10205. ThisReg := taicpu(p).oper[1]^.reg;
  10206. { Check for:
  10207. movs/z ###,%ecx (or %cx or %rcx)
  10208. ...
  10209. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10210. (dealloc %ecx)
  10211. Change to:
  10212. mov ###,%cl (if ### = %cl, then remove completely)
  10213. ...
  10214. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10215. }
  10216. if (getsupreg(ThisReg) = RS_ECX) and
  10217. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10218. (hp1.typ = ait_instruction) and
  10219. (
  10220. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10221. instruction that doesn't actually contain ECX }
  10222. (cs_opt_level3 in current_settings.optimizerswitches) or
  10223. RegInInstruction(NR_ECX, hp1) or
  10224. (
  10225. { It's common for the shift/rotate's read/write register to be
  10226. initialised in between, so under -O2 and under, search ahead
  10227. one more instruction
  10228. }
  10229. GetNextInstruction(hp1, hp1) and
  10230. (hp1.typ = ait_instruction) and
  10231. RegInInstruction(NR_ECX, hp1)
  10232. )
  10233. ) and
  10234. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10235. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10236. begin
  10237. TransferUsedRegs(TmpUsedRegs);
  10238. hp2 := p;
  10239. repeat
  10240. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10241. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10242. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10243. begin
  10244. case taicpu(p).opsize of
  10245. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10246. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10247. begin
  10248. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10249. RemoveCurrentP(p);
  10250. end
  10251. else
  10252. begin
  10253. taicpu(p).opcode := A_MOV;
  10254. taicpu(p).opsize := S_B;
  10255. taicpu(p).oper[1]^.reg := NR_CL;
  10256. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10257. end;
  10258. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10259. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10260. begin
  10261. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10262. RemoveCurrentP(p);
  10263. end
  10264. else
  10265. begin
  10266. taicpu(p).opcode := A_MOV;
  10267. taicpu(p).opsize := S_W;
  10268. taicpu(p).oper[1]^.reg := NR_CX;
  10269. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10270. end;
  10271. {$ifdef x86_64}
  10272. S_LQ:
  10273. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10274. begin
  10275. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10276. RemoveCurrentP(p);
  10277. end
  10278. else
  10279. begin
  10280. taicpu(p).opcode := A_MOV;
  10281. taicpu(p).opsize := S_L;
  10282. taicpu(p).oper[1]^.reg := NR_ECX;
  10283. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10284. end;
  10285. {$endif x86_64}
  10286. else
  10287. InternalError(2021120401);
  10288. end;
  10289. Result := True;
  10290. Exit;
  10291. end;
  10292. end;
  10293. { This is anything but quick! }
  10294. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10295. Exit;
  10296. SetLength(InstrList, 0);
  10297. InstrMax := -1;
  10298. case taicpu(p).opsize of
  10299. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10300. begin
  10301. {$if defined(i386) or defined(i8086)}
  10302. { If the target size is 8-bit, make sure we can actually encode it }
  10303. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10304. Exit;
  10305. {$endif i386 or i8086}
  10306. LowerLimit := $FF;
  10307. SignedLowerLimit := $7F;
  10308. SignedLowerLimitBottom := -128;
  10309. MinSize := S_B;
  10310. if taicpu(p).opsize = S_BW then
  10311. begin
  10312. MaxSize := S_W;
  10313. UpperLimit := $FFFF;
  10314. SignedUpperLimit := $7FFF;
  10315. SignedUpperLimitBottom := -32768;
  10316. end
  10317. else
  10318. begin
  10319. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10320. MaxSize := S_L;
  10321. UpperLimit := $FFFFFFFF;
  10322. SignedUpperLimit := $7FFFFFFF;
  10323. SignedUpperLimitBottom := -2147483648;
  10324. end;
  10325. end;
  10326. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10327. begin
  10328. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10329. LowerLimit := $FFFF;
  10330. SignedLowerLimit := $7FFF;
  10331. SignedLowerLimitBottom := -32768;
  10332. UpperLimit := $FFFFFFFF;
  10333. SignedUpperLimit := $7FFFFFFF;
  10334. SignedUpperLimitBottom := -2147483648;
  10335. MinSize := S_W;
  10336. MaxSize := S_L;
  10337. end;
  10338. {$ifdef x86_64}
  10339. S_LQ:
  10340. begin
  10341. { Both the lower and upper limits are set to 32-bit. If a limit
  10342. is breached, then optimisation is impossible }
  10343. LowerLimit := $FFFFFFFF;
  10344. SignedLowerLimit := $7FFFFFFF;
  10345. SignedLowerLimitBottom := -2147483648;
  10346. UpperLimit := $FFFFFFFF;
  10347. SignedUpperLimit := $7FFFFFFF;
  10348. SignedUpperLimitBottom := -2147483648;
  10349. MinSize := S_L;
  10350. MaxSize := S_L;
  10351. end;
  10352. {$endif x86_64}
  10353. else
  10354. InternalError(2020112301);
  10355. end;
  10356. TestValMin := 0;
  10357. TestValMax := LowerLimit;
  10358. TestValSignedMax := SignedLowerLimit;
  10359. TryShiftDownLimit := LowerLimit;
  10360. TryShiftDown := S_NO;
  10361. ShiftDownOverflow := False;
  10362. RegChanged := False;
  10363. BitwiseOnly := True;
  10364. OrXorUsed := False;
  10365. UpperSignedOverflow := False;
  10366. LowerSignedOverflow := False;
  10367. UpperUnsignedOverflow := False;
  10368. LowerUnsignedOverflow := False;
  10369. hp1 := p;
  10370. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10371. (hp1.typ = ait_instruction) and
  10372. (
  10373. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10374. instruction that doesn't actually contain ThisReg }
  10375. (cs_opt_level3 in current_settings.optimizerswitches) or
  10376. { This allows this Movx optimisation to work through the SETcc instructions
  10377. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10378. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10379. skip over these SETcc instructions). }
  10380. (taicpu(hp1).opcode = A_SETcc) or
  10381. RegInInstruction(ThisReg, hp1)
  10382. ) do
  10383. begin
  10384. case taicpu(hp1).opcode of
  10385. A_INC,A_DEC:
  10386. begin
  10387. { Has to be an exact match on the register }
  10388. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10389. Break;
  10390. if taicpu(hp1).opcode = A_INC then
  10391. begin
  10392. Inc(TestValMin);
  10393. Inc(TestValMax);
  10394. Inc(TestValSignedMax);
  10395. end
  10396. else
  10397. begin
  10398. Dec(TestValMin);
  10399. Dec(TestValMax);
  10400. Dec(TestValSignedMax);
  10401. end;
  10402. end;
  10403. A_TEST, A_CMP:
  10404. begin
  10405. if (
  10406. { Too high a risk of non-linear behaviour that breaks DFA
  10407. here, unless it's cmp $0,%reg, which is equivalent to
  10408. test %reg,%reg }
  10409. OrXorUsed and
  10410. (taicpu(hp1).opcode = A_CMP) and
  10411. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10412. ) or
  10413. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10414. { Has to be an exact match on the register }
  10415. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10416. (
  10417. { Permit "test %reg,%reg" }
  10418. (taicpu(hp1).opcode = A_TEST) and
  10419. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10420. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10421. ) or
  10422. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10423. { Make sure the comparison value is not smaller than the
  10424. smallest allowed signed value for the minimum size (e.g.
  10425. -128 for 8-bit) }
  10426. not (
  10427. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10428. { Is it in the negative range? }
  10429. (
  10430. (taicpu(hp1).oper[0]^.val < 0) and
  10431. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10432. )
  10433. ) then
  10434. Break;
  10435. { Check to see if the active register is used afterwards }
  10436. TransferUsedRegs(TmpUsedRegs);
  10437. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10438. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10439. begin
  10440. { Make sure the comparison or any previous instructions
  10441. hasn't pushed the test values outside of the range of
  10442. MinSize }
  10443. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10444. begin
  10445. { Exceeded lower bound but not upper bound }
  10446. Exit;
  10447. end
  10448. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10449. begin
  10450. { Size didn't exceed lower bound }
  10451. TargetSize := MinSize;
  10452. end
  10453. else
  10454. Break;
  10455. case TargetSize of
  10456. S_B:
  10457. TargetSubReg := R_SUBL;
  10458. S_W:
  10459. TargetSubReg := R_SUBW;
  10460. S_L:
  10461. TargetSubReg := R_SUBD;
  10462. else
  10463. InternalError(2021051002);
  10464. end;
  10465. if TargetSize <> MaxSize then
  10466. begin
  10467. { Update the register to its new size }
  10468. setsubreg(ThisReg, TargetSubReg);
  10469. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10470. taicpu(hp1).oper[1]^.reg := ThisReg;
  10471. taicpu(hp1).opsize := TargetSize;
  10472. { Convert the input MOVZX to a MOV if necessary }
  10473. AdjustInitialLoadAndSize;
  10474. if (InstrMax >= 0) then
  10475. begin
  10476. for Index := 0 to InstrMax do
  10477. begin
  10478. { If p_removed is true, then the original MOV/Z was removed
  10479. and removing the AND instruction may not be safe if it
  10480. appears first }
  10481. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10482. InternalError(2020112311);
  10483. if InstrList[Index].oper[0]^.typ = top_reg then
  10484. InstrList[Index].oper[0]^.reg := ThisReg;
  10485. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10486. InstrList[Index].opsize := MinSize;
  10487. end;
  10488. end;
  10489. Result := True;
  10490. end;
  10491. Exit;
  10492. end;
  10493. end;
  10494. A_SETcc:
  10495. begin
  10496. { This allows this Movx optimisation to work through the SETcc instructions
  10497. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10498. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10499. skip over these SETcc instructions). }
  10500. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10501. { Of course, break out if the current register is used }
  10502. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10503. Break
  10504. else
  10505. { We must use Continue so the instruction doesn't get added
  10506. to InstrList }
  10507. Continue;
  10508. end;
  10509. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10510. begin
  10511. if
  10512. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10513. { Has to be an exact match on the register }
  10514. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10515. (
  10516. (
  10517. (taicpu(hp1).oper[0]^.typ = top_const) and
  10518. (
  10519. (
  10520. (taicpu(hp1).opcode = A_SHL) and
  10521. (
  10522. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10523. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10524. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10525. )
  10526. ) or (
  10527. (taicpu(hp1).opcode <> A_SHL) and
  10528. (
  10529. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10530. { Is it in the negative range? }
  10531. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10532. )
  10533. )
  10534. )
  10535. ) or (
  10536. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10537. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10538. )
  10539. ) then
  10540. Break;
  10541. { Only process OR and XOR if there are only bitwise operations,
  10542. since otherwise they can too easily fool the data flow
  10543. analysis (they can cause non-linear behaviour) }
  10544. case taicpu(hp1).opcode of
  10545. A_ADD:
  10546. begin
  10547. if OrXorUsed then
  10548. { Too high a risk of non-linear behaviour that breaks DFA here }
  10549. Break
  10550. else
  10551. BitwiseOnly := False;
  10552. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10553. begin
  10554. TestValMin := TestValMin * 2;
  10555. TestValMax := TestValMax * 2;
  10556. TestValSignedMax := TestValSignedMax * 2;
  10557. end
  10558. else
  10559. begin
  10560. WorkingValue := taicpu(hp1).oper[0]^.val;
  10561. TestValMin := TestValMin + WorkingValue;
  10562. TestValMax := TestValMax + WorkingValue;
  10563. TestValSignedMax := TestValSignedMax + WorkingValue;
  10564. end;
  10565. end;
  10566. A_SUB:
  10567. begin
  10568. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10569. begin
  10570. TestValMin := 0;
  10571. TestValMax := 0;
  10572. TestValSignedMax := 0;
  10573. end
  10574. else
  10575. begin
  10576. if OrXorUsed then
  10577. { Too high a risk of non-linear behaviour that breaks DFA here }
  10578. Break
  10579. else
  10580. BitwiseOnly := False;
  10581. WorkingValue := taicpu(hp1).oper[0]^.val;
  10582. TestValMin := TestValMin - WorkingValue;
  10583. TestValMax := TestValMax - WorkingValue;
  10584. TestValSignedMax := TestValSignedMax - WorkingValue;
  10585. end;
  10586. end;
  10587. A_AND:
  10588. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10589. begin
  10590. { we might be able to go smaller if AND appears first }
  10591. if InstrMax = -1 then
  10592. case MinSize of
  10593. S_B:
  10594. ;
  10595. S_W:
  10596. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10597. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10598. begin
  10599. TryShiftDown := S_B;
  10600. TryShiftDownLimit := $FF;
  10601. end;
  10602. S_L:
  10603. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10604. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10605. begin
  10606. TryShiftDown := S_B;
  10607. TryShiftDownLimit := $FF;
  10608. end
  10609. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10610. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10611. begin
  10612. TryShiftDown := S_W;
  10613. TryShiftDownLimit := $FFFF;
  10614. end;
  10615. else
  10616. InternalError(2020112320);
  10617. end;
  10618. WorkingValue := taicpu(hp1).oper[0]^.val;
  10619. TestValMin := TestValMin and WorkingValue;
  10620. TestValMax := TestValMax and WorkingValue;
  10621. TestValSignedMax := TestValSignedMax and WorkingValue;
  10622. end;
  10623. A_OR:
  10624. begin
  10625. if not BitwiseOnly then
  10626. Break;
  10627. OrXorUsed := True;
  10628. WorkingValue := taicpu(hp1).oper[0]^.val;
  10629. TestValMin := TestValMin or WorkingValue;
  10630. TestValMax := TestValMax or WorkingValue;
  10631. TestValSignedMax := TestValSignedMax or WorkingValue;
  10632. end;
  10633. A_XOR:
  10634. begin
  10635. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10636. begin
  10637. TestValMin := 0;
  10638. TestValMax := 0;
  10639. TestValSignedMax := 0;
  10640. end
  10641. else
  10642. begin
  10643. if not BitwiseOnly then
  10644. Break;
  10645. OrXorUsed := True;
  10646. WorkingValue := taicpu(hp1).oper[0]^.val;
  10647. TestValMin := TestValMin xor WorkingValue;
  10648. TestValMax := TestValMax xor WorkingValue;
  10649. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10650. end;
  10651. end;
  10652. A_SHL:
  10653. begin
  10654. BitwiseOnly := False;
  10655. WorkingValue := taicpu(hp1).oper[0]^.val;
  10656. TestValMin := TestValMin shl WorkingValue;
  10657. TestValMax := TestValMax shl WorkingValue;
  10658. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10659. end;
  10660. A_SHR,
  10661. { The first instruction was MOVZX, so the value won't be negative }
  10662. A_SAR:
  10663. begin
  10664. if InstrMax <> -1 then
  10665. BitwiseOnly := False
  10666. else
  10667. { we might be able to go smaller if SHR appears first }
  10668. case MinSize of
  10669. S_B:
  10670. ;
  10671. S_W:
  10672. if (taicpu(hp1).oper[0]^.val >= 8) then
  10673. begin
  10674. TryShiftDown := S_B;
  10675. TryShiftDownLimit := $FF;
  10676. TryShiftDownSignedLimit := $7F;
  10677. TryShiftDownSignedLimitLower := -128;
  10678. end;
  10679. S_L:
  10680. if (taicpu(hp1).oper[0]^.val >= 24) then
  10681. begin
  10682. TryShiftDown := S_B;
  10683. TryShiftDownLimit := $FF;
  10684. TryShiftDownSignedLimit := $7F;
  10685. TryShiftDownSignedLimitLower := -128;
  10686. end
  10687. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10688. begin
  10689. TryShiftDown := S_W;
  10690. TryShiftDownLimit := $FFFF;
  10691. TryShiftDownSignedLimit := $7FFF;
  10692. TryShiftDownSignedLimitLower := -32768;
  10693. end;
  10694. else
  10695. InternalError(2020112321);
  10696. end;
  10697. WorkingValue := taicpu(hp1).oper[0]^.val;
  10698. if taicpu(hp1).opcode = A_SAR then
  10699. begin
  10700. TestValMin := SarInt64(TestValMin, WorkingValue);
  10701. TestValMax := SarInt64(TestValMax, WorkingValue);
  10702. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10703. end
  10704. else
  10705. begin
  10706. TestValMin := TestValMin shr WorkingValue;
  10707. TestValMax := TestValMax shr WorkingValue;
  10708. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10709. end;
  10710. end;
  10711. else
  10712. InternalError(2020112303);
  10713. end;
  10714. end;
  10715. (*
  10716. A_IMUL:
  10717. case taicpu(hp1).ops of
  10718. 2:
  10719. begin
  10720. if not MatchOpType(hp1, top_reg, top_reg) or
  10721. { Has to be an exact match on the register }
  10722. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10723. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10724. Break;
  10725. TestValMin := TestValMin * TestValMin;
  10726. TestValMax := TestValMax * TestValMax;
  10727. TestValSignedMax := TestValSignedMax * TestValMax;
  10728. end;
  10729. 3:
  10730. begin
  10731. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10732. { Has to be an exact match on the register }
  10733. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10734. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10735. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10736. { Is it in the negative range? }
  10737. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10738. Break;
  10739. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10740. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10741. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10742. end;
  10743. else
  10744. Break;
  10745. end;
  10746. A_IDIV:
  10747. case taicpu(hp1).ops of
  10748. 3:
  10749. begin
  10750. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10751. { Has to be an exact match on the register }
  10752. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10753. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10754. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10755. { Is it in the negative range? }
  10756. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10757. Break;
  10758. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10759. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10760. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10761. end;
  10762. else
  10763. Break;
  10764. end;
  10765. *)
  10766. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10767. begin
  10768. { If there are no instructions in between, then we might be able to make a saving }
  10769. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10770. Break;
  10771. { We have something like:
  10772. movzbw %dl,%dx
  10773. ...
  10774. movswl %dx,%edx
  10775. Change the latter to a zero-extension then enter the
  10776. A_MOVZX case branch.
  10777. }
  10778. {$ifdef x86_64}
  10779. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10780. begin
  10781. { this becomes a zero extension from 32-bit to 64-bit, but
  10782. the upper 32 bits are already zero, so just delete the
  10783. instruction }
  10784. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10785. RemoveInstruction(hp1);
  10786. Result := True;
  10787. Exit;
  10788. end
  10789. else
  10790. {$endif x86_64}
  10791. begin
  10792. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10793. taicpu(hp1).opcode := A_MOVZX;
  10794. {$ifdef x86_64}
  10795. case taicpu(hp1).opsize of
  10796. S_BQ:
  10797. begin
  10798. taicpu(hp1).opsize := S_BL;
  10799. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10800. end;
  10801. S_WQ:
  10802. begin
  10803. taicpu(hp1).opsize := S_WL;
  10804. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10805. end;
  10806. S_LQ:
  10807. begin
  10808. taicpu(hp1).opcode := A_MOV;
  10809. taicpu(hp1).opsize := S_L;
  10810. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10811. { In this instance, we need to break out because the
  10812. instruction is no longer MOVZX or MOVSXD }
  10813. Result := True;
  10814. Exit;
  10815. end;
  10816. else
  10817. ;
  10818. end;
  10819. {$endif x86_64}
  10820. Result := CompressInstructions;
  10821. Exit;
  10822. end;
  10823. end;
  10824. A_MOVZX:
  10825. begin
  10826. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10827. Break;
  10828. if (InstrMax = -1) then
  10829. begin
  10830. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10831. begin
  10832. { Optimise around i40003 }
  10833. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10834. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10835. {$ifndef x86_64}
  10836. and (
  10837. (taicpu(p).oper[0]^.typ <> top_reg) or
  10838. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10839. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10840. )
  10841. {$endif not x86_64}
  10842. then
  10843. begin
  10844. if (taicpu(p).oper[0]^.typ = top_reg) then
  10845. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10846. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10847. taicpu(p).opsize := S_BL;
  10848. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10849. RemoveInstruction(hp1);
  10850. Result := True;
  10851. Exit;
  10852. end;
  10853. end
  10854. else
  10855. begin
  10856. { Will return false if the second parameter isn't ThisReg
  10857. (can happen on -O2 and under) }
  10858. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10859. begin
  10860. { The two MOVZX instructions are adjacent, so remove the first one }
  10861. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10862. RemoveCurrentP(p);
  10863. Result := True;
  10864. Exit;
  10865. end;
  10866. Break;
  10867. end;
  10868. end;
  10869. Result := CompressInstructions;
  10870. Exit;
  10871. end;
  10872. else
  10873. { This includes ADC, SBB and IDIV }
  10874. Break;
  10875. end;
  10876. if not CheckOverflowConditions then
  10877. Break;
  10878. { Contains highest index (so instruction count - 1) }
  10879. Inc(InstrMax);
  10880. if InstrMax > High(InstrList) then
  10881. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10882. InstrList[InstrMax] := taicpu(hp1);
  10883. end;
  10884. end;
  10885. {$pop}
  10886. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10887. var
  10888. hp1 : tai;
  10889. begin
  10890. Result:=false;
  10891. if (taicpu(p).ops >= 2) and
  10892. ((taicpu(p).oper[0]^.typ = top_const) or
  10893. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10894. (taicpu(p).oper[1]^.typ = top_reg) and
  10895. ((taicpu(p).ops = 2) or
  10896. ((taicpu(p).oper[2]^.typ = top_reg) and
  10897. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10898. GetLastInstruction(p,hp1) and
  10899. MatchInstruction(hp1,A_MOV,[]) and
  10900. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10901. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10902. begin
  10903. TransferUsedRegs(TmpUsedRegs);
  10904. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10905. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10906. { change
  10907. mov reg1,reg2
  10908. imul y,reg2 to imul y,reg1,reg2 }
  10909. begin
  10910. taicpu(p).ops := 3;
  10911. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10912. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10913. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10914. RemoveInstruction(hp1);
  10915. result:=true;
  10916. end;
  10917. end;
  10918. end;
  10919. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10920. var
  10921. ThisLabel: TAsmLabel;
  10922. begin
  10923. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10924. ThisLabel.decrefs;
  10925. taicpu(p).condition := C_None;
  10926. taicpu(p).opcode := A_RET;
  10927. taicpu(p).is_jmp := false;
  10928. taicpu(p).ops := taicpu(ret_p).ops;
  10929. case taicpu(ret_p).ops of
  10930. 0:
  10931. taicpu(p).clearop(0);
  10932. 1:
  10933. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10934. else
  10935. internalerror(2016041301);
  10936. end;
  10937. { If the original label is now dead, it might turn out that the label
  10938. immediately follows p. As a result, everything beyond it, which will
  10939. be just some final register configuration and a RET instruction, is
  10940. now dead code. [Kit] }
  10941. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10942. running RemoveDeadCodeAfterJump for each RET instruction, because
  10943. this optimisation rarely happens and most RETs appear at the end of
  10944. routines where there is nothing that can be stripped. [Kit] }
  10945. if not ThisLabel.is_used then
  10946. RemoveDeadCodeAfterJump(p);
  10947. end;
  10948. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10949. var
  10950. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10951. Unconditional, PotentialModified: Boolean;
  10952. OperPtr: POper;
  10953. NewRef: TReference;
  10954. InstrList: array of taicpu;
  10955. InstrMax, Index: Integer;
  10956. const
  10957. {$ifdef DEBUG_AOPTCPU}
  10958. SNoFlags: shortstring = ' so the flags aren''t modified';
  10959. {$else DEBUG_AOPTCPU}
  10960. SNoFlags = '';
  10961. {$endif DEBUG_AOPTCPU}
  10962. begin
  10963. Result:=false;
  10964. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10965. begin
  10966. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10967. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10968. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10969. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10970. GetNextInstruction(hp1, hp2) and
  10971. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10972. { Change from: To:
  10973. set(C) %reg j(~C) label
  10974. test %reg,%reg/cmp $0,%reg
  10975. je label
  10976. set(C) %reg j(C) label
  10977. test %reg,%reg/cmp $0,%reg
  10978. jne label
  10979. (Also do something similar with sete/setne instead of je/jne)
  10980. }
  10981. begin
  10982. { Before we do anything else, we need to check the instructions
  10983. in between SETcc and TEST to make sure they don't modify the
  10984. FLAGS register - if -O2 or under, there won't be any
  10985. instructions between SET and TEST }
  10986. TransferUsedRegs(TmpUsedRegs);
  10987. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10988. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10989. begin
  10990. next := p;
  10991. SetLength(InstrList, 0);
  10992. InstrMax := -1;
  10993. PotentialModified := False;
  10994. { Make a note of every instruction that modifies the FLAGS
  10995. register }
  10996. while GetNextInstruction(next, next) and (next <> hp1) do
  10997. begin
  10998. if next.typ <> ait_instruction then
  10999. { GetNextInstructionUsingReg should have returned False }
  11000. InternalError(2021051701);
  11001. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  11002. begin
  11003. case taicpu(next).opcode of
  11004. A_SETcc,
  11005. A_CMOVcc,
  11006. A_Jcc:
  11007. begin
  11008. if PotentialModified then
  11009. { Not safe because the flags were modified earlier }
  11010. Exit
  11011. else
  11012. { Condition is the same as the initial SETcc, so this is safe
  11013. (don't add to instruction list though) }
  11014. Continue;
  11015. end;
  11016. A_ADD:
  11017. begin
  11018. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11019. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11020. (taicpu(next).oper[1]^.typ <> top_reg) or
  11021. { Must write to a register }
  11022. (taicpu(next).oper[0]^.typ = top_ref) then
  11023. { Require a constant or a register }
  11024. Exit;
  11025. PotentialModified := True;
  11026. end;
  11027. A_SUB:
  11028. begin
  11029. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11030. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11031. (taicpu(next).oper[1]^.typ <> top_reg) or
  11032. { Must write to a register }
  11033. (taicpu(next).oper[0]^.typ <> top_const) or
  11034. (taicpu(next).oper[0]^.val = $80000000) then
  11035. { Can't subtract a register with LEA - also
  11036. check that the value isn't -2^31, as this
  11037. can't be negated }
  11038. Exit;
  11039. PotentialModified := True;
  11040. end;
  11041. A_SAL,
  11042. A_SHL:
  11043. begin
  11044. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11045. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11046. (taicpu(next).oper[1]^.typ <> top_reg) or
  11047. { Must write to a register }
  11048. (taicpu(next).oper[0]^.typ <> top_const) or
  11049. (taicpu(next).oper[0]^.val < 0) or
  11050. (taicpu(next).oper[0]^.val > 3) then
  11051. Exit;
  11052. PotentialModified := True;
  11053. end;
  11054. A_IMUL:
  11055. begin
  11056. if (taicpu(next).ops <> 3) or
  11057. (taicpu(next).oper[1]^.typ <> top_reg) or
  11058. { Must write to a register }
  11059. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11060. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11061. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11062. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11063. Exit
  11064. else
  11065. PotentialModified := True;
  11066. end;
  11067. else
  11068. { Don't know how to change this, so abort }
  11069. Exit;
  11070. end;
  11071. { Contains highest index (so instruction count - 1) }
  11072. Inc(InstrMax);
  11073. if InstrMax > High(InstrList) then
  11074. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11075. InstrList[InstrMax] := taicpu(next);
  11076. end;
  11077. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11078. end;
  11079. if not Assigned(next) or (next <> hp1) then
  11080. { It should be equal to hp1 }
  11081. InternalError(2021051702);
  11082. { Cycle through each instruction and check to see if we can
  11083. change them to versions that don't modify the flags }
  11084. if (InstrMax >= 0) then
  11085. begin
  11086. for Index := 0 to InstrMax do
  11087. case InstrList[Index].opcode of
  11088. A_ADD:
  11089. begin
  11090. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11091. InstrList[Index].opcode := A_LEA;
  11092. reference_reset(NewRef, 1, []);
  11093. NewRef.base := InstrList[Index].oper[1]^.reg;
  11094. if InstrList[Index].oper[0]^.typ = top_reg then
  11095. begin
  11096. NewRef.index := InstrList[Index].oper[0]^.reg;
  11097. NewRef.scalefactor := 1;
  11098. end
  11099. else
  11100. NewRef.offset := InstrList[Index].oper[0]^.val;
  11101. InstrList[Index].loadref(0, NewRef);
  11102. end;
  11103. A_SUB:
  11104. begin
  11105. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11106. InstrList[Index].opcode := A_LEA;
  11107. reference_reset(NewRef, 1, []);
  11108. NewRef.base := InstrList[Index].oper[1]^.reg;
  11109. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11110. InstrList[Index].loadref(0, NewRef);
  11111. end;
  11112. A_SHL,
  11113. A_SAL:
  11114. begin
  11115. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11116. InstrList[Index].opcode := A_LEA;
  11117. reference_reset(NewRef, 1, []);
  11118. NewRef.index := InstrList[Index].oper[1]^.reg;
  11119. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11120. InstrList[Index].loadref(0, NewRef);
  11121. end;
  11122. A_IMUL:
  11123. begin
  11124. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11125. InstrList[Index].opcode := A_LEA;
  11126. reference_reset(NewRef, 1, []);
  11127. NewRef.index := InstrList[Index].oper[1]^.reg;
  11128. case InstrList[Index].oper[0]^.val of
  11129. 2, 4, 8:
  11130. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11131. else {3, 5 and 9}
  11132. begin
  11133. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11134. NewRef.base := InstrList[Index].oper[1]^.reg;
  11135. end;
  11136. end;
  11137. InstrList[Index].loadref(0, NewRef);
  11138. end;
  11139. else
  11140. InternalError(2021051710);
  11141. end;
  11142. end;
  11143. { Mark the FLAGS register as used across this whole block }
  11144. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11145. end;
  11146. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11147. JumpC := taicpu(hp2).condition;
  11148. Unconditional := False;
  11149. if conditions_equal(JumpC, C_E) then
  11150. SetC := inverse_cond(taicpu(p).condition)
  11151. else if conditions_equal(JumpC, C_NE) then
  11152. SetC := taicpu(p).condition
  11153. else
  11154. { We've got something weird here (and inefficent) }
  11155. begin
  11156. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11157. SetC := C_NONE;
  11158. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11159. if condition_in(C_AE, JumpC) then
  11160. Unconditional := True
  11161. else
  11162. { Not sure what to do with this jump - drop out }
  11163. Exit;
  11164. end;
  11165. RemoveInstruction(hp1);
  11166. if Unconditional then
  11167. MakeUnconditional(taicpu(hp2))
  11168. else
  11169. begin
  11170. if SetC = C_NONE then
  11171. InternalError(2018061402);
  11172. taicpu(hp2).SetCondition(SetC);
  11173. end;
  11174. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11175. TmpUsedRegs }
  11176. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11177. begin
  11178. RemoveCurrentp(p, hp2);
  11179. if taicpu(hp2).opcode = A_SETcc then
  11180. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11181. else
  11182. begin
  11183. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11184. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11185. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11186. end;
  11187. end
  11188. else
  11189. if taicpu(hp2).opcode = A_SETcc then
  11190. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11191. else
  11192. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11193. Result := True;
  11194. end
  11195. else if
  11196. { Make sure the instructions are adjacent }
  11197. (
  11198. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11199. GetNextInstruction(p, hp1)
  11200. ) and
  11201. MatchInstruction(hp1, A_MOV, [S_B]) and
  11202. { Writing to memory is allowed }
  11203. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11204. begin
  11205. {
  11206. Watch out for sequences such as:
  11207. set(c)b %regb
  11208. movb %regb,(ref)
  11209. movb $0,1(ref)
  11210. movb $0,2(ref)
  11211. movb $0,3(ref)
  11212. Much more efficient to turn it into:
  11213. movl $0,%regl
  11214. set(c)b %regb
  11215. movl %regl,(ref)
  11216. Or:
  11217. set(c)b %regb
  11218. movzbl %regb,%regl
  11219. movl %regl,(ref)
  11220. }
  11221. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11222. GetNextInstruction(hp1, hp2) and
  11223. MatchInstruction(hp2, A_MOV, [S_B]) and
  11224. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11225. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11226. begin
  11227. { Don't do anything else except set Result to True }
  11228. end
  11229. else
  11230. begin
  11231. if taicpu(p).oper[0]^.typ = top_reg then
  11232. begin
  11233. TransferUsedRegs(TmpUsedRegs);
  11234. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11235. end;
  11236. { If it's not a register, it's a memory address }
  11237. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11238. begin
  11239. { Even if the register is still in use, we can minimise the
  11240. pipeline stall by changing the MOV into another SETcc. }
  11241. taicpu(hp1).opcode := A_SETcc;
  11242. taicpu(hp1).condition := taicpu(p).condition;
  11243. if taicpu(hp1).oper[1]^.typ = top_ref then
  11244. begin
  11245. { Swapping the operand pointers like this is probably a
  11246. bit naughty, but it is far faster than using loadoper
  11247. to transfer the reference from oper[1] to oper[0] if
  11248. you take into account the extra procedure calls and
  11249. the memory allocation and deallocation required }
  11250. OperPtr := taicpu(hp1).oper[1];
  11251. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11252. taicpu(hp1).oper[0] := OperPtr;
  11253. end
  11254. else
  11255. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11256. taicpu(hp1).clearop(1);
  11257. taicpu(hp1).ops := 1;
  11258. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11259. end
  11260. else
  11261. begin
  11262. if taicpu(hp1).oper[1]^.typ = top_reg then
  11263. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11264. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11265. RemoveInstruction(hp1);
  11266. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11267. end
  11268. end;
  11269. Result := True;
  11270. end;
  11271. end;
  11272. end;
  11273. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11274. var
  11275. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11276. TargetReg: TRegister;
  11277. condition, inverted_condition: TAsmCond;
  11278. FoundMOV: Boolean;
  11279. begin
  11280. Result := False;
  11281. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11282. create the most optimial instructions possible due to limited
  11283. register availability, and there are situations where two
  11284. complementary "simple" CMOV blocks are created which, after the fact
  11285. can be merged into a "double" block. For example:
  11286. movw $257,%ax
  11287. movw $2,%r8w
  11288. xorl r9d,%r9d
  11289. testw $16,18(%rcx)
  11290. cmovew %ax,%dx
  11291. cmovew %r8w,%bx
  11292. cmovel %r9d,%r14d
  11293. movw $1283,%ax
  11294. movw $4,%r8w
  11295. movl $9,%r9d
  11296. cmovnew %ax,%dx
  11297. cmovnew %r8w,%bx
  11298. cmovnel %r9d,%r14d
  11299. The CMOVNE instructions at the end can be removed, and the
  11300. destination registers copied into the MOV instructions directly
  11301. above them, before finally being moved to before the first CMOVE
  11302. instructions, to produce:
  11303. movw $257,%ax
  11304. movw $2,%r8w
  11305. xorl r9d,%r9d
  11306. testw $16,18(%rcx)
  11307. movw $1283,%dx
  11308. movw $4,%bx
  11309. movl $9,%r14d
  11310. cmovew %ax,%dx
  11311. cmovew %r8w,%bx
  11312. cmovel %r9d,%r14d
  11313. Which can then be later optimised to:
  11314. movw $257,%ax
  11315. movw $2,%r8w
  11316. xorl r9d,%r9d
  11317. movw $1283,%dx
  11318. movw $4,%bx
  11319. movl $9,%r14d
  11320. testw $16,18(%rcx)
  11321. cmovew %ax,%dx
  11322. cmovew %r8w,%bx
  11323. cmovel %r9d,%r14d
  11324. }
  11325. TargetReg := taicpu(hp1).oper[1]^.reg;
  11326. condition := taicpu(hp1).condition;
  11327. inverted_condition := inverse_cond(condition);
  11328. pFirstMov := nil;
  11329. pLastMov := nil;
  11330. pCMOV := nil;
  11331. if (p.typ = ait_instruction) then
  11332. pCond := p
  11333. else if not GetNextInstruction(p, pCond) then
  11334. InternalError(2024012501);
  11335. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11336. { We should get the CMP or TEST instructeion }
  11337. InternalError(2024012502);
  11338. if (
  11339. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11340. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11341. ) then
  11342. begin
  11343. { We have to tread carefully here, hence why we're not using
  11344. GetNextInstructionUsingReg... we can only accept MOV and other
  11345. CMOV instructions. Anything else and we must drop out}
  11346. hp2 := hp1;
  11347. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11348. begin
  11349. if (hp2.typ <> ait_instruction) then
  11350. Exit;
  11351. case taicpu(hp2).opcode of
  11352. A_MOV:
  11353. begin
  11354. if not Assigned(pFirstMov) then
  11355. pFirstMov := hp2;
  11356. pLastMOV := hp2;
  11357. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11358. { Something different - drop out }
  11359. Exit;
  11360. { Otherwise, leave it for now }
  11361. end;
  11362. A_CMOVcc:
  11363. begin
  11364. if taicpu(hp2).condition = inverted_condition then
  11365. begin
  11366. { We found what we're looking for }
  11367. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11368. begin
  11369. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11370. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11371. begin
  11372. pCMOV := hp2;
  11373. Break;
  11374. end
  11375. else
  11376. { Unsafe reference - drop out }
  11377. Exit;
  11378. end;
  11379. end
  11380. else if taicpu(hp2).condition <> condition then
  11381. { Something weird - drop out }
  11382. Exit;
  11383. end;
  11384. else
  11385. { Invalid }
  11386. Exit;
  11387. end;
  11388. end;
  11389. if not Assigned(pCMOV) then
  11390. { No complementary CMOV found }
  11391. Exit;
  11392. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11393. begin
  11394. { Don't need to do anything special or search for a matching MOV }
  11395. Asml.Remove(pCMOV);
  11396. if RegInInstruction(TargetReg, pCond) then
  11397. { Make sure we don't overwrite the register if it's being used in the condition }
  11398. Asml.InsertAfter(pCMOV, pCond)
  11399. else
  11400. Asml.InsertBefore(pCMOV, pCond);
  11401. taicpu(pCMOV).opcode := A_MOV;
  11402. taicpu(pCMOV).condition := C_None;
  11403. { Don't need to worry about allocating new registers in these cases }
  11404. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11405. Result := True;
  11406. Exit;
  11407. end
  11408. else
  11409. begin
  11410. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11411. FoundMOV := False;
  11412. { Search for the MOV that sets the target register }
  11413. hp2 := pFirstMov;
  11414. repeat
  11415. if (taicpu(hp2).opcode = A_MOV) and
  11416. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11417. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11418. begin
  11419. { Change the destination }
  11420. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11421. if not FoundMOV then
  11422. begin
  11423. FoundMOV := True;
  11424. { Make sure the register is allocated }
  11425. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11426. end;
  11427. hp1 := tai(hp2.Previous);
  11428. Asml.Remove(hp2);
  11429. if RegInInstruction(TargetReg, pCond) then
  11430. { Make sure we don't overwrite the register if it's being used in the condition }
  11431. Asml.InsertAfter(hp2, pCond)
  11432. else
  11433. Asml.InsertBefore(hp2, pCond);
  11434. if (hp2 = pLastMov) then
  11435. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11436. Break;
  11437. hp2 := hp1;
  11438. end;
  11439. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11440. if FoundMOV then
  11441. { Delete the CMOV }
  11442. RemoveInstruction(pCMOV)
  11443. else
  11444. begin
  11445. { If no MOV was found, we have to actually move and transmute the CMOV }
  11446. Asml.Remove(pCMOV);
  11447. if RegInInstruction(TargetReg, pCond) then
  11448. { Make sure we don't overwrite the register if it's being used in the condition }
  11449. Asml.InsertAfter(pCMOV, pCond)
  11450. else
  11451. Asml.InsertBefore(pCMOV, pCond);
  11452. taicpu(pCMOV).opcode := A_MOV;
  11453. taicpu(pCMOV).condition := C_None;
  11454. end;
  11455. Result := True;
  11456. Exit;
  11457. end;
  11458. end;
  11459. end;
  11460. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11461. var
  11462. hp1, hp2, pCond: tai;
  11463. begin
  11464. Result := False;
  11465. { Search ahead for CMOV instructions }
  11466. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11467. begin
  11468. hp1 := p;
  11469. hp2 := p;
  11470. pCond := nil; { To prevent compiler warnings }
  11471. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11472. DEFAULTFLAGS }
  11473. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11474. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11475. pCond := p;
  11476. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11477. begin
  11478. if (hp1.typ <> ait_instruction) then
  11479. { Break out on markers and labels etc. }
  11480. Break;
  11481. case taicpu(hp1).opcode of
  11482. A_MOV:
  11483. { Ignore regular MOVs unless they are obviously not related
  11484. to a CMOV block }
  11485. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11486. Break;
  11487. A_CMOVcc:
  11488. if TryCmpCMovOpts(pCond, hp1) then
  11489. begin
  11490. hp1 := hp2;
  11491. { p itself isn't changed, and we're still inside a
  11492. while loop to catch subsequent CMOVs, so just flag
  11493. a new iteration }
  11494. Include(OptsToCheck, aoc_ForceNewIteration);
  11495. Continue;
  11496. end;
  11497. else
  11498. { Drop out if we find anything else }
  11499. Break;
  11500. end;
  11501. hp2 := hp1;
  11502. end;
  11503. end;
  11504. end;
  11505. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11506. var
  11507. hp1, hp2, pCond: tai;
  11508. SourceReg, TargetReg: TRegister;
  11509. begin
  11510. Result := False;
  11511. { In some situations, we end up with an inefficient arrangement of
  11512. instructions in the form of:
  11513. or %reg1,%reg2
  11514. (%reg1 deallocated)
  11515. test %reg2,%reg2
  11516. mov x,%reg2
  11517. we may be able to swap and rearrange the registers to produce:
  11518. or %reg2,%reg1
  11519. mov x,%reg2
  11520. test %reg1,%reg1
  11521. (%reg1 deallocated)
  11522. }
  11523. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11524. (taicpu(p).oper[1]^.typ = top_reg) and
  11525. (
  11526. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11527. MatchOperand(taicpu(p).oper[0]^, -1)
  11528. ) and
  11529. GetNextInstruction(p, hp1) and
  11530. MatchInstruction(hp1, A_MOV, []) and
  11531. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11532. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11533. begin
  11534. TargetReg := taicpu(p).oper[1]^.reg;
  11535. { Now look backwards to find a simple commutative operation: ADD,
  11536. IMUL (2-register version), OR, AND or XOR - whose destination
  11537. register is the same as TEST }
  11538. hp2 := p;
  11539. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11540. if RegInInstruction(TargetReg, hp2) then
  11541. begin
  11542. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11543. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11544. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11545. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11546. begin
  11547. SourceReg := taicpu(hp2).oper[0]^.reg;
  11548. if
  11549. { Make sure the MOV doesn't use the other register }
  11550. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11551. { And make sure the source register is not used afterwards }
  11552. not RegInUsedRegs(SourceReg, UsedRegs) then
  11553. begin
  11554. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11555. taicpu(hp2).oper[0]^.reg := TargetReg;
  11556. taicpu(hp2).oper[1]^.reg := SourceReg;
  11557. if taicpu(p).oper[0]^.typ = top_reg then
  11558. taicpu(p).oper[0]^.reg := SourceReg;
  11559. taicpu(p).oper[1]^.reg := SourceReg;
  11560. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11561. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11562. Include(OptsToCheck, aoc_ForceNewIteration);
  11563. { We can still check the following optimisations since
  11564. the instruction is still a TEST }
  11565. end;
  11566. end;
  11567. Break;
  11568. end;
  11569. end;
  11570. { Search ahead3 for CMOV instructions }
  11571. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11572. begin
  11573. hp1 := p;
  11574. hp2 := p;
  11575. pCond := nil; { To prevent compiler warnings }
  11576. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11577. DEFAULTFLAGS }
  11578. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11579. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11580. pCond := p;
  11581. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11582. begin
  11583. if (hp1.typ <> ait_instruction) then
  11584. { Break out on markers and labels etc. }
  11585. Break;
  11586. case taicpu(hp1).opcode of
  11587. A_MOV:
  11588. { Ignore regular MOVs unless they are obviously not related
  11589. to a CMOV block }
  11590. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11591. Break;
  11592. A_CMOVcc:
  11593. if TryCmpCMovOpts(pCond, hp1) then
  11594. begin
  11595. hp1 := hp2;
  11596. { p itself isn't changed, and we're still inside a
  11597. while loop to catch subsequent CMOVs, so just flag
  11598. a new iteration }
  11599. Include(OptsToCheck, aoc_ForceNewIteration);
  11600. Continue;
  11601. end;
  11602. else
  11603. { Drop out if we find anything else }
  11604. Break;
  11605. end;
  11606. hp2 := hp1;
  11607. end;
  11608. end;
  11609. end;
  11610. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11611. var
  11612. hp1: tai;
  11613. Count: Integer;
  11614. OrigLabel: TAsmLabel;
  11615. begin
  11616. result := False;
  11617. { Sometimes, the optimisations below can permit this }
  11618. RemoveDeadCodeAfterJump(p);
  11619. 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
  11620. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11621. begin
  11622. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11623. { Also a side-effect of optimisations }
  11624. if CollapseZeroDistJump(p, OrigLabel) then
  11625. begin
  11626. Result := True;
  11627. Exit;
  11628. end;
  11629. hp1 := GetLabelWithSym(OrigLabel);
  11630. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11631. begin
  11632. if taicpu(hp1).opcode = A_RET then
  11633. begin
  11634. {
  11635. change
  11636. jmp .L1
  11637. ...
  11638. .L1:
  11639. ret
  11640. into
  11641. ret
  11642. }
  11643. begin
  11644. ConvertJumpToRET(p, hp1);
  11645. result:=true;
  11646. end;
  11647. end
  11648. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11649. not (cs_opt_size in current_settings.optimizerswitches) and
  11650. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11651. begin
  11652. Result := True;
  11653. Exit;
  11654. end;
  11655. end;
  11656. end;
  11657. end;
  11658. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11659. begin
  11660. Result := assigned(p) and
  11661. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11662. (taicpu(p).oper[1]^.typ = top_reg) and
  11663. (
  11664. (taicpu(p).oper[0]^.typ = top_reg) or
  11665. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11666. it is not expected that this can cause a seg. violation }
  11667. (
  11668. (taicpu(p).oper[0]^.typ = top_ref) and
  11669. { TODO: Can we detect which references become constants at this
  11670. stage so we don't have to do a blanket ban? }
  11671. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11672. (
  11673. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11674. (
  11675. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11676. not RefModified and
  11677. { If the reference also appears in the condition, then we know it's safe, otherwise
  11678. any kind of access violation would have occurred already }
  11679. Assigned(cond_p) and
  11680. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11681. (cond_p.typ = ait_instruction) and
  11682. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11683. { Just consider 2-operand comparison instructions for now to be safe }
  11684. (taicpu(cond_p).ops = 2) and
  11685. (
  11686. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11687. (
  11688. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11689. { Don't risk identical registers but different offsets, as we may have constructs
  11690. such as buffer streams with things like length fields that indicate whether
  11691. any more data follows. And there are probably some contrived examples where
  11692. writing to offsets behind the one being read also lead to access violations }
  11693. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11694. (
  11695. { Check that we're not modifying a register that appears in the reference }
  11696. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11697. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11698. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11699. )
  11700. )
  11701. )
  11702. )
  11703. )
  11704. )
  11705. );
  11706. end;
  11707. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11708. begin
  11709. { Update integer registers, ignoring deallocations }
  11710. repeat
  11711. while assigned(p) and
  11712. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11713. (p.typ = ait_label) or
  11714. ((p.typ = ait_marker) and
  11715. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11716. p := tai(p.next);
  11717. while assigned(p) and
  11718. (p.typ=ait_RegAlloc) Do
  11719. begin
  11720. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11721. begin
  11722. case tai_regalloc(p).ratype of
  11723. ra_alloc :
  11724. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11725. else
  11726. ;
  11727. end;
  11728. end;
  11729. p := tai(p.next);
  11730. end;
  11731. until not(assigned(p)) or
  11732. (not(p.typ in SkipInstr) and
  11733. not((p.typ = ait_label) and
  11734. labelCanBeSkipped(tai_label(p))));
  11735. end;
  11736. {$ifndef 8086}
  11737. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11738. begin
  11739. Result := False;
  11740. EndJump := nil;
  11741. BlockStop := nil;
  11742. while (BlockStart <> fOptimizer.BlockEnd) and
  11743. { stop on labels }
  11744. (BlockStart.typ <> ait_label) do
  11745. begin
  11746. { Keep track of all integer registers that are used }
  11747. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11748. if BlockStart.typ = ait_instruction then
  11749. begin
  11750. if (taicpu(BlockStart).opcode = A_JMP) then
  11751. begin
  11752. if not IsJumpToLabel(taicpu(BlockStart)) or
  11753. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11754. Exit;
  11755. EndJump := BlockStart;
  11756. Break;
  11757. end
  11758. { Check to see if we have a valid MOV instruction instead }
  11759. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11760. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11761. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11762. begin
  11763. Exit;
  11764. end
  11765. else
  11766. { This will be a valid MOV }
  11767. fAllocationRange := BlockStart;
  11768. end;
  11769. OneBeforeBlock := BlockStart;
  11770. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11771. end;
  11772. if (BlockStart = fOptimizer.BlockEnd) then
  11773. Exit;
  11774. BlockStop := BlockStart;
  11775. Result := True;
  11776. end;
  11777. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11778. var
  11779. hp1: tai;
  11780. RefModified: Boolean;
  11781. begin
  11782. Result := 0;
  11783. hp1 := BlockStart;
  11784. RefModified := False; { As long as the condition is inverted, this can be reset }
  11785. while assigned(hp1) and
  11786. (hp1 <> BlockStop) do
  11787. begin
  11788. case hp1.typ of
  11789. ait_instruction:
  11790. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11791. begin
  11792. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11793. begin
  11794. Inc(Result);
  11795. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11796. Assigned(fCondition) and
  11797. { Will have 2 operands }
  11798. (
  11799. (
  11800. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11801. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11802. ) or
  11803. (
  11804. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11805. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11806. )
  11807. ) then
  11808. { It is no longer safe to use the reference in the condition.
  11809. this prevents problems such as:
  11810. mov (%reg),%reg
  11811. mov (%reg),...
  11812. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11813. (fixes #40165)
  11814. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11815. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11816. }
  11817. RefModified := True;
  11818. end
  11819. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11820. { CMOV with constants grows the code size }
  11821. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11822. begin
  11823. { Register was reserved by TryCMOVConst and
  11824. stored on ConstRegs }
  11825. end
  11826. else
  11827. begin
  11828. Result := -1;
  11829. Exit;
  11830. end;
  11831. end
  11832. else
  11833. begin
  11834. Result := -1;
  11835. Exit;
  11836. end;
  11837. else
  11838. { Most likely an align };
  11839. end;
  11840. fOptimizer.GetNextInstruction(hp1, hp1);
  11841. end;
  11842. end;
  11843. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11844. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11845. (this is done as a separate stage because the double types are extensions of the branching type,
  11846. but we can't discount the conditional jump until the last step) }
  11847. procedure EvaluateBranchingType;
  11848. begin
  11849. Inc(CMOVScore);
  11850. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11851. { Too many instructions to be worthwhile }
  11852. fState := tsInvalid;
  11853. end;
  11854. var
  11855. hp1: tai;
  11856. Count: Integer;
  11857. begin
  11858. { Table of valid CMOV block types
  11859. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11860. ---------- --------- --------- --------- --------- ---------
  11861. tsSimple X Yes X X X
  11862. tsDetour = 1st X X X X
  11863. tsBranching <> Mid Yes X X X
  11864. tsDouble End-label Yes * Yes X Yes
  11865. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11866. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11867. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11868. * Only one reference allowed
  11869. }
  11870. hp1 := nil; { To prevent compiler warnings }
  11871. Optimizer.CopyUsedRegs(RegisterTracking);
  11872. fOptimizer := Optimizer;
  11873. fLabel := AFirstLabel;
  11874. CMOVScore := 0;
  11875. ConstCount := 0;
  11876. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11877. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11878. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11879. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11880. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11881. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11882. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11883. fInsertionPoint := p_initialjump;
  11884. fCondition := nil;
  11885. fInitialJump := p_initialjump;
  11886. fFirstMovBlock := p_initialmov;
  11887. fFirstMovBlockStop := nil;
  11888. fSecondJump := nil;
  11889. fSecondMovBlock := nil;
  11890. fSecondMovBlockStop := nil;
  11891. fMidLabel := nil;
  11892. fSecondJump := nil;
  11893. fSecondMovBlock := nil;
  11894. fEndLabel := nil;
  11895. fAllocationRange := nil;
  11896. { Assume it all goes horribly wrong! }
  11897. fState := tsInvalid;
  11898. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11899. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11900. 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
  11901. begin
  11902. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11903. for Count := 0 to 1 do
  11904. with taicpu(fCondition).oper[Count]^ do
  11905. case typ of
  11906. top_reg:
  11907. if getregtype(reg) = R_INTREGISTER then
  11908. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11909. top_ref:
  11910. begin
  11911. if
  11912. {$ifdef x86_64}
  11913. (ref^.base <> NR_RIP) and
  11914. {$endif x86_64}
  11915. (ref^.base <> NR_NO) then
  11916. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11917. if (ref^.index <> NR_NO) then
  11918. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11919. end
  11920. else
  11921. ;
  11922. end;
  11923. { When inserting instructions before hp_prev, try to insert them
  11924. before the allocation of the FLAGS register }
  11925. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11926. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11927. { If not found, set it equal to the condition so it's something sensible }
  11928. fInsertionPoint := fCondition;
  11929. { When dealing with a comparison against zero, take note of the
  11930. instruction before it to see if we can move instructions further
  11931. back in order to benefit PostPeepholeOptTestOr.
  11932. }
  11933. if (
  11934. (
  11935. (taicpu(fCondition).opcode = A_CMP) and
  11936. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11937. ) or
  11938. (
  11939. (taicpu(fCondition).opcode = A_TEST) and
  11940. (
  11941. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11942. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11943. )
  11944. )
  11945. ) and
  11946. Optimizer.GetLastInstruction(fCondition, hp1) then
  11947. begin
  11948. { These instructions set the zero flag if the result is zero }
  11949. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11950. begin
  11951. fInsertionPoint := hp1;
  11952. { Also mark all the registers in this previous instruction
  11953. as 'in use', even if they've just been deallocated }
  11954. for Count := 0 to 1 do
  11955. with taicpu(hp1).oper[Count]^ do
  11956. case typ of
  11957. top_reg:
  11958. if getregtype(reg) = R_INTREGISTER then
  11959. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11960. top_ref:
  11961. begin
  11962. if
  11963. {$ifdef x86_64}
  11964. (ref^.base <> NR_RIP) and
  11965. {$endif x86_64}
  11966. (ref^.base <> NR_NO) then
  11967. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11968. if (ref^.index <> NR_NO) then
  11969. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11970. end
  11971. else
  11972. ;
  11973. end;
  11974. end;
  11975. end;
  11976. end
  11977. else
  11978. fCondition := nil;
  11979. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11980. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11981. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11982. { If not found, set it equal to p so it's something sensible }
  11983. fInsertionPoint := hp1;
  11984. hp1 := p_initialmov;
  11985. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  11986. Exit;
  11987. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  11988. if (hp1.typ <> ait_label) then { should be on a jump }
  11989. begin
  11990. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  11991. { Need a label afterwards }
  11992. Exit;
  11993. end
  11994. else
  11995. fMidLabel := hp1;
  11996. if tai_label(fMidLabel).labsym <> AFirstLabel then
  11997. { Not the correct label }
  11998. fMidLabel := nil;
  11999. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  12000. { If there's neither a 2nd jump nor correct label, then it's invalid
  12001. (see above table) }
  12002. Exit;
  12003. { Analyse the first block of MOVs more closely }
  12004. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  12005. if Assigned(fSecondJump) then
  12006. begin
  12007. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  12008. begin
  12009. fState := tsDetour
  12010. end
  12011. else
  12012. begin
  12013. { Need the correct mid-label for this one }
  12014. if not Assigned(fMidLabel) then
  12015. Exit;
  12016. fState := tsBranching;
  12017. end;
  12018. end
  12019. else
  12020. { No jump. but mid-label is present }
  12021. fState := tsSimple;
  12022. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  12023. begin
  12024. { Invalid or too many instructions to be worthwhile }
  12025. fState := tsInvalid;
  12026. Exit;
  12027. end;
  12028. { check further for
  12029. jCC xxx
  12030. <several movs 1>
  12031. jmp yyy
  12032. xxx:
  12033. <several movs 2>
  12034. yyy:
  12035. etc.
  12036. }
  12037. if (fState = tsBranching) and
  12038. { Estimate for required savings for extra jump }
  12039. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12040. { Only one reference is allowed for double blocks }
  12041. (AFirstLabel.getrefs = 1) then
  12042. begin
  12043. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12044. fSecondMovBlock := hp1;
  12045. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12046. begin
  12047. EvaluateBranchingType;
  12048. Exit;
  12049. end;
  12050. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12051. if (hp1.typ <> ait_label) then { should be on a jump }
  12052. begin
  12053. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12054. begin
  12055. { Need a label afterwards }
  12056. EvaluateBranchingType;
  12057. Exit;
  12058. end;
  12059. end
  12060. else
  12061. fEndLabel := hp1;
  12062. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12063. { Second jump doesn't go to the end }
  12064. fEndLabel := nil;
  12065. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12066. begin
  12067. { If there's neither a 3rd jump nor correct end label, then it's
  12068. not a invalid double block, but is a valid single branching
  12069. block (see above table) }
  12070. EvaluateBranchingType;
  12071. Exit;
  12072. end;
  12073. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12074. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12075. { Invalid or too many instructions to be worthwhile }
  12076. Exit;
  12077. Inc(CMOVScore, Count);
  12078. if Assigned(fThirdJump) then
  12079. begin
  12080. if not Assigned(fSecondJump) then
  12081. fState := tsDoubleSecondBranching
  12082. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12083. fState := tsDoubleBranchSame
  12084. else
  12085. fState := tsDoubleBranchDifferent;
  12086. end
  12087. else
  12088. fState := tsDouble;
  12089. end;
  12090. if fState = tsBranching then
  12091. EvaluateBranchingType;
  12092. end;
  12093. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12094. new register to store the constant }
  12095. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12096. var
  12097. RegSize: TSubRegister;
  12098. CurrentVal: TCGInt;
  12099. ANewReg: TRegister;
  12100. X: ShortInt;
  12101. begin
  12102. Result := False;
  12103. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12104. Exit;
  12105. if ConstCount >= MAX_CMOV_REGISTERS then
  12106. { Arrays are full }
  12107. Exit;
  12108. { Remember that CMOV can't encode 8-bit registers }
  12109. case taicpu(p).opsize of
  12110. S_W:
  12111. RegSize := R_SUBW;
  12112. S_L:
  12113. RegSize := R_SUBD;
  12114. {$ifdef x86_64}
  12115. S_Q:
  12116. RegSize := R_SUBQ;
  12117. {$endif x86_64}
  12118. else
  12119. InternalError(2021100401);
  12120. end;
  12121. { See if the value has already been reserved for another CMOV instruction }
  12122. CurrentVal := taicpu(p).oper[0]^.val;
  12123. for X := 0 to ConstCount - 1 do
  12124. if ConstVals[X] = CurrentVal then
  12125. begin
  12126. ConstRegs[ConstCount] := ConstRegs[X];
  12127. ConstSizes[ConstCount] := RegSize;
  12128. ConstVals[ConstCount] := CurrentVal;
  12129. Inc(ConstCount);
  12130. Inc(Count);
  12131. Result := True;
  12132. Exit;
  12133. end;
  12134. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12135. if ANewReg = NR_NO then
  12136. { No free registers }
  12137. Exit;
  12138. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12139. up vying for the same register }
  12140. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12141. ConstRegs[ConstCount] := ANewReg;
  12142. ConstSizes[ConstCount] := RegSize;
  12143. ConstVals[ConstCount] := CurrentVal;
  12144. Inc(ConstCount);
  12145. Inc(Count);
  12146. Result := True;
  12147. end;
  12148. destructor TCMOVTracking.Done;
  12149. begin
  12150. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12151. end;
  12152. procedure TCMOVTracking.Process(out new_p: tai);
  12153. var
  12154. Count, Writes: LongInt;
  12155. RegMatch: Boolean;
  12156. hp1, hp_new: tai;
  12157. inverted_condition, condition: TAsmCond;
  12158. begin
  12159. if (fState in [tsInvalid, tsProcessed]) then
  12160. InternalError(2023110701);
  12161. { Repurpose RegisterTracking to mark registers that we've defined }
  12162. RegisterTracking[R_INTREGISTER].Clear;
  12163. Count := 0;
  12164. Writes := 0;
  12165. condition := taicpu(fInitialJump).condition;
  12166. inverted_condition := inverse_cond(condition);
  12167. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12168. doesn't get CMOVs in this case }
  12169. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12170. begin
  12171. { Include the jump in the flag tracking }
  12172. if Assigned(fThirdJump) then
  12173. begin
  12174. if (fState = tsDoubleBranchSame) then
  12175. begin
  12176. { Will be an unconditional jump, so track to the instruction before it }
  12177. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12178. InternalError(2023110710);
  12179. end
  12180. else
  12181. hp1 := fThirdJump;
  12182. end
  12183. else
  12184. hp1 := fSecondMovBlockStop;
  12185. end
  12186. else
  12187. begin
  12188. { Include a conditional jump in the flag tracking }
  12189. if Assigned(fSecondJump) then
  12190. begin
  12191. if (fState = tsDetour) then
  12192. begin
  12193. { Will be an unconditional jump, so track to the instruction before it }
  12194. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12195. InternalError(2023110711);
  12196. end
  12197. else
  12198. hp1 := fSecondJump;
  12199. end
  12200. else
  12201. hp1 := fFirstMovBlockStop;
  12202. end;
  12203. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12204. { Process the second set of MOVs first, because if a destination
  12205. register is shared between the first and second MOV sets, it is more
  12206. efficient to turn the first one into a MOV instruction and place it
  12207. before the CMP if possible, but we won't know which registers are
  12208. shared until we've processed at least one list, so we might as well
  12209. make it the second one since that won't be modified again. }
  12210. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12211. begin
  12212. hp1 := fSecondMovBlock;
  12213. repeat
  12214. if not Assigned(hp1) then
  12215. InternalError(2018062902);
  12216. if (hp1.typ = ait_instruction) then
  12217. begin
  12218. { Extra safeguard }
  12219. if (taicpu(hp1).opcode <> A_MOV) then
  12220. InternalError(2018062903);
  12221. { Note: tsDoubleBranchDifferent is essentially identical to
  12222. tsBranching and the 2nd block is best left largely
  12223. untouched, but we need to evaluate which registers the MOVs
  12224. write to in order to track what would be complementary CMOV
  12225. pairs that can be further optimised. [Kit] }
  12226. if fState <> tsDoubleBranchDifferent then
  12227. begin
  12228. if taicpu(hp1).oper[0]^.typ = top_const then
  12229. begin
  12230. RegMatch := False;
  12231. for Count := 0 to ConstCount - 1 do
  12232. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12233. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12234. begin
  12235. RegMatch := True;
  12236. { If it's in RegisterTracking, then this register
  12237. is being used more than once and hence has
  12238. already had its value defined (it gets added to
  12239. UsedRegs through AllocRegBetween below) }
  12240. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12241. begin
  12242. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12243. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12244. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12245. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12246. ConstMovs[Count] := hp_new;
  12247. end
  12248. else
  12249. { We just need an instruction between hp_prev and hp1
  12250. where we know the register is marked as in use }
  12251. hp_new := fSecondMovBlock;
  12252. { Keep track of largest write for this register so it can be optimised later }
  12253. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12254. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12255. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12256. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12257. Break;
  12258. end;
  12259. if not RegMatch then
  12260. InternalError(2021100411);
  12261. end;
  12262. taicpu(hp1).opcode := A_CMOVcc;
  12263. taicpu(hp1).condition := condition;
  12264. end;
  12265. { Store these writes to search for duplicates later on }
  12266. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12267. Inc(Writes);
  12268. end;
  12269. fOptimizer.GetNextInstruction(hp1, hp1);
  12270. until (hp1 = fSecondMovBlockStop);
  12271. end;
  12272. { Now do the first set of MOVs }
  12273. hp1 := fFirstMovBlock;
  12274. repeat
  12275. if not Assigned(hp1) then
  12276. InternalError(2018062904);
  12277. if (hp1.typ = ait_instruction) then
  12278. begin
  12279. RegMatch := False;
  12280. { Extra safeguard }
  12281. if (taicpu(hp1).opcode <> A_MOV) then
  12282. InternalError(2018062905);
  12283. { Search through the RegWrites list to see if there are any
  12284. opposing CMOV pairs that write to the same register }
  12285. for Count := 0 to Writes - 1 do
  12286. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12287. begin
  12288. { We have a match. Keep this as a MOV }
  12289. { Move ahead in preparation }
  12290. fOptimizer.GetNextInstruction(hp1, hp1);
  12291. RegMatch := True;
  12292. Break;
  12293. end;
  12294. if RegMatch then
  12295. Continue;
  12296. if taicpu(hp1).oper[0]^.typ = top_const then
  12297. begin
  12298. for Count := 0 to ConstCount - 1 do
  12299. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12300. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12301. begin
  12302. RegMatch := True;
  12303. { If it's in RegisterTracking, then this register is
  12304. being used more than once and hence has already had
  12305. its value defined (it gets added to UsedRegs through
  12306. AllocRegBetween below) }
  12307. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12308. begin
  12309. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12310. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12311. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12312. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12313. ConstMovs[Count] := hp_new;
  12314. end
  12315. else
  12316. { We just need an instruction between hp_prev and hp1
  12317. where we know the register is marked as in use }
  12318. hp_new := fFirstMovBlock;
  12319. { Keep track of largest write for this register so it can be optimised later }
  12320. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12321. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12322. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12323. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12324. Break;
  12325. end;
  12326. if not RegMatch then
  12327. InternalError(2021100412);
  12328. end;
  12329. taicpu(hp1).opcode := A_CMOVcc;
  12330. taicpu(hp1).condition := inverted_condition;
  12331. if (fState = tsDoubleBranchDifferent) then
  12332. begin
  12333. { Store these writes to search for duplicates later on }
  12334. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12335. Inc(Writes);
  12336. end;
  12337. end;
  12338. fOptimizer.GetNextInstruction(hp1, hp1);
  12339. until (hp1 = fFirstMovBlockStop);
  12340. { Update initialisation MOVs to the smallest possible size }
  12341. for Count := 0 to ConstCount - 1 do
  12342. if Assigned(ConstMovs[Count]) then
  12343. begin
  12344. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12345. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12346. end;
  12347. case fState of
  12348. tsSimple:
  12349. begin
  12350. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12351. { No branch to delete }
  12352. end;
  12353. tsDetour:
  12354. begin
  12355. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12356. { Preserve jump }
  12357. end;
  12358. tsBranching, tsDoubleBranchDifferent:
  12359. begin
  12360. if (fState = tsBranching) then
  12361. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12362. else
  12363. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12364. taicpu(fSecondJump).opcode := A_JCC;
  12365. taicpu(fSecondJump).condition := inverted_condition;
  12366. end;
  12367. tsDouble, tsDoubleBranchSame:
  12368. begin
  12369. if (fState = tsDouble) then
  12370. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12371. else
  12372. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12373. { Delete second jump }
  12374. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12375. fOptimizer.RemoveInstruction(fSecondJump);
  12376. end;
  12377. tsDoubleSecondBranching:
  12378. begin
  12379. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12380. { Delete second jump, preserve third jump as conditional }
  12381. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12382. fOptimizer.RemoveInstruction(fSecondJump);
  12383. taicpu(fThirdJump).opcode := A_JCC;
  12384. taicpu(fThirdJump).condition := condition;
  12385. end;
  12386. else
  12387. InternalError(2023110720);
  12388. end;
  12389. { Now we can safely decrement the reference count }
  12390. tasmlabel(fLabel).decrefs;
  12391. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12392. { Remove the original jump }
  12393. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12394. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12395. fState := tsProcessed;
  12396. end;
  12397. {$endif 8086}
  12398. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12399. var
  12400. hp1,hp2: tai;
  12401. carryadd_opcode : TAsmOp;
  12402. symbol: TAsmSymbol;
  12403. increg, tmpreg: TRegister;
  12404. {$ifndef i8086}
  12405. CMOVTracking: PCMOVTracking;
  12406. hp3,hp4,hp5: tai;
  12407. {$endif i8086}
  12408. TempBool: Boolean;
  12409. begin
  12410. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12411. DoJumpOptimizations(p, TempBool) then
  12412. Exit(True);
  12413. result:=false;
  12414. if GetNextInstruction(p,hp1) then
  12415. begin
  12416. if (hp1.typ=ait_label) then
  12417. begin
  12418. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12419. Exit;
  12420. end
  12421. else if (hp1.typ<>ait_instruction) then
  12422. Exit;
  12423. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12424. if (
  12425. (
  12426. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12427. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12428. (Taicpu(hp1).oper[0]^.val=1)
  12429. ) or
  12430. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12431. ) and
  12432. GetNextInstruction(hp1,hp2) and
  12433. (hp2.typ = ait_label) and
  12434. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  12435. { jb @@1 cmc
  12436. inc/dec operand --> adc/sbb operand,0
  12437. @@1:
  12438. ... and ...
  12439. jnb @@1
  12440. inc/dec operand --> adc/sbb operand,0
  12441. @@1: }
  12442. begin
  12443. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12444. begin
  12445. case taicpu(hp1).opcode of
  12446. A_INC,
  12447. A_ADD:
  12448. carryadd_opcode:=A_ADC;
  12449. A_DEC,
  12450. A_SUB:
  12451. carryadd_opcode:=A_SBB;
  12452. else
  12453. InternalError(2021011001);
  12454. end;
  12455. Taicpu(p).clearop(0);
  12456. Taicpu(p).ops:=0;
  12457. Taicpu(p).is_jmp:=false;
  12458. Taicpu(p).opcode:=A_CMC;
  12459. Taicpu(p).condition:=C_NONE;
  12460. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12461. Taicpu(hp1).ops:=2;
  12462. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12463. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12464. else
  12465. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12466. Taicpu(hp1).loadconst(0,0);
  12467. Taicpu(hp1).opcode:=carryadd_opcode;
  12468. result:=true;
  12469. exit;
  12470. end
  12471. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12472. begin
  12473. case taicpu(hp1).opcode of
  12474. A_INC,
  12475. A_ADD:
  12476. carryadd_opcode:=A_ADC;
  12477. A_DEC,
  12478. A_SUB:
  12479. carryadd_opcode:=A_SBB;
  12480. else
  12481. InternalError(2021011002);
  12482. end;
  12483. Taicpu(hp1).ops:=2;
  12484. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12485. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12486. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12487. else
  12488. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12489. Taicpu(hp1).loadconst(0,0);
  12490. Taicpu(hp1).opcode:=carryadd_opcode;
  12491. RemoveCurrentP(p, hp1);
  12492. result:=true;
  12493. exit;
  12494. end
  12495. {
  12496. jcc @@1 setcc tmpreg
  12497. inc/dec/add/sub operand -> (movzx tmpreg)
  12498. @@1: add/sub tmpreg,operand
  12499. While this increases code size slightly, it makes the code much faster if the
  12500. jump is unpredictable
  12501. }
  12502. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12503. begin
  12504. { search for an available register which is volatile }
  12505. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12506. if increg <> NR_NO then
  12507. begin
  12508. { We don't need to check if tmpreg is in hp1 or not, because
  12509. it will be marked as in use at p (if not, this is
  12510. indictive of a compiler bug). }
  12511. TAsmLabel(symbol).decrefs;
  12512. Taicpu(p).clearop(0);
  12513. Taicpu(p).ops:=1;
  12514. Taicpu(p).is_jmp:=false;
  12515. Taicpu(p).opcode:=A_SETcc;
  12516. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12517. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12518. Taicpu(p).loadreg(0,increg);
  12519. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12520. begin
  12521. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12522. R_SUBW:
  12523. begin
  12524. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12525. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12526. end;
  12527. R_SUBD:
  12528. begin
  12529. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12530. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12531. end;
  12532. {$ifdef x86_64}
  12533. R_SUBQ:
  12534. begin
  12535. { MOVZX doesn't have a 64-bit variant, because
  12536. the 32-bit version implicitly zeroes the
  12537. upper 32-bits of the destination register }
  12538. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12539. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12540. setsubreg(tmpreg, R_SUBQ);
  12541. end;
  12542. {$endif x86_64}
  12543. else
  12544. Internalerror(2020030601);
  12545. end;
  12546. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12547. asml.InsertAfter(hp2,p);
  12548. end
  12549. else
  12550. tmpreg := increg;
  12551. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12552. begin
  12553. Taicpu(hp1).ops:=2;
  12554. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12555. end;
  12556. Taicpu(hp1).loadreg(0,tmpreg);
  12557. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12558. Result := True;
  12559. { p is no longer a Jcc instruction, so exit }
  12560. Exit;
  12561. end;
  12562. end;
  12563. end;
  12564. { Detect the following:
  12565. jmp<cond> @Lbl1
  12566. jmp @Lbl2
  12567. ...
  12568. @Lbl1:
  12569. ret
  12570. Change to:
  12571. jmp<inv_cond> @Lbl2
  12572. ret
  12573. }
  12574. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12575. begin
  12576. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12577. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12578. MatchInstruction(hp2,A_RET,[S_NO]) then
  12579. begin
  12580. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12581. { Change label address to that of the unconditional jump }
  12582. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12583. TAsmLabel(symbol).DecRefs;
  12584. taicpu(hp1).opcode := A_RET;
  12585. taicpu(hp1).is_jmp := false;
  12586. taicpu(hp1).ops := taicpu(hp2).ops;
  12587. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12588. case taicpu(hp2).ops of
  12589. 0:
  12590. taicpu(hp1).clearop(0);
  12591. 1:
  12592. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12593. else
  12594. internalerror(2016041302);
  12595. end;
  12596. end;
  12597. {$ifndef i8086}
  12598. end
  12599. {
  12600. convert
  12601. j<c> .L1
  12602. mov 1,reg
  12603. jmp .L2
  12604. .L1
  12605. mov 0,reg
  12606. .L2
  12607. into
  12608. mov 0,reg
  12609. set<not(c)> reg
  12610. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12611. would destroy the flag contents
  12612. }
  12613. else if MatchInstruction(hp1,A_MOV,[]) and
  12614. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12615. {$ifdef i386}
  12616. (
  12617. { Under i386, ESI, EDI, EBP and ESP
  12618. don't have an 8-bit representation }
  12619. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12620. ) and
  12621. {$endif i386}
  12622. (taicpu(hp1).oper[0]^.val=1) and
  12623. GetNextInstruction(hp1,hp2) and
  12624. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12625. GetNextInstruction(hp2,hp3) and
  12626. (hp3.typ=ait_label) and
  12627. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12628. (tai_label(hp3).labsym.getrefs=1) and
  12629. GetNextInstruction(hp3,hp4) and
  12630. MatchInstruction(hp4,A_MOV,[]) and
  12631. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12632. (taicpu(hp4).oper[0]^.val=0) and
  12633. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12634. GetNextInstruction(hp4,hp5) and
  12635. (hp5.typ=ait_label) and
  12636. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12637. (tai_label(hp5).labsym.getrefs=1) then
  12638. begin
  12639. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12640. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12641. { remove last label }
  12642. RemoveInstruction(hp5);
  12643. { remove second label }
  12644. RemoveInstruction(hp3);
  12645. { remove jmp }
  12646. RemoveInstruction(hp2);
  12647. if taicpu(hp1).opsize=S_B then
  12648. RemoveInstruction(hp1)
  12649. else
  12650. taicpu(hp1).loadconst(0,0);
  12651. taicpu(hp4).opcode:=A_SETcc;
  12652. taicpu(hp4).opsize:=S_B;
  12653. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12654. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12655. taicpu(hp4).opercnt:=1;
  12656. taicpu(hp4).ops:=1;
  12657. taicpu(hp4).freeop(1);
  12658. RemoveCurrentP(p);
  12659. Result:=true;
  12660. exit;
  12661. end
  12662. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12663. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12664. begin
  12665. { check for
  12666. jCC xxx
  12667. <several movs>
  12668. xxx:
  12669. Also spot:
  12670. Jcc xxx
  12671. <several movs>
  12672. jmp xxx
  12673. Change to:
  12674. <several cmovs with inverted condition>
  12675. jmp xxx (only for the 2nd case)
  12676. }
  12677. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12678. if CMOVTracking^.State <> tsInvalid then
  12679. begin
  12680. CMovTracking^.Process(p);
  12681. Result := True;
  12682. end;
  12683. CMOVTracking^.Done;
  12684. {$endif i8086}
  12685. end;
  12686. end;
  12687. end;
  12688. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12689. var
  12690. hp1,hp2,hp3: tai;
  12691. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12692. NewSize: TOpSize;
  12693. NewRegSize: TSubRegister;
  12694. Limit: TCgInt;
  12695. SwapOper: POper;
  12696. begin
  12697. result:=false;
  12698. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12699. GetNextInstruction(p,hp1) and
  12700. (hp1.typ = ait_instruction);
  12701. if reg_and_hp1_is_instr and
  12702. (
  12703. (taicpu(hp1).opcode <> A_LEA) or
  12704. { If the LEA instruction can be converted into an arithmetic instruction,
  12705. it may be possible to then fold it. }
  12706. (
  12707. { If the flags register is in use, don't change the instruction
  12708. to an ADD otherwise this will scramble the flags. [Kit] }
  12709. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12710. ConvertLEA(taicpu(hp1))
  12711. )
  12712. ) and
  12713. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12714. GetNextInstruction(hp1,hp2) and
  12715. MatchInstruction(hp2,A_MOV,[]) and
  12716. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12717. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12718. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12719. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12720. {$ifdef i386}
  12721. { not all registers have byte size sub registers on i386 }
  12722. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12723. {$endif i386}
  12724. (((taicpu(hp1).ops=2) and
  12725. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12726. ((taicpu(hp1).ops=1) and
  12727. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12728. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12729. begin
  12730. { change movsX/movzX reg/ref, reg2
  12731. add/sub/or/... reg3/$const, reg2
  12732. mov reg2 reg/ref
  12733. to add/sub/or/... reg3/$const, reg/ref }
  12734. { by example:
  12735. movswl %si,%eax movswl %si,%eax p
  12736. decl %eax addl %edx,%eax hp1
  12737. movw %ax,%si movw %ax,%si hp2
  12738. ->
  12739. movswl %si,%eax movswl %si,%eax p
  12740. decw %eax addw %edx,%eax hp1
  12741. movw %ax,%si movw %ax,%si hp2
  12742. }
  12743. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12744. {
  12745. ->
  12746. movswl %si,%eax movswl %si,%eax p
  12747. decw %si addw %dx,%si hp1
  12748. movw %ax,%si movw %ax,%si hp2
  12749. }
  12750. case taicpu(hp1).ops of
  12751. 1:
  12752. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12753. 2:
  12754. begin
  12755. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12756. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12757. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12758. end;
  12759. else
  12760. internalerror(2008042702);
  12761. end;
  12762. {
  12763. ->
  12764. decw %si addw %dx,%si p
  12765. }
  12766. DebugMsg(SPeepholeOptimization + 'var3',p);
  12767. RemoveCurrentP(p, hp1);
  12768. RemoveInstruction(hp2);
  12769. Result := True;
  12770. Exit;
  12771. end;
  12772. if reg_and_hp1_is_instr and
  12773. (taicpu(hp1).opcode = A_MOV) and
  12774. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12775. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12776. {$ifdef x86_64}
  12777. { check for implicit extension to 64 bit }
  12778. or
  12779. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12780. (taicpu(hp1).opsize=S_Q) and
  12781. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12782. )
  12783. {$endif x86_64}
  12784. )
  12785. then
  12786. begin
  12787. { change
  12788. movx %reg1,%reg2
  12789. mov %reg2,%reg3
  12790. dealloc %reg2
  12791. into
  12792. movx %reg,%reg3
  12793. }
  12794. TransferUsedRegs(TmpUsedRegs);
  12795. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12796. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12797. begin
  12798. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12799. {$ifdef x86_64}
  12800. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12801. (taicpu(hp1).opsize=S_Q) then
  12802. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12803. else
  12804. {$endif x86_64}
  12805. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12806. RemoveInstruction(hp1);
  12807. Result := True;
  12808. Exit;
  12809. end;
  12810. end;
  12811. if reg_and_hp1_is_instr and
  12812. ((taicpu(hp1).opcode=A_MOV) or
  12813. (taicpu(hp1).opcode=A_ADD) or
  12814. (taicpu(hp1).opcode=A_SUB) or
  12815. (taicpu(hp1).opcode=A_CMP) or
  12816. (taicpu(hp1).opcode=A_OR) or
  12817. (taicpu(hp1).opcode=A_XOR) or
  12818. (taicpu(hp1).opcode=A_AND)
  12819. ) and
  12820. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12821. begin
  12822. AndTest := (taicpu(hp1).opcode=A_AND) and
  12823. GetNextInstruction(hp1, hp2) and
  12824. (hp2.typ = ait_instruction) and
  12825. (
  12826. (
  12827. (taicpu(hp2).opcode=A_TEST) and
  12828. (
  12829. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12830. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12831. (
  12832. { If the AND and TEST instructions share a constant, this is also valid }
  12833. (taicpu(hp1).oper[0]^.typ = top_const) and
  12834. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12835. )
  12836. ) and
  12837. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12838. ) or
  12839. (
  12840. (taicpu(hp2).opcode=A_CMP) and
  12841. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12842. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12843. )
  12844. );
  12845. { change
  12846. movx (oper),%reg2
  12847. and $x,%reg2
  12848. test %reg2,%reg2
  12849. dealloc %reg2
  12850. into
  12851. op %reg1,%reg3
  12852. if the second op accesses only the bits stored in reg1
  12853. }
  12854. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12855. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12856. (taicpu(hp1).oper[0]^.typ = top_const) and
  12857. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12858. AndTest then
  12859. begin
  12860. { Check if the AND constant is in range }
  12861. case taicpu(p).opsize of
  12862. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12863. begin
  12864. NewSize := S_B;
  12865. Limit := $FF;
  12866. end;
  12867. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12868. begin
  12869. NewSize := S_W;
  12870. Limit := $FFFF;
  12871. end;
  12872. {$ifdef x86_64}
  12873. S_LQ:
  12874. begin
  12875. NewSize := S_L;
  12876. Limit := $FFFFFFFF;
  12877. end;
  12878. {$endif x86_64}
  12879. else
  12880. InternalError(2021120303);
  12881. end;
  12882. if (
  12883. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12884. { Check for negative operands }
  12885. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12886. ) and
  12887. GetNextInstruction(hp2,hp3) and
  12888. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12889. (taicpu(hp3).condition in [C_E,C_NE]) then
  12890. begin
  12891. TransferUsedRegs(TmpUsedRegs);
  12892. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12893. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12894. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12895. begin
  12896. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12897. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12898. taicpu(hp1).opcode := A_TEST;
  12899. taicpu(hp1).opsize := NewSize;
  12900. RemoveInstruction(hp2);
  12901. RemoveCurrentP(p, hp1);
  12902. Result:=true;
  12903. exit;
  12904. end;
  12905. end;
  12906. end;
  12907. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12908. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12909. (taicpu(hp1).opsize=S_B)) or
  12910. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12911. (taicpu(hp1).opsize=S_W))
  12912. {$ifdef x86_64}
  12913. or ((taicpu(p).opsize=S_LQ) and
  12914. (taicpu(hp1).opsize=S_L))
  12915. {$endif x86_64}
  12916. ) and
  12917. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12918. begin
  12919. { change
  12920. movx %reg1,%reg2
  12921. op %reg2,%reg3
  12922. dealloc %reg2
  12923. into
  12924. op %reg1,%reg3
  12925. if the second op accesses only the bits stored in reg1
  12926. }
  12927. TransferUsedRegs(TmpUsedRegs);
  12928. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12929. if AndTest then
  12930. begin
  12931. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12932. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12933. end
  12934. else
  12935. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12936. if not RegUsed then
  12937. begin
  12938. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12939. if taicpu(p).oper[0]^.typ=top_reg then
  12940. begin
  12941. case taicpu(hp1).opsize of
  12942. S_B:
  12943. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12944. S_W:
  12945. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12946. S_L:
  12947. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12948. else
  12949. Internalerror(2020102301);
  12950. end;
  12951. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12952. end
  12953. else
  12954. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12955. RemoveCurrentP(p);
  12956. if AndTest then
  12957. RemoveInstruction(hp2);
  12958. result:=true;
  12959. exit;
  12960. end;
  12961. end
  12962. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12963. (
  12964. { Bitwise operations only }
  12965. (taicpu(hp1).opcode=A_AND) or
  12966. (taicpu(hp1).opcode=A_TEST) or
  12967. (
  12968. (taicpu(hp1).oper[0]^.typ = top_const) and
  12969. (
  12970. (taicpu(hp1).opcode=A_OR) or
  12971. (taicpu(hp1).opcode=A_XOR)
  12972. )
  12973. )
  12974. ) and
  12975. (
  12976. (taicpu(hp1).oper[0]^.typ = top_const) or
  12977. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12978. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12979. ) then
  12980. begin
  12981. { change
  12982. movx %reg2,%reg2
  12983. op const,%reg2
  12984. into
  12985. op const,%reg2 (smaller version)
  12986. movx %reg2,%reg2
  12987. also change
  12988. movx %reg1,%reg2
  12989. and/test (oper),%reg2
  12990. dealloc %reg2
  12991. into
  12992. and/test (oper),%reg1
  12993. }
  12994. case taicpu(p).opsize of
  12995. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12996. begin
  12997. NewSize := S_B;
  12998. NewRegSize := R_SUBL;
  12999. Limit := $FF;
  13000. end;
  13001. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13002. begin
  13003. NewSize := S_W;
  13004. NewRegSize := R_SUBW;
  13005. Limit := $FFFF;
  13006. end;
  13007. {$ifdef x86_64}
  13008. S_LQ:
  13009. begin
  13010. NewSize := S_L;
  13011. NewRegSize := R_SUBD;
  13012. Limit := $FFFFFFFF;
  13013. end;
  13014. {$endif x86_64}
  13015. else
  13016. Internalerror(2021120302);
  13017. end;
  13018. TransferUsedRegs(TmpUsedRegs);
  13019. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13020. if AndTest then
  13021. begin
  13022. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13023. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13024. end
  13025. else
  13026. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13027. if
  13028. (
  13029. (taicpu(p).opcode = A_MOVZX) and
  13030. (
  13031. (taicpu(hp1).opcode=A_AND) or
  13032. (taicpu(hp1).opcode=A_TEST)
  13033. ) and
  13034. not (
  13035. { If both are references, then the final instruction will have
  13036. both operands as references, which is not allowed }
  13037. (taicpu(p).oper[0]^.typ = top_ref) and
  13038. (taicpu(hp1).oper[0]^.typ = top_ref)
  13039. ) and
  13040. not RegUsed
  13041. ) or
  13042. (
  13043. (
  13044. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13045. not RegUsed
  13046. ) and
  13047. (taicpu(p).oper[0]^.typ = top_reg) and
  13048. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13049. (taicpu(hp1).oper[0]^.typ = top_const) and
  13050. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13051. ) then
  13052. begin
  13053. {$if defined(i386) or defined(i8086)}
  13054. { If the target size is 8-bit, make sure we can actually encode it }
  13055. 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
  13056. Exit;
  13057. {$endif i386 or i8086}
  13058. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13059. taicpu(hp1).opsize := NewSize;
  13060. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13061. if AndTest then
  13062. begin
  13063. RemoveInstruction(hp2);
  13064. if not RegUsed then
  13065. begin
  13066. taicpu(hp1).opcode := A_TEST;
  13067. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13068. begin
  13069. { Make sure the reference is the second operand }
  13070. SwapOper := taicpu(hp1).oper[0];
  13071. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13072. taicpu(hp1).oper[1] := SwapOper;
  13073. end;
  13074. end;
  13075. end;
  13076. case taicpu(hp1).oper[0]^.typ of
  13077. top_reg:
  13078. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13079. top_const:
  13080. { For the AND/TEST case }
  13081. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13082. else
  13083. ;
  13084. end;
  13085. if RegUsed then
  13086. begin
  13087. AsmL.Remove(p);
  13088. AsmL.InsertAfter(p, hp1);
  13089. p := hp1;
  13090. end
  13091. else
  13092. RemoveCurrentP(p, hp1);
  13093. result:=true;
  13094. exit;
  13095. end;
  13096. end;
  13097. end;
  13098. if reg_and_hp1_is_instr and
  13099. (taicpu(p).oper[0]^.typ = top_reg) and
  13100. (
  13101. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13102. ) and
  13103. (taicpu(hp1).oper[0]^.typ = top_const) and
  13104. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13105. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13106. { Minimum shift value allowed is the bit difference between the sizes }
  13107. (taicpu(hp1).oper[0]^.val >=
  13108. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13109. 8 * (
  13110. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13111. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13112. )
  13113. ) then
  13114. begin
  13115. { For:
  13116. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13117. shl/sal ##, %reg1
  13118. Remove the movsx/movzx instruction if the shift overwrites the
  13119. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13120. }
  13121. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13122. RemoveCurrentP(p, hp1);
  13123. Result := True;
  13124. Exit;
  13125. end
  13126. else if reg_and_hp1_is_instr and
  13127. (taicpu(p).oper[0]^.typ = top_reg) and
  13128. (
  13129. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13130. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13131. ) and
  13132. (taicpu(hp1).oper[0]^.typ = top_const) and
  13133. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13134. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13135. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13136. (taicpu(hp1).oper[0]^.val <
  13137. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13138. 8 * (
  13139. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13140. )
  13141. ) then
  13142. begin
  13143. { For:
  13144. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13145. sar ##, %reg1 shr ##, %reg1
  13146. Move the shift to before the movx instruction if the shift value
  13147. is not too large.
  13148. }
  13149. asml.Remove(hp1);
  13150. asml.InsertBefore(hp1, p);
  13151. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13152. case taicpu(p).opsize of
  13153. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13154. taicpu(hp1).opsize := S_B;
  13155. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13156. taicpu(hp1).opsize := S_W;
  13157. {$ifdef x86_64}
  13158. S_LQ:
  13159. taicpu(hp1).opsize := S_L;
  13160. {$endif}
  13161. else
  13162. InternalError(2020112401);
  13163. end;
  13164. if (taicpu(hp1).opcode = A_SHR) then
  13165. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13166. else
  13167. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13168. Result := True;
  13169. end;
  13170. if reg_and_hp1_is_instr and
  13171. (taicpu(p).oper[0]^.typ = top_reg) and
  13172. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13173. (
  13174. (taicpu(hp1).opcode = taicpu(p).opcode)
  13175. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13176. {$ifdef x86_64}
  13177. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13178. {$endif x86_64}
  13179. ) then
  13180. begin
  13181. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13182. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13183. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13184. begin
  13185. {
  13186. For example:
  13187. movzbw %al,%ax
  13188. movzwl %ax,%eax
  13189. Compress into:
  13190. movzbl %al,%eax
  13191. }
  13192. RegUsed := False;
  13193. case taicpu(p).opsize of
  13194. S_BW:
  13195. case taicpu(hp1).opsize of
  13196. S_WL:
  13197. begin
  13198. taicpu(p).opsize := S_BL;
  13199. RegUsed := True;
  13200. end;
  13201. {$ifdef x86_64}
  13202. S_WQ:
  13203. begin
  13204. if taicpu(p).opcode = A_MOVZX then
  13205. begin
  13206. taicpu(p).opsize := S_BL;
  13207. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13208. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13209. end
  13210. else
  13211. taicpu(p).opsize := S_BQ;
  13212. RegUsed := True;
  13213. end;
  13214. {$endif x86_64}
  13215. else
  13216. ;
  13217. end;
  13218. {$ifdef x86_64}
  13219. S_BL:
  13220. case taicpu(hp1).opsize of
  13221. S_LQ:
  13222. begin
  13223. if taicpu(p).opcode = A_MOVZX then
  13224. begin
  13225. taicpu(p).opsize := S_BL;
  13226. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13227. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13228. end
  13229. else
  13230. taicpu(p).opsize := S_BQ;
  13231. RegUsed := True;
  13232. end;
  13233. else
  13234. ;
  13235. end;
  13236. S_WL:
  13237. case taicpu(hp1).opsize of
  13238. S_LQ:
  13239. begin
  13240. if taicpu(p).opcode = A_MOVZX then
  13241. begin
  13242. taicpu(p).opsize := S_WL;
  13243. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13244. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13245. end
  13246. else
  13247. taicpu(p).opsize := S_WQ;
  13248. RegUsed := True;
  13249. end;
  13250. else
  13251. ;
  13252. end;
  13253. {$endif x86_64}
  13254. else
  13255. ;
  13256. end;
  13257. if RegUsed then
  13258. begin
  13259. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13260. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13261. RemoveInstruction(hp1);
  13262. Result := True;
  13263. Exit;
  13264. end;
  13265. end;
  13266. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13267. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13268. GetNextInstruction(hp1, hp2) and
  13269. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13270. (
  13271. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13272. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13273. {$ifdef x86_64}
  13274. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13275. {$endif x86_64}
  13276. ) and
  13277. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13278. (
  13279. (
  13280. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13281. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13282. ) or
  13283. (
  13284. { Only allow the operands in reverse order for TEST instructions }
  13285. (taicpu(hp2).opcode = A_TEST) and
  13286. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13287. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13288. )
  13289. ) then
  13290. begin
  13291. {
  13292. For example:
  13293. movzbl %al,%eax
  13294. movzbl (ref),%edx
  13295. andl %edx,%eax
  13296. (%edx deallocated)
  13297. Change to:
  13298. andb (ref),%al
  13299. movzbl %al,%eax
  13300. Rules are:
  13301. - First two instructions have the same opcode and opsize
  13302. - First instruction's operands are the same super-register
  13303. - Second instruction operates on a different register
  13304. - Third instruction is AND, OR, XOR or TEST
  13305. - Third instruction's operands are the destination registers of the first two instructions
  13306. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13307. - Second instruction's destination register is deallocated afterwards
  13308. }
  13309. TransferUsedRegs(TmpUsedRegs);
  13310. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13311. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13312. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13313. begin
  13314. case taicpu(p).opsize of
  13315. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13316. NewSize := S_B;
  13317. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13318. NewSize := S_W;
  13319. {$ifdef x86_64}
  13320. S_LQ:
  13321. NewSize := S_L;
  13322. {$endif x86_64}
  13323. else
  13324. InternalError(2021120301);
  13325. end;
  13326. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13327. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13328. taicpu(hp2).opsize := NewSize;
  13329. RemoveInstruction(hp1);
  13330. { With TEST, it's best to keep the MOVX instruction at the top }
  13331. if (taicpu(hp2).opcode <> A_TEST) then
  13332. begin
  13333. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13334. asml.Remove(p);
  13335. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13336. asml.InsertAfter(p, hp2);
  13337. p := hp2;
  13338. end
  13339. else
  13340. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13341. Result := True;
  13342. Exit;
  13343. end;
  13344. end;
  13345. end;
  13346. if taicpu(p).opcode=A_MOVZX then
  13347. begin
  13348. { removes superfluous And's after movzx's }
  13349. if reg_and_hp1_is_instr and
  13350. (taicpu(hp1).opcode = A_AND) and
  13351. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13352. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13353. {$ifdef x86_64}
  13354. { check for implicit extension to 64 bit }
  13355. or
  13356. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13357. (taicpu(hp1).opsize=S_Q) and
  13358. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13359. )
  13360. {$endif x86_64}
  13361. )
  13362. then
  13363. begin
  13364. case taicpu(p).opsize Of
  13365. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13366. if (taicpu(hp1).oper[0]^.val = $ff) then
  13367. begin
  13368. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13369. RemoveInstruction(hp1);
  13370. Result:=true;
  13371. exit;
  13372. end;
  13373. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13374. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13375. begin
  13376. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13377. RemoveInstruction(hp1);
  13378. Result:=true;
  13379. exit;
  13380. end;
  13381. {$ifdef x86_64}
  13382. S_LQ:
  13383. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13384. begin
  13385. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13386. RemoveInstruction(hp1);
  13387. Result:=true;
  13388. exit;
  13389. end;
  13390. {$endif x86_64}
  13391. else
  13392. ;
  13393. end;
  13394. { we cannot get rid of the and, but can we get rid of the movz ?}
  13395. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13396. begin
  13397. case taicpu(p).opsize Of
  13398. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13399. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13400. begin
  13401. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13402. RemoveCurrentP(p,hp1);
  13403. Result:=true;
  13404. exit;
  13405. end;
  13406. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13407. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13408. begin
  13409. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13410. RemoveCurrentP(p,hp1);
  13411. Result:=true;
  13412. exit;
  13413. end;
  13414. {$ifdef x86_64}
  13415. S_LQ:
  13416. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13417. begin
  13418. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13419. RemoveCurrentP(p,hp1);
  13420. Result:=true;
  13421. exit;
  13422. end;
  13423. {$endif x86_64}
  13424. else
  13425. ;
  13426. end;
  13427. end;
  13428. end;
  13429. { changes some movzx constructs to faster synonyms (all examples
  13430. are given with eax/ax, but are also valid for other registers)}
  13431. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13432. begin
  13433. case taicpu(p).opsize of
  13434. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13435. (the machine code is equivalent to movzbl %al,%eax), but the
  13436. code generator still generates that assembler instruction and
  13437. it is silently converted. This should probably be checked.
  13438. [Kit] }
  13439. S_BW:
  13440. begin
  13441. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13442. (
  13443. not IsMOVZXAcceptable
  13444. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13445. or (
  13446. (cs_opt_size in current_settings.optimizerswitches) and
  13447. (taicpu(p).oper[1]^.reg = NR_AX)
  13448. )
  13449. ) then
  13450. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13451. begin
  13452. DebugMsg(SPeepholeOptimization + 'var7',p);
  13453. taicpu(p).opcode := A_AND;
  13454. taicpu(p).changeopsize(S_W);
  13455. taicpu(p).loadConst(0,$ff);
  13456. Result := True;
  13457. end
  13458. else if not IsMOVZXAcceptable and
  13459. GetNextInstruction(p, hp1) and
  13460. (tai(hp1).typ = ait_instruction) and
  13461. (taicpu(hp1).opcode = A_AND) and
  13462. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13463. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13464. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13465. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13466. begin
  13467. DebugMsg(SPeepholeOptimization + 'var8',p);
  13468. taicpu(p).opcode := A_MOV;
  13469. taicpu(p).changeopsize(S_W);
  13470. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13471. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13472. Result := True;
  13473. end;
  13474. end;
  13475. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13476. S_BL:
  13477. if not IsMOVZXAcceptable then
  13478. begin
  13479. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13480. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13481. begin
  13482. DebugMsg(SPeepholeOptimization + 'var9',p);
  13483. taicpu(p).opcode := A_AND;
  13484. taicpu(p).changeopsize(S_L);
  13485. taicpu(p).loadConst(0,$ff);
  13486. Result := True;
  13487. end
  13488. else if GetNextInstruction(p, hp1) and
  13489. (tai(hp1).typ = ait_instruction) and
  13490. (taicpu(hp1).opcode = A_AND) and
  13491. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13492. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13493. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13494. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13495. begin
  13496. DebugMsg(SPeepholeOptimization + 'var10',p);
  13497. taicpu(p).opcode := A_MOV;
  13498. taicpu(p).changeopsize(S_L);
  13499. { do not use R_SUBWHOLE
  13500. as movl %rdx,%eax
  13501. is invalid in assembler PM }
  13502. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13503. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13504. Result := True;
  13505. end;
  13506. end;
  13507. {$endif i8086}
  13508. S_WL:
  13509. if not IsMOVZXAcceptable then
  13510. begin
  13511. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13512. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13513. begin
  13514. DebugMsg(SPeepholeOptimization + 'var11',p);
  13515. taicpu(p).opcode := A_AND;
  13516. taicpu(p).changeopsize(S_L);
  13517. taicpu(p).loadConst(0,$ffff);
  13518. Result := True;
  13519. end
  13520. else if GetNextInstruction(p, hp1) and
  13521. (tai(hp1).typ = ait_instruction) and
  13522. (taicpu(hp1).opcode = A_AND) and
  13523. (taicpu(hp1).oper[0]^.typ = top_const) and
  13524. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13525. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13526. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13527. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13528. begin
  13529. DebugMsg(SPeepholeOptimization + 'var12',p);
  13530. taicpu(p).opcode := A_MOV;
  13531. taicpu(p).changeopsize(S_L);
  13532. { do not use R_SUBWHOLE
  13533. as movl %rdx,%eax
  13534. is invalid in assembler PM }
  13535. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13536. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13537. Result := True;
  13538. end;
  13539. end;
  13540. else
  13541. InternalError(2017050705);
  13542. end;
  13543. end
  13544. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13545. begin
  13546. if GetNextInstruction(p, hp1) and
  13547. (tai(hp1).typ = ait_instruction) and
  13548. (taicpu(hp1).opcode = A_AND) and
  13549. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13550. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13551. begin
  13552. case taicpu(p).opsize Of
  13553. S_BL:
  13554. if (taicpu(hp1).opsize <> S_L) or
  13555. (taicpu(hp1).oper[0]^.val > $FF) then
  13556. begin
  13557. DebugMsg(SPeepholeOptimization + 'var13',p);
  13558. taicpu(hp1).changeopsize(S_L);
  13559. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13560. Include(OptsToCheck, aoc_ForceNewIteration);
  13561. end;
  13562. S_WL:
  13563. if (taicpu(hp1).opsize <> S_L) or
  13564. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13565. begin
  13566. DebugMsg(SPeepholeOptimization + 'var14',p);
  13567. taicpu(hp1).changeopsize(S_L);
  13568. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13569. Include(OptsToCheck, aoc_ForceNewIteration);
  13570. end;
  13571. S_BW:
  13572. if (taicpu(hp1).opsize <> S_W) or
  13573. (taicpu(hp1).oper[0]^.val > $FF) then
  13574. begin
  13575. DebugMsg(SPeepholeOptimization + 'var15',p);
  13576. taicpu(hp1).changeopsize(S_W);
  13577. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13578. Include(OptsToCheck, aoc_ForceNewIteration);
  13579. end;
  13580. else
  13581. Internalerror(2017050704)
  13582. end;
  13583. end;
  13584. end;
  13585. end;
  13586. end;
  13587. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13588. var
  13589. hp1, hp2 : tai;
  13590. MaskLength : Cardinal;
  13591. MaskedBits : TCgInt;
  13592. ActiveReg : TRegister;
  13593. begin
  13594. Result:=false;
  13595. { There are no optimisations for reference targets }
  13596. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13597. Exit;
  13598. while GetNextInstruction(p, hp1) and
  13599. (hp1.typ = ait_instruction) do
  13600. begin
  13601. if (taicpu(p).oper[0]^.typ = top_const) then
  13602. begin
  13603. case taicpu(hp1).opcode of
  13604. A_AND:
  13605. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13606. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13607. { the second register must contain the first one, so compare their subreg types }
  13608. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13609. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13610. { change
  13611. and const1, reg
  13612. and const2, reg
  13613. to
  13614. and (const1 and const2), reg
  13615. }
  13616. begin
  13617. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13618. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13619. RemoveCurrentP(p, hp1);
  13620. Result:=true;
  13621. exit;
  13622. end;
  13623. A_CMP:
  13624. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13625. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13626. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13627. { Just check that the condition on the next instruction is compatible }
  13628. GetNextInstruction(hp1, hp2) and
  13629. (hp2.typ = ait_instruction) and
  13630. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13631. then
  13632. { change
  13633. and 2^n, reg
  13634. cmp 2^n, reg
  13635. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13636. to
  13637. and 2^n, reg
  13638. test reg, reg
  13639. j(~c) / set(~c) / cmov(~c)
  13640. }
  13641. begin
  13642. { Keep TEST instruction in, rather than remove it, because
  13643. it may trigger other optimisations such as MovAndTest2Test }
  13644. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13645. taicpu(hp1).opcode := A_TEST;
  13646. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13647. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13648. Result := True;
  13649. Exit;
  13650. end
  13651. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13652. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13653. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13654. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13655. { change
  13656. and $ff/$ff/$ffff, reg
  13657. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13658. dealloc reg
  13659. to
  13660. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13661. }
  13662. begin
  13663. TransferUsedRegs(TmpUsedRegs);
  13664. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13665. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13666. begin
  13667. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13668. case taicpu(p).oper[0]^.val of
  13669. $ff:
  13670. begin
  13671. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13672. taicpu(hp1).opsize:=S_B;
  13673. end;
  13674. $ffff:
  13675. begin
  13676. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13677. taicpu(hp1).opsize:=S_W;
  13678. end;
  13679. $ffffffff:
  13680. begin
  13681. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13682. taicpu(hp1).opsize:=S_L;
  13683. end;
  13684. else
  13685. Internalerror(2023030401);
  13686. end;
  13687. RemoveCurrentP(p);
  13688. Result := True;
  13689. Exit;
  13690. end;
  13691. end;
  13692. A_MOVZX:
  13693. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13694. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13695. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13696. (
  13697. (
  13698. (taicpu(p).opsize=S_W) and
  13699. (taicpu(hp1).opsize=S_BW)
  13700. ) or
  13701. (
  13702. (taicpu(p).opsize=S_L) and
  13703. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13704. )
  13705. {$ifdef x86_64}
  13706. or
  13707. (
  13708. (taicpu(p).opsize=S_Q) and
  13709. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13710. )
  13711. {$endif x86_64}
  13712. ) then
  13713. begin
  13714. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13715. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13716. ) or
  13717. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13718. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13719. then
  13720. begin
  13721. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13722. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13723. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13724. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13725. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13726. }
  13727. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13728. RemoveInstruction(hp1);
  13729. { See if there are other optimisations possible }
  13730. Continue;
  13731. end;
  13732. end;
  13733. A_SHL:
  13734. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13735. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13736. begin
  13737. {$ifopt R+}
  13738. {$define RANGE_WAS_ON}
  13739. {$R-}
  13740. {$endif}
  13741. { get length of potential and mask }
  13742. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13743. { really a mask? }
  13744. {$ifdef RANGE_WAS_ON}
  13745. {$R+}
  13746. {$endif}
  13747. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13748. { unmasked part shifted out? }
  13749. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13750. begin
  13751. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13752. RemoveCurrentP(p, hp1);
  13753. Result:=true;
  13754. exit;
  13755. end;
  13756. end;
  13757. A_SHR:
  13758. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13759. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13760. (taicpu(hp1).oper[0]^.val <= 63) then
  13761. begin
  13762. { Does SHR combined with the AND cover all the bits?
  13763. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13764. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13765. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13766. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13767. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13768. begin
  13769. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13770. RemoveCurrentP(p, hp1);
  13771. Result := True;
  13772. Exit;
  13773. end;
  13774. end;
  13775. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13776. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13777. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13778. begin
  13779. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13780. (
  13781. (
  13782. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13783. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13784. ) or (
  13785. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13786. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13787. {$ifdef x86_64}
  13788. ) or (
  13789. (taicpu(hp1).opsize = S_LQ) and
  13790. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13791. {$endif x86_64}
  13792. )
  13793. ) then
  13794. begin
  13795. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13796. begin
  13797. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13798. RemoveInstruction(hp1);
  13799. { See if there are other optimisations possible }
  13800. Continue;
  13801. end;
  13802. { The super-registers are the same though.
  13803. Note that this change by itself doesn't improve
  13804. code speed, but it opens up other optimisations. }
  13805. {$ifdef x86_64}
  13806. { Convert 64-bit register to 32-bit }
  13807. case taicpu(hp1).opsize of
  13808. S_BQ:
  13809. begin
  13810. taicpu(hp1).opsize := S_BL;
  13811. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13812. end;
  13813. S_WQ:
  13814. begin
  13815. taicpu(hp1).opsize := S_WL;
  13816. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13817. end
  13818. else
  13819. ;
  13820. end;
  13821. {$endif x86_64}
  13822. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13823. taicpu(hp1).opcode := A_MOVZX;
  13824. { See if there are other optimisations possible }
  13825. Continue;
  13826. end;
  13827. end;
  13828. else
  13829. ;
  13830. end;
  13831. end
  13832. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13833. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13834. begin
  13835. {$ifdef x86_64}
  13836. if (taicpu(p).opsize = S_Q) then
  13837. begin
  13838. { Never necessary }
  13839. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13840. RemoveCurrentP(p, hp1);
  13841. Result := True;
  13842. Exit;
  13843. end;
  13844. {$endif x86_64}
  13845. { Forward check to determine necessity of and %reg,%reg }
  13846. TransferUsedRegs(TmpUsedRegs);
  13847. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13848. { Saves on a bunch of dereferences }
  13849. ActiveReg := taicpu(p).oper[1]^.reg;
  13850. case taicpu(hp1).opcode of
  13851. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13852. if (
  13853. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13854. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13855. ) and
  13856. (
  13857. (taicpu(hp1).opcode <> A_MOV) or
  13858. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13859. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13860. ) and
  13861. not (
  13862. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13863. (taicpu(hp1).opcode = A_MOV) and
  13864. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13865. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13866. ) and
  13867. (
  13868. (
  13869. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13870. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13871. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13872. ) or
  13873. (
  13874. {$ifdef x86_64}
  13875. (
  13876. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13877. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13878. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13879. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13880. ) and
  13881. {$endif x86_64}
  13882. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13883. )
  13884. ) then
  13885. begin
  13886. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13887. RemoveCurrentP(p, hp1);
  13888. Result := True;
  13889. Exit;
  13890. end;
  13891. A_ADD,
  13892. A_AND,
  13893. A_BSF,
  13894. A_BSR,
  13895. A_BTC,
  13896. A_BTR,
  13897. A_BTS,
  13898. A_OR,
  13899. A_SUB,
  13900. A_XOR:
  13901. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13902. if (
  13903. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13904. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13905. ) and
  13906. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13907. begin
  13908. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13909. RemoveCurrentP(p, hp1);
  13910. Result := True;
  13911. Exit;
  13912. end;
  13913. A_CMP,
  13914. A_TEST:
  13915. if (
  13916. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13917. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13918. ) and
  13919. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13920. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13921. begin
  13922. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13923. RemoveCurrentP(p, hp1);
  13924. Result := True;
  13925. Exit;
  13926. end;
  13927. A_BSWAP,
  13928. A_NEG,
  13929. A_NOT:
  13930. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13931. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13932. begin
  13933. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13934. RemoveCurrentP(p, hp1);
  13935. Result := True;
  13936. Exit;
  13937. end;
  13938. else
  13939. ;
  13940. end;
  13941. end;
  13942. if (taicpu(hp1).is_jmp) and
  13943. (taicpu(hp1).opcode<>A_JMP) and
  13944. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13945. begin
  13946. { change
  13947. and x, reg
  13948. jxx
  13949. to
  13950. test x, reg
  13951. jxx
  13952. if reg is deallocated before the
  13953. jump, but only if it's a conditional jump (PFV)
  13954. }
  13955. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13956. taicpu(p).opcode := A_TEST;
  13957. Exit;
  13958. end;
  13959. Break;
  13960. end;
  13961. { Lone AND tests }
  13962. if (taicpu(p).oper[0]^.typ = top_const) then
  13963. begin
  13964. {
  13965. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13966. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13967. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13968. }
  13969. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13970. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13971. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13972. begin
  13973. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13974. if taicpu(p).opsize = S_L then
  13975. begin
  13976. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13977. Result := True;
  13978. end;
  13979. end;
  13980. end;
  13981. { Backward check to determine necessity of and %reg,%reg }
  13982. if (taicpu(p).oper[0]^.typ = top_reg) and
  13983. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13984. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13985. GetLastInstruction(p, hp2) and
  13986. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  13987. { Check size of adjacent instruction to determine if the AND is
  13988. effectively a null operation }
  13989. (
  13990. (taicpu(p).opsize = taicpu(hp2).opsize) or
  13991. { Note: Don't include S_Q }
  13992. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  13993. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  13994. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  13995. ) then
  13996. begin
  13997. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  13998. { If GetNextInstruction returned False, hp1 will be nil }
  13999. RemoveCurrentP(p, hp1);
  14000. Result := True;
  14001. Exit;
  14002. end;
  14003. end;
  14004. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  14005. var
  14006. hp1, hp2: tai;
  14007. NewRef: TReference;
  14008. Distance: Cardinal;
  14009. TempTracking: TAllUsedRegs;
  14010. { This entire nested function is used in an if-statement below, but we
  14011. want to avoid all the used reg transfers and GetNextInstruction calls
  14012. until we really have to check }
  14013. function MemRegisterNotUsedLater: Boolean; inline;
  14014. var
  14015. hp2: tai;
  14016. begin
  14017. TransferUsedRegs(TmpUsedRegs);
  14018. hp2 := p;
  14019. repeat
  14020. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14021. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14022. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  14023. end;
  14024. begin
  14025. Result := False;
  14026. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14027. (taicpu(p).oper[1]^.typ = top_reg) then
  14028. begin
  14029. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14030. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14031. (hp1.typ <> ait_instruction) or
  14032. not
  14033. (
  14034. (cs_opt_level3 in current_settings.optimizerswitches) or
  14035. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14036. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14037. ) then
  14038. Exit;
  14039. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14040. addq $x, %rax
  14041. movq %rax, %rdx
  14042. sarq $63, %rdx
  14043. (%rax still in use)
  14044. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14045. leaq $x(%rax),%rdx
  14046. addq $x, %rax
  14047. sarq $63, %rdx
  14048. ...which is okay since it breaks the dependency chain between
  14049. addq and movq, but if OptPass2MOV is called first:
  14050. addq $x, %rax
  14051. cqto
  14052. ...which is better in all ways, taking only 2 cycles to execute
  14053. and much smaller in code size.
  14054. }
  14055. { The extra register tracking is quite strenuous }
  14056. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14057. MatchInstruction(hp1, A_MOV, []) then
  14058. begin
  14059. { Update the register tracking to the MOV instruction }
  14060. CopyUsedRegs(TempTracking);
  14061. hp2 := p;
  14062. repeat
  14063. UpdateUsedRegs(tai(hp2.Next));
  14064. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14065. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14066. OptPass2ADD get called again }
  14067. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14068. begin
  14069. { Reset the tracking to the current instruction }
  14070. RestoreUsedRegs(TempTracking);
  14071. ReleaseUsedRegs(TempTracking);
  14072. Result := True;
  14073. Exit;
  14074. end;
  14075. { Reset the tracking to the current instruction }
  14076. RestoreUsedRegs(TempTracking);
  14077. ReleaseUsedRegs(TempTracking);
  14078. { If OptPass2MOV returned True, we don't need to set Result to
  14079. True if hp1 didn't change because the ADD instruction didn't
  14080. get modified and we'll be evaluating hp1 again when the
  14081. peephole optimizer reaches it }
  14082. end;
  14083. { Change:
  14084. add %reg2,%reg1
  14085. (%reg2 not modified in between)
  14086. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14087. To:
  14088. mov/s/z #(%reg1,%reg2),%reg1
  14089. }
  14090. if (taicpu(p).oper[0]^.typ = top_reg) and
  14091. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14092. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14093. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14094. (
  14095. (
  14096. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14097. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14098. { r/esp cannot be an index }
  14099. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14100. ) or (
  14101. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14102. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14103. )
  14104. ) and (
  14105. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14106. (
  14107. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14108. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14109. MemRegisterNotUsedLater
  14110. )
  14111. ) then
  14112. begin
  14113. if (
  14114. { Instructions are guaranteed to be adjacent on -O2 and under }
  14115. (cs_opt_level3 in current_settings.optimizerswitches) and
  14116. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14117. ) then
  14118. begin
  14119. { If the other register is used in between, move the MOV
  14120. instruction to right after the ADD instruction so a
  14121. saving can still be made }
  14122. Asml.Remove(hp1);
  14123. Asml.InsertAfter(hp1, p);
  14124. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14125. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14126. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14127. RemoveCurrentp(p, hp1);
  14128. end
  14129. else
  14130. begin
  14131. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14132. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14133. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14134. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14135. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14136. { hp1 may not be the immediate next instruction under -O3 }
  14137. RemoveCurrentp(p)
  14138. else
  14139. RemoveCurrentp(p, hp1);
  14140. end;
  14141. Result := True;
  14142. Exit;
  14143. end;
  14144. { Change:
  14145. addl/q $x,%reg1
  14146. movl/q %reg1,%reg2
  14147. To:
  14148. leal/q $x(%reg1),%reg2
  14149. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14150. Breaks the dependency chain.
  14151. }
  14152. if (taicpu(p).oper[0]^.typ = top_const) and
  14153. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14154. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14155. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14156. (
  14157. { Instructions are guaranteed to be adjacent on -O2 and under }
  14158. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14159. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14160. ) then
  14161. begin
  14162. TransferUsedRegs(TmpUsedRegs);
  14163. hp2 := p;
  14164. repeat
  14165. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14166. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14167. if (
  14168. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14169. not (cs_opt_size in current_settings.optimizerswitches) or
  14170. (
  14171. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14172. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14173. )
  14174. ) then
  14175. begin
  14176. { Change the MOV instruction to a LEA instruction, and update the
  14177. first operand }
  14178. reference_reset(NewRef, 1, []);
  14179. NewRef.base := taicpu(p).oper[1]^.reg;
  14180. NewRef.scalefactor := 1;
  14181. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14182. taicpu(hp1).opcode := A_LEA;
  14183. taicpu(hp1).loadref(0, NewRef);
  14184. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14185. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14186. begin
  14187. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14188. { Move what is now the LEA instruction to before the ADD instruction }
  14189. Asml.Remove(hp1);
  14190. Asml.InsertBefore(hp1, p);
  14191. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14192. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14193. p := hp1;
  14194. end
  14195. else
  14196. begin
  14197. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14198. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14199. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14200. { hp1 may not be the immediate next instruction under -O3 }
  14201. RemoveCurrentp(p)
  14202. else
  14203. RemoveCurrentp(p, hp1);
  14204. end;
  14205. Result := True;
  14206. end;
  14207. end;
  14208. end;
  14209. end;
  14210. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14211. var
  14212. SubReg: TSubRegister;
  14213. hp1, hp2: tai;
  14214. CallJmp: Boolean;
  14215. begin
  14216. Result := False;
  14217. CallJmp := False;
  14218. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14219. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14220. with taicpu(p).oper[0]^.ref^ do
  14221. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14222. if (offset = 0) then
  14223. begin
  14224. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14225. begin
  14226. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14227. taicpu(p).opcode := A_ADD;
  14228. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14229. Result := True;
  14230. end
  14231. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14232. begin
  14233. if (base <> NR_NO) then
  14234. begin
  14235. if (scalefactor <= 1) then
  14236. begin
  14237. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14238. taicpu(p).opcode := A_ADD;
  14239. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14240. Result := True;
  14241. end;
  14242. end
  14243. else
  14244. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14245. if (scalefactor in [2, 4, 8]) then
  14246. begin
  14247. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14248. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14249. taicpu(p).opcode := A_SHL;
  14250. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14251. Result := True;
  14252. end;
  14253. end;
  14254. end
  14255. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14256. lot of latency, so break off the offset if %reg3 is used soon
  14257. afterwards }
  14258. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14259. { If 3-component addresses don't have additional latency, don't
  14260. perform this optimisation }
  14261. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14262. GetNextInstruction(p, hp1) and
  14263. (hp1.typ = ait_instruction) and
  14264. (
  14265. (
  14266. { Permit jumps and calls since they have a larger degree of overhead }
  14267. (
  14268. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14269. (
  14270. { ... unless the register specifies the location }
  14271. (taicpu(hp1).ops > 0) and
  14272. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14273. )
  14274. ) and
  14275. (
  14276. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14277. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14278. )
  14279. )
  14280. or
  14281. (
  14282. { Check up to two instructions ahead }
  14283. GetNextInstruction(hp1, hp2) and
  14284. (hp2.typ = ait_instruction) and
  14285. (
  14286. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14287. (
  14288. { Same as above }
  14289. (taicpu(hp2).ops > 0) and
  14290. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14291. )
  14292. ) and
  14293. (
  14294. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14295. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14296. )
  14297. )
  14298. ) then
  14299. begin
  14300. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14301. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14302. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14303. offset := 0;
  14304. if Assigned(symbol) or Assigned(relsymbol) then
  14305. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14306. else
  14307. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14308. { Inserting before the next instruction rather than after the
  14309. current instruction gives more accurate register tracking }
  14310. asml.InsertBefore(hp2, hp1);
  14311. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14312. Result := True;
  14313. end;
  14314. end;
  14315. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14316. var
  14317. hp1, hp2: tai;
  14318. NewRef: TReference;
  14319. Distance: Cardinal;
  14320. TempTracking: TAllUsedRegs;
  14321. begin
  14322. Result := False;
  14323. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14324. MatchOpType(taicpu(p),top_const,top_reg) then
  14325. begin
  14326. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14327. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14328. (hp1.typ <> ait_instruction) or
  14329. not
  14330. (
  14331. (cs_opt_level3 in current_settings.optimizerswitches) or
  14332. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14333. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14334. ) then
  14335. Exit;
  14336. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14337. subq $x, %rax
  14338. movq %rax, %rdx
  14339. sarq $63, %rdx
  14340. (%rax still in use)
  14341. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14342. leaq $-x(%rax),%rdx
  14343. movq $x, %rax
  14344. sarq $63, %rdx
  14345. ...which is okay since it breaks the dependency chain between
  14346. subq and movq, but if OptPass2MOV is called first:
  14347. subq $x, %rax
  14348. cqto
  14349. ...which is better in all ways, taking only 2 cycles to execute
  14350. and much smaller in code size.
  14351. }
  14352. { The extra register tracking is quite strenuous }
  14353. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14354. MatchInstruction(hp1, A_MOV, []) then
  14355. begin
  14356. { Update the register tracking to the MOV instruction }
  14357. CopyUsedRegs(TempTracking);
  14358. hp2 := p;
  14359. repeat
  14360. UpdateUsedRegs(tai(hp2.Next));
  14361. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14362. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14363. OptPass2SUB get called again }
  14364. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14365. begin
  14366. { Reset the tracking to the current instruction }
  14367. RestoreUsedRegs(TempTracking);
  14368. ReleaseUsedRegs(TempTracking);
  14369. Result := True;
  14370. Exit;
  14371. end;
  14372. { Reset the tracking to the current instruction }
  14373. RestoreUsedRegs(TempTracking);
  14374. ReleaseUsedRegs(TempTracking);
  14375. { If OptPass2MOV returned True, we don't need to set Result to
  14376. True if hp1 didn't change because the SUB instruction didn't
  14377. get modified and we'll be evaluating hp1 again when the
  14378. peephole optimizer reaches it }
  14379. end;
  14380. { Change:
  14381. subl/q $x,%reg1
  14382. movl/q %reg1,%reg2
  14383. To:
  14384. leal/q $-x(%reg1),%reg2
  14385. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14386. Breaks the dependency chain and potentially permits the removal of
  14387. a CMP instruction if one follows.
  14388. }
  14389. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14390. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14391. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14392. (
  14393. { Instructions are guaranteed to be adjacent on -O2 and under }
  14394. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14395. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14396. ) then
  14397. begin
  14398. TransferUsedRegs(TmpUsedRegs);
  14399. hp2 := p;
  14400. repeat
  14401. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14402. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14403. if (
  14404. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14405. not (cs_opt_size in current_settings.optimizerswitches) or
  14406. (
  14407. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14408. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14409. )
  14410. ) then
  14411. begin
  14412. { Change the MOV instruction to a LEA instruction, and update the
  14413. first operand }
  14414. reference_reset(NewRef, 1, []);
  14415. NewRef.base := taicpu(p).oper[1]^.reg;
  14416. NewRef.scalefactor := 1;
  14417. NewRef.offset := -taicpu(p).oper[0]^.val;
  14418. taicpu(hp1).opcode := A_LEA;
  14419. taicpu(hp1).loadref(0, NewRef);
  14420. TransferUsedRegs(TmpUsedRegs);
  14421. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14422. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14423. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14424. begin
  14425. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14426. { Move what is now the LEA instruction to before the SUB instruction }
  14427. Asml.Remove(hp1);
  14428. Asml.InsertBefore(hp1, p);
  14429. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14430. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14431. p := hp1;
  14432. end
  14433. else
  14434. begin
  14435. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14436. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14437. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14438. { hp1 may not be the immediate next instruction under -O3 }
  14439. RemoveCurrentp(p)
  14440. else
  14441. RemoveCurrentp(p, hp1);
  14442. end;
  14443. Result := True;
  14444. end;
  14445. end;
  14446. end;
  14447. end;
  14448. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14449. begin
  14450. { we can skip all instructions not messing with the stack pointer }
  14451. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14452. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14453. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14454. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14455. ({(taicpu(hp1).ops=0) or }
  14456. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14457. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14458. ) and }
  14459. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14460. )
  14461. ) do
  14462. GetNextInstruction(hp1,hp1);
  14463. Result:=assigned(hp1);
  14464. end;
  14465. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14466. var
  14467. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14468. begin
  14469. Result:=false;
  14470. hp5:=nil;
  14471. hp6:=nil;
  14472. hp7:=nil;
  14473. hp8:=nil;
  14474. { replace
  14475. leal(q) x(<stackpointer>),<stackpointer>
  14476. <optional .seh_stackalloc ...>
  14477. <optional .seh_endprologue ...>
  14478. call procname
  14479. <optional NOP>
  14480. leal(q) -x(<stackpointer>),<stackpointer>
  14481. <optional VZEROUPPER>
  14482. ret
  14483. by
  14484. jmp procname
  14485. but do it only on level 4 because it destroys stack back traces
  14486. }
  14487. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14488. MatchOpType(taicpu(p),top_ref,top_reg) and
  14489. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14490. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14491. { the -8, -24, -40 are not required, but bail out early if possible,
  14492. higher values are unlikely }
  14493. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14494. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14495. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14496. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14497. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14498. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14499. GetNextInstruction(p, hp1) and
  14500. { Take a copy of hp1 }
  14501. SetAndTest(hp1, hp4) and
  14502. { trick to skip label }
  14503. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14504. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14505. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14506. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14507. SkipSimpleInstructions(hp1) and
  14508. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14509. GetNextInstruction(hp1, hp2) and
  14510. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14511. { skip nop instruction on win64 }
  14512. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14513. SetAndTest(hp2,hp6) and
  14514. GetNextInstruction(hp2,hp2) and
  14515. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14516. ) and
  14517. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14518. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14519. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14520. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14521. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14522. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14523. { Segment register will be NR_NO }
  14524. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14525. GetNextInstruction(hp2, hp3) and
  14526. { trick to skip label }
  14527. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14528. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14529. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14530. SetAndTest(hp3,hp5) and
  14531. GetNextInstruction(hp3,hp3) and
  14532. MatchInstruction(hp3,A_RET,[S_NO])
  14533. )
  14534. ) and
  14535. (taicpu(hp3).ops=0) then
  14536. begin
  14537. taicpu(hp1).opcode := A_JMP;
  14538. taicpu(hp1).is_jmp := true;
  14539. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14540. { search for the stackalloc directive and remove it }
  14541. hp7:=tai(p.next);
  14542. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14543. begin
  14544. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14545. begin
  14546. { sanity check }
  14547. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14548. Internalerror(2024012201);
  14549. hp8:=tai(hp7.next);
  14550. RemoveInstruction(tai(hp7));
  14551. hp7:=hp8;
  14552. break;
  14553. end
  14554. else
  14555. hp7:=tai(hp7.next);
  14556. end;
  14557. RemoveCurrentP(p, hp4);
  14558. RemoveInstruction(hp2);
  14559. RemoveInstruction(hp3);
  14560. { if there is a vzeroupper instruction then move it before the jmp }
  14561. if Assigned(hp5) then
  14562. begin
  14563. AsmL.Remove(hp5);
  14564. ASmL.InsertBefore(hp5,hp1)
  14565. end;
  14566. { remove nop on win64 }
  14567. if Assigned(hp6) then
  14568. RemoveInstruction(hp6);
  14569. Result:=true;
  14570. end;
  14571. end;
  14572. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14573. {$ifdef x86_64}
  14574. var
  14575. hp1, hp2, hp3, hp4, hp5: tai;
  14576. {$endif x86_64}
  14577. begin
  14578. Result:=false;
  14579. {$ifdef x86_64}
  14580. hp5:=nil;
  14581. { replace
  14582. push %rax
  14583. call procname
  14584. pop %rcx
  14585. ret
  14586. by
  14587. jmp procname
  14588. but do it only on level 4 because it destroys stack back traces
  14589. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14590. for all supported calling conventions
  14591. }
  14592. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14593. MatchOpType(taicpu(p),top_reg) and
  14594. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14595. GetNextInstruction(p, hp1) and
  14596. { Take a copy of hp1 }
  14597. SetAndTest(hp1, hp4) and
  14598. { trick to skip label }
  14599. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14600. SkipSimpleInstructions(hp1) and
  14601. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14602. GetNextInstruction(hp1, hp2) and
  14603. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14604. MatchOpType(taicpu(hp2),top_reg) and
  14605. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14606. GetNextInstruction(hp2, hp3) and
  14607. { trick to skip label }
  14608. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14609. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14610. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14611. SetAndTest(hp3,hp5) and
  14612. GetNextInstruction(hp3,hp3) and
  14613. MatchInstruction(hp3,A_RET,[S_NO])
  14614. )
  14615. ) and
  14616. (taicpu(hp3).ops=0) then
  14617. begin
  14618. taicpu(hp1).opcode := A_JMP;
  14619. taicpu(hp1).is_jmp := true;
  14620. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14621. RemoveCurrentP(p, hp4);
  14622. RemoveInstruction(hp2);
  14623. RemoveInstruction(hp3);
  14624. if Assigned(hp5) then
  14625. begin
  14626. AsmL.Remove(hp5);
  14627. ASmL.InsertBefore(hp5,hp1)
  14628. end;
  14629. Result:=true;
  14630. end;
  14631. {$endif x86_64}
  14632. end;
  14633. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14634. var
  14635. Value, RegName: string;
  14636. hp1: tai;
  14637. begin
  14638. Result:=false;
  14639. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14640. begin
  14641. case taicpu(p).oper[0]^.val of
  14642. 0:
  14643. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14644. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14645. (
  14646. { See if we can still convert the instruction }
  14647. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14648. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14649. ) then
  14650. begin
  14651. { change "mov $0,%reg" into "xor %reg,%reg" }
  14652. taicpu(p).opcode := A_XOR;
  14653. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14654. Result := True;
  14655. {$ifdef x86_64}
  14656. end
  14657. else if (taicpu(p).opsize = S_Q) then
  14658. begin
  14659. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14660. { The actual optimization }
  14661. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14662. taicpu(p).changeopsize(S_L);
  14663. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14664. Result := True;
  14665. end;
  14666. $1..$FFFFFFFF:
  14667. begin
  14668. { Code size reduction by J. Gareth "Kit" Moreton }
  14669. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14670. case taicpu(p).opsize of
  14671. S_Q:
  14672. begin
  14673. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14674. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14675. { The actual optimization }
  14676. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14677. taicpu(p).changeopsize(S_L);
  14678. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14679. Result := True;
  14680. end;
  14681. else
  14682. { Do nothing };
  14683. end;
  14684. {$endif x86_64}
  14685. end;
  14686. -1:
  14687. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14688. if (cs_opt_size in current_settings.optimizerswitches) and
  14689. (taicpu(p).opsize <> S_B) and
  14690. (
  14691. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14692. (
  14693. { See if we can still convert the instruction }
  14694. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14695. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14696. )
  14697. ) then
  14698. begin
  14699. { change "mov $-1,%reg" into "or $-1,%reg" }
  14700. { NOTES:
  14701. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14702. - This operation creates a false dependency on the register, so only do it when optimising for size
  14703. - 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
  14704. }
  14705. taicpu(p).opcode := A_OR;
  14706. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14707. Result := True;
  14708. end;
  14709. else
  14710. { Do nothing };
  14711. end;
  14712. end;
  14713. end;
  14714. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14715. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14716. begin
  14717. Result := False;
  14718. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14719. Exit;
  14720. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14721. so don't bother optimising }
  14722. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14723. Exit;
  14724. if (taicpu(p).oper[0]^.typ <> top_const) or
  14725. { If the value can fit into an 8-bit signed integer, a smaller
  14726. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14727. falls within this range }
  14728. (
  14729. (taicpu(p).oper[0]^.val > -128) and
  14730. (taicpu(p).oper[0]^.val <= 127)
  14731. ) then
  14732. Exit;
  14733. { If we're optimising for size, this is acceptable }
  14734. if (cs_opt_size in current_settings.optimizerswitches) then
  14735. Exit(True);
  14736. if (taicpu(p).oper[1]^.typ = top_reg) and
  14737. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14738. Exit(True);
  14739. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14740. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14741. Exit(True);
  14742. end;
  14743. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14744. var
  14745. hp1: tai;
  14746. Value: TCGInt;
  14747. begin
  14748. Result := False;
  14749. if MatchOpType(taicpu(p), top_const, top_reg) then
  14750. begin
  14751. { Detect:
  14752. andw x, %ax (0 <= x < $8000)
  14753. ...
  14754. movzwl %ax,%eax
  14755. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14756. }
  14757. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14758. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14759. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14760. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14761. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14762. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14763. begin
  14764. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14765. taicpu(hp1).opcode := A_CWDE;
  14766. taicpu(hp1).clearop(0);
  14767. taicpu(hp1).clearop(1);
  14768. taicpu(hp1).ops := 0;
  14769. { A change was made, but not with p, so don't set Result, but
  14770. notify the compiler that a change was made }
  14771. Include(OptsToCheck, aoc_ForceNewIteration);
  14772. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14773. end;
  14774. end;
  14775. { If "not x" is a power of 2 (popcnt = 1), change:
  14776. and $x, %reg/ref
  14777. To:
  14778. btr lb(x), %reg/ref
  14779. }
  14780. if IsBTXAcceptable(p) and
  14781. (
  14782. { Make sure a TEST doesn't follow that plays with the register }
  14783. not GetNextInstruction(p, hp1) or
  14784. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14785. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14786. ) then
  14787. begin
  14788. {$push}{$R-}{$Q-}
  14789. { Value is a sign-extended 32-bit integer - just correct it
  14790. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14791. checks to see if this operand is an immediate. }
  14792. Value := not taicpu(p).oper[0]^.val;
  14793. {$pop}
  14794. {$ifdef x86_64}
  14795. if taicpu(p).opsize = S_L then
  14796. {$endif x86_64}
  14797. Value := Value and $FFFFFFFF;
  14798. if (PopCnt(QWord(Value)) = 1) then
  14799. begin
  14800. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14801. taicpu(p).opcode := A_BTR;
  14802. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14803. Result := True;
  14804. Exit;
  14805. end;
  14806. end;
  14807. end;
  14808. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14809. begin
  14810. Result := False;
  14811. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14812. Exit;
  14813. { Convert:
  14814. movswl %ax,%eax -> cwtl
  14815. movslq %eax,%rax -> cdqe
  14816. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14817. refer to the same opcode and depends only on the assembler's
  14818. current operand-size attribute. [Kit]
  14819. }
  14820. with taicpu(p) do
  14821. case opsize of
  14822. S_WL:
  14823. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14824. begin
  14825. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14826. opcode := A_CWDE;
  14827. clearop(0);
  14828. clearop(1);
  14829. ops := 0;
  14830. Result := True;
  14831. end;
  14832. {$ifdef x86_64}
  14833. S_LQ:
  14834. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14835. begin
  14836. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14837. opcode := A_CDQE;
  14838. clearop(0);
  14839. clearop(1);
  14840. ops := 0;
  14841. Result := True;
  14842. end;
  14843. {$endif x86_64}
  14844. else
  14845. ;
  14846. end;
  14847. end;
  14848. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14849. var
  14850. hp1, hp2: tai;
  14851. IdentityMask, Shift: TCGInt;
  14852. LimitSize: Topsize;
  14853. DoNotMerge: Boolean;
  14854. begin
  14855. Result := False;
  14856. { All these optimisations work on "shr const,%reg" }
  14857. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14858. Exit;
  14859. DoNotMerge := False;
  14860. Shift := taicpu(p).oper[0]^.val;
  14861. LimitSize := taicpu(p).opsize;
  14862. hp1 := p;
  14863. repeat
  14864. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14865. Break;
  14866. { Detect:
  14867. shr x, %reg
  14868. and y, %reg
  14869. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14870. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14871. }
  14872. case taicpu(hp1).opcode of
  14873. A_AND:
  14874. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14875. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14876. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14877. begin
  14878. { Make sure the FLAGS register isn't in use }
  14879. TransferUsedRegs(TmpUsedRegs);
  14880. hp2 := p;
  14881. repeat
  14882. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14883. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14884. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14885. begin
  14886. { Generate the identity mask }
  14887. case taicpu(p).opsize of
  14888. S_B:
  14889. IdentityMask := $FF shr Shift;
  14890. S_W:
  14891. IdentityMask := $FFFF shr Shift;
  14892. S_L:
  14893. IdentityMask := $FFFFFFFF shr Shift;
  14894. {$ifdef x86_64}
  14895. S_Q:
  14896. { We need to force the operands to be unsigned 64-bit
  14897. integers otherwise the wrong value is generated }
  14898. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14899. {$endif x86_64}
  14900. else
  14901. InternalError(2022081501);
  14902. end;
  14903. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14904. begin
  14905. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14906. { All the possible 1 bits are covered, so we can remove the AND }
  14907. hp2 := tai(hp1.Previous);
  14908. RemoveInstruction(hp1);
  14909. { p wasn't actually changed, so don't set Result to True,
  14910. but a change was nonetheless made elsewhere }
  14911. Include(OptsToCheck, aoc_ForceNewIteration);
  14912. { Do another pass in case other AND or MOVZX instructions
  14913. follow }
  14914. hp1 := hp2;
  14915. Continue;
  14916. end;
  14917. end;
  14918. end;
  14919. A_TEST, A_CMP, A_Jcc:
  14920. { Skip over conditional jumps and relevant comparisons }
  14921. Continue;
  14922. A_MOVZX:
  14923. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14924. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14925. begin
  14926. { Since the original register is being read as is, subsequent
  14927. SHRs must not be merged at this point }
  14928. DoNotMerge := True;
  14929. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14930. begin
  14931. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14932. begin
  14933. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14934. { All the possible 1 bits are covered, so we can remove the AND }
  14935. hp2 := tai(hp1.Previous);
  14936. RemoveInstruction(hp1);
  14937. hp1 := hp2;
  14938. end
  14939. else { Different register target }
  14940. begin
  14941. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14942. taicpu(hp1).opcode := A_MOV;
  14943. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14944. case taicpu(hp1).opsize of
  14945. S_BW:
  14946. taicpu(hp1).opsize := S_W;
  14947. S_BL, S_WL:
  14948. taicpu(hp1).opsize := S_L;
  14949. else
  14950. InternalError(2022081503);
  14951. end;
  14952. end;
  14953. end
  14954. else if (Shift > 0) and
  14955. (taicpu(p).opsize = S_W) and
  14956. (taicpu(hp1).opsize = S_WL) and
  14957. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14958. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14959. begin
  14960. { Detect:
  14961. shr x, %ax (x > 0)
  14962. ...
  14963. movzwl %ax,%eax
  14964. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14965. }
  14966. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14967. taicpu(hp1).opcode := A_CWDE;
  14968. taicpu(hp1).clearop(0);
  14969. taicpu(hp1).clearop(1);
  14970. taicpu(hp1).ops := 0;
  14971. end;
  14972. { Move onto the next instruction }
  14973. Continue;
  14974. end;
  14975. A_SHL, A_SAL, A_SHR:
  14976. if (taicpu(hp1).opsize <= LimitSize) and
  14977. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14978. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14979. begin
  14980. { Make sure the sizes don't exceed the register size limit
  14981. (measured by the shift value falling below the limit) }
  14982. if taicpu(hp1).opsize < LimitSize then
  14983. LimitSize := taicpu(hp1).opsize;
  14984. if taicpu(hp1).opcode = A_SHR then
  14985. Inc(Shift, taicpu(hp1).oper[0]^.val)
  14986. else
  14987. begin
  14988. Dec(Shift, taicpu(hp1).oper[0]^.val);
  14989. DoNotMerge := True;
  14990. end;
  14991. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  14992. Break;
  14993. { Since we've established that the combined shift is within
  14994. limits, we can actually combine the adjacent SHR
  14995. instructions even if they're different sizes }
  14996. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  14997. begin
  14998. hp2 := tai(hp1.Previous);
  14999. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  15000. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  15001. RemoveInstruction(hp1);
  15002. hp1 := hp2;
  15003. end;
  15004. { Move onto the next instruction }
  15005. Continue;
  15006. end;
  15007. else
  15008. ;
  15009. end;
  15010. Break;
  15011. until False;
  15012. { Detect the following (looking backwards):
  15013. shr %cl,%reg
  15014. shr x, %reg
  15015. Swap the two SHR instructions to minimise a pipeline stall.
  15016. }
  15017. if GetLastInstruction(p, hp1) and
  15018. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  15019. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  15020. { First operand will be %cl }
  15021. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  15022. { Just to be sure }
  15023. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  15024. begin
  15025. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  15026. { Moving the entries this way ensures the register tracking remains correct }
  15027. Asml.Remove(p);
  15028. Asml.InsertBefore(p, hp1);
  15029. p := hp1;
  15030. { Don't set Result to True because the current instruction is now
  15031. "shr %cl,%reg" and there's nothing more we can do with it }
  15032. end;
  15033. end;
  15034. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15035. var
  15036. hp1, hp2: tai;
  15037. Opposite, SecondOpposite: TAsmOp;
  15038. NewCond: TAsmCond;
  15039. begin
  15040. Result := False;
  15041. { Change:
  15042. add/sub 128,(dest)
  15043. To:
  15044. sub/add -128,(dest)
  15045. This generaally takes fewer bytes to encode because -128 can be stored
  15046. in a signed byte, whereas +128 cannot.
  15047. }
  15048. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15049. begin
  15050. if taicpu(p).opcode = A_ADD then
  15051. Opposite := A_SUB
  15052. else
  15053. Opposite := A_ADD;
  15054. { Be careful if the flags are in use, because the CF flag inverts
  15055. when changing from ADD to SUB and vice versa }
  15056. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15057. GetNextInstruction(p, hp1) then
  15058. begin
  15059. TransferUsedRegs(TmpUsedRegs);
  15060. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15061. hp2 := hp1;
  15062. { Scan ahead to check if everything's safe }
  15063. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15064. begin
  15065. if (hp1.typ <> ait_instruction) then
  15066. { Probably unsafe since the flags are still in use }
  15067. Exit;
  15068. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15069. { Stop searching at an unconditional jump }
  15070. Break;
  15071. if not
  15072. (
  15073. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15074. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15075. ) and
  15076. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15077. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15078. Exit;
  15079. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15080. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15081. { Move to the next instruction }
  15082. GetNextInstruction(hp1, hp1);
  15083. end;
  15084. while Assigned(hp2) and (hp2 <> hp1) do
  15085. begin
  15086. NewCond := C_None;
  15087. case taicpu(hp2).condition of
  15088. C_A, C_NBE:
  15089. NewCond := C_BE;
  15090. C_B, C_C, C_NAE:
  15091. NewCond := C_AE;
  15092. C_AE, C_NB, C_NC:
  15093. NewCond := C_B;
  15094. C_BE, C_NA:
  15095. NewCond := C_A;
  15096. else
  15097. { No change needed };
  15098. end;
  15099. if NewCond <> C_None then
  15100. begin
  15101. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15102. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15103. taicpu(hp2).condition := NewCond;
  15104. end
  15105. else
  15106. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15107. begin
  15108. { Because of the flipping of the carry bit, to ensure
  15109. the operation remains equivalent, ADC becomes SBB
  15110. and vice versa, and the constant is not-inverted.
  15111. If multiple ADCs or SBBs appear in a row, each one
  15112. changed causes the carry bit to invert, so they all
  15113. need to be flipped }
  15114. if taicpu(hp2).opcode = A_ADC then
  15115. SecondOpposite := A_SBB
  15116. else
  15117. SecondOpposite := A_ADC;
  15118. if taicpu(hp2).oper[0]^.typ <> top_const then
  15119. { Should have broken out of this optimisation already }
  15120. InternalError(2021112901);
  15121. 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]^) + ' -> ' +
  15122. 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);
  15123. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15124. taicpu(hp2).opcode := SecondOpposite;
  15125. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15126. end;
  15127. { Move to the next instruction }
  15128. GetNextInstruction(hp2, hp2);
  15129. end;
  15130. if (hp2 <> hp1) then
  15131. InternalError(2021111501);
  15132. end;
  15133. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15134. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15135. taicpu(p).opcode := Opposite;
  15136. taicpu(p).oper[0]^.val := -128;
  15137. { No further optimisations can be made on this instruction, so move
  15138. onto the next one to save time }
  15139. p := tai(p.Next);
  15140. UpdateUsedRegs(p);
  15141. Result := True;
  15142. Exit;
  15143. end;
  15144. { Detect:
  15145. add/sub %reg2,(dest)
  15146. add/sub x, (dest)
  15147. (dest can be a register or a reference)
  15148. Swap the instructions to minimise a pipeline stall. This reverses the
  15149. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15150. optimisations could be made.
  15151. }
  15152. if (taicpu(p).oper[0]^.typ = top_reg) and
  15153. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15154. (
  15155. (
  15156. (taicpu(p).oper[1]^.typ = top_reg) and
  15157. { We can try searching further ahead if we're writing to a register }
  15158. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15159. ) or
  15160. (
  15161. (taicpu(p).oper[1]^.typ = top_ref) and
  15162. GetNextInstruction(p, hp1)
  15163. )
  15164. ) and
  15165. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15166. (taicpu(hp1).oper[0]^.typ = top_const) and
  15167. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15168. begin
  15169. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15170. TransferUsedRegs(TmpUsedRegs);
  15171. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15172. hp2 := p;
  15173. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15174. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15175. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15176. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15177. begin
  15178. asml.remove(hp1);
  15179. asml.InsertBefore(hp1, p);
  15180. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15181. Result := True;
  15182. end;
  15183. end;
  15184. end;
  15185. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15186. var
  15187. hp1: tai;
  15188. begin
  15189. Result:=false;
  15190. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15191. while GetNextInstruction(p, hp1) and
  15192. TrySwapMovCmp(p, hp1) do
  15193. begin
  15194. if MatchInstruction(hp1, A_MOV, []) then
  15195. begin
  15196. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15197. begin
  15198. { A little hacky, but since CMP doesn't read the flags, only
  15199. modify them, it's safe if they get scrambled by MOV -> XOR }
  15200. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15201. Result := PostPeepholeOptMov(hp1);
  15202. {$ifdef x86_64}
  15203. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15204. { Used to shrink instruction size }
  15205. PostPeepholeOptXor(hp1);
  15206. {$endif x86_64}
  15207. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15208. end
  15209. else
  15210. begin
  15211. Result := PostPeepholeOptMov(hp1);
  15212. {$ifdef x86_64}
  15213. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15214. { Used to shrink instruction size }
  15215. PostPeepholeOptXor(hp1);
  15216. {$endif x86_64}
  15217. end;
  15218. end;
  15219. { Enabling this flag is actually a null operation, but it marks
  15220. the code as 'modified' during this pass }
  15221. Include(OptsToCheck, aoc_ForceNewIteration);
  15222. end;
  15223. { change "cmp $0, %reg" to "test %reg, %reg" }
  15224. if MatchOpType(taicpu(p),top_const,top_reg) and
  15225. (taicpu(p).oper[0]^.val = 0) then
  15226. begin
  15227. taicpu(p).opcode := A_TEST;
  15228. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15229. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15230. Result:=true;
  15231. end;
  15232. end;
  15233. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15234. var
  15235. IsTestConstX, IsValid : Boolean;
  15236. hp1,hp2 : tai;
  15237. begin
  15238. Result:=false;
  15239. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15240. if (taicpu(p).opcode = A_TEST) then
  15241. while GetNextInstruction(p, hp1) and
  15242. TrySwapMovCmp(p, hp1) do
  15243. begin
  15244. if MatchInstruction(hp1, A_MOV, []) then
  15245. begin
  15246. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15247. begin
  15248. { A little hacky, but since TEST doesn't read the flags, only
  15249. modify them, it's safe if they get scrambled by MOV -> XOR }
  15250. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15251. Result := PostPeepholeOptMov(hp1);
  15252. {$ifdef x86_64}
  15253. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15254. { Used to shrink instruction size }
  15255. PostPeepholeOptXor(hp1);
  15256. {$endif x86_64}
  15257. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15258. end
  15259. else
  15260. begin
  15261. Result := PostPeepholeOptMov(hp1);
  15262. {$ifdef x86_64}
  15263. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15264. { Used to shrink instruction size }
  15265. PostPeepholeOptXor(hp1);
  15266. {$endif x86_64}
  15267. end;
  15268. end;
  15269. { Enabling this flag is actually a null operation, but it marks
  15270. the code as 'modified' during this pass }
  15271. Include(OptsToCheck, aoc_ForceNewIteration);
  15272. end;
  15273. { If x is a power of 2 (popcnt = 1), change:
  15274. or $x, %reg/ref
  15275. To:
  15276. bts lb(x), %reg/ref
  15277. }
  15278. if (taicpu(p).opcode = A_OR) and
  15279. IsBTXAcceptable(p) and
  15280. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15281. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15282. (
  15283. { Don't optimise if a test instruction follows }
  15284. not GetNextInstruction(p, hp1) or
  15285. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15286. ) then
  15287. begin
  15288. 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);
  15289. taicpu(p).opcode := A_BTS;
  15290. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15291. Result := True;
  15292. Exit;
  15293. end;
  15294. { If x is a power of 2 (popcnt = 1), change:
  15295. test $x, %reg/ref
  15296. je / sete / cmove (or jne / setne)
  15297. To:
  15298. bt lb(x), %reg/ref
  15299. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15300. }
  15301. if (taicpu(p).opcode = A_TEST) and
  15302. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15303. (taicpu(p).oper[0]^.typ = top_const) and
  15304. (
  15305. (cs_opt_size in current_settings.optimizerswitches) or
  15306. (
  15307. (taicpu(p).oper[1]^.typ = top_reg) and
  15308. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15309. ) or
  15310. (
  15311. (taicpu(p).oper[1]^.typ <> top_reg) and
  15312. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15313. )
  15314. ) and
  15315. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15316. { For sizes less than S_L, the byte size is equal or larger with BT,
  15317. so don't bother optimising }
  15318. (taicpu(p).opsize >= S_L) then
  15319. begin
  15320. IsValid := True;
  15321. { Check the next set of instructions, watching the FLAGS register
  15322. and the conditions used }
  15323. TransferUsedRegs(TmpUsedRegs);
  15324. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15325. hp1 := p;
  15326. hp2 := nil;
  15327. while GetNextInstruction(hp1, hp1) do
  15328. begin
  15329. if not Assigned(hp2) then
  15330. { The first instruction after TEST }
  15331. hp2 := hp1;
  15332. if (hp1.typ <> ait_instruction) then
  15333. begin
  15334. { If the flags are no longer in use, everything is fine }
  15335. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15336. IsValid := False;
  15337. Break;
  15338. end;
  15339. case taicpu(hp1).condition of
  15340. C_None:
  15341. begin
  15342. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15343. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15344. { Something is not quite normal, so play safe and don't change }
  15345. IsValid := False;
  15346. Break;
  15347. end;
  15348. C_E, C_Z, C_NE, C_NZ:
  15349. { This is fine };
  15350. else
  15351. begin
  15352. { Unsupported condition }
  15353. IsValid := False;
  15354. Break;
  15355. end;
  15356. end;
  15357. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15358. end;
  15359. if IsValid then
  15360. begin
  15361. while hp2 <> hp1 do
  15362. begin
  15363. case taicpu(hp2).condition of
  15364. C_Z, C_E:
  15365. taicpu(hp2).condition := C_NC;
  15366. C_NZ, C_NE:
  15367. taicpu(hp2).condition := C_C;
  15368. else
  15369. { Should not get this by this point }
  15370. InternalError(2022110701);
  15371. end;
  15372. GetNextInstruction(hp2, hp2);
  15373. end;
  15374. 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);
  15375. taicpu(p).opcode := A_BT;
  15376. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15377. Result := True;
  15378. Exit;
  15379. end;
  15380. end;
  15381. { removes the line marked with (x) from the sequence
  15382. and/or/xor/add/sub/... $x, %y
  15383. test/or %y, %y | test $-1, %y (x)
  15384. j(n)z _Label
  15385. as the first instruction already adjusts the ZF
  15386. %y operand may also be a reference }
  15387. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15388. MatchOperand(taicpu(p).oper[0]^,-1);
  15389. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15390. GetLastInstruction(p, hp1) and
  15391. (tai(hp1).typ = ait_instruction) and
  15392. GetNextInstruction(p,hp2) and
  15393. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15394. case taicpu(hp1).opcode Of
  15395. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15396. { These two instructions set the zero flag if the result is zero }
  15397. A_POPCNT, A_LZCNT:
  15398. begin
  15399. if (
  15400. { With POPCNT, an input of zero will set the zero flag
  15401. because the population count of zero is zero }
  15402. (taicpu(hp1).opcode = A_POPCNT) and
  15403. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15404. (
  15405. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15406. { Faster than going through the second half of the 'or'
  15407. condition below }
  15408. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15409. )
  15410. ) or (
  15411. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15412. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15413. { and in case of carry for A(E)/B(E)/C/NC }
  15414. (
  15415. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15416. (
  15417. (taicpu(hp1).opcode <> A_ADD) and
  15418. (taicpu(hp1).opcode <> A_SUB) and
  15419. (taicpu(hp1).opcode <> A_LZCNT)
  15420. )
  15421. )
  15422. ) then
  15423. begin
  15424. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15425. RemoveCurrentP(p, hp2);
  15426. Result:=true;
  15427. Exit;
  15428. end;
  15429. end;
  15430. A_SHL, A_SAL, A_SHR, A_SAR:
  15431. begin
  15432. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15433. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15434. { therefore, it's only safe to do this optimization for }
  15435. { shifts by a (nonzero) constant }
  15436. (taicpu(hp1).oper[0]^.typ = top_const) and
  15437. (taicpu(hp1).oper[0]^.val <> 0) and
  15438. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15439. { and in case of carry for A(E)/B(E)/C/NC }
  15440. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15441. begin
  15442. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15443. RemoveCurrentP(p, hp2);
  15444. Result:=true;
  15445. Exit;
  15446. end;
  15447. end;
  15448. A_DEC, A_INC, A_NEG:
  15449. begin
  15450. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15451. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15452. { and in case of carry for A(E)/B(E)/C/NC }
  15453. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15454. begin
  15455. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15456. RemoveCurrentP(p, hp2);
  15457. Result:=true;
  15458. Exit;
  15459. end;
  15460. end;
  15461. A_ANDN, A_BZHI:
  15462. begin
  15463. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15464. { Only the zero and sign flags are consistent with what the result is }
  15465. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15466. begin
  15467. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15468. RemoveCurrentP(p, hp2);
  15469. Result:=true;
  15470. Exit;
  15471. end;
  15472. end;
  15473. A_BEXTR:
  15474. begin
  15475. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15476. { Only the zero flag is set }
  15477. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15478. begin
  15479. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15480. RemoveCurrentP(p, hp2);
  15481. Result:=true;
  15482. Exit;
  15483. end;
  15484. end;
  15485. else
  15486. ;
  15487. end; { case }
  15488. { change "test $-1,%reg" into "test %reg,%reg" }
  15489. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15490. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15491. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15492. if MatchInstruction(p, A_OR, []) and
  15493. { Can only match if they're both registers }
  15494. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15495. begin
  15496. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15497. taicpu(p).opcode := A_TEST;
  15498. { No need to set Result to True, as we've done all the optimisations we can }
  15499. end;
  15500. end;
  15501. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15502. var
  15503. hp1,hp3 : tai;
  15504. {$ifndef x86_64}
  15505. hp2 : taicpu;
  15506. {$endif x86_64}
  15507. begin
  15508. Result:=false;
  15509. hp3:=nil;
  15510. {$ifndef x86_64}
  15511. { don't do this on modern CPUs, this really hurts them due to
  15512. broken call/ret pairing }
  15513. if (current_settings.optimizecputype < cpu_Pentium2) and
  15514. not(cs_create_pic in current_settings.moduleswitches) and
  15515. GetNextInstruction(p, hp1) and
  15516. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15517. MatchOpType(taicpu(hp1),top_ref) and
  15518. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15519. begin
  15520. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15521. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15522. InsertLLItem(p.previous, p, hp2);
  15523. taicpu(p).opcode := A_JMP;
  15524. taicpu(p).is_jmp := true;
  15525. RemoveInstruction(hp1);
  15526. Result:=true;
  15527. end
  15528. else
  15529. {$endif x86_64}
  15530. { replace
  15531. call procname
  15532. ret
  15533. by
  15534. jmp procname
  15535. but do it only on level 4 because it destroys stack back traces
  15536. else if the subroutine is marked as no return, remove the ret
  15537. }
  15538. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15539. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15540. GetNextInstruction(p, hp1) and
  15541. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15542. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15543. SetAndTest(hp1,hp3) and
  15544. GetNextInstruction(hp1,hp1) and
  15545. MatchInstruction(hp1,A_RET,[S_NO])
  15546. )
  15547. ) and
  15548. (taicpu(hp1).ops=0) then
  15549. begin
  15550. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15551. { we might destroy stack alignment here if we do not do a call }
  15552. (target_info.stackalign<=sizeof(SizeUInt)) then
  15553. begin
  15554. taicpu(p).opcode := A_JMP;
  15555. taicpu(p).is_jmp := true;
  15556. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15557. end
  15558. else
  15559. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15560. RemoveInstruction(hp1);
  15561. if Assigned(hp3) then
  15562. begin
  15563. AsmL.Remove(hp3);
  15564. AsmL.InsertBefore(hp3,p)
  15565. end;
  15566. Result:=true;
  15567. end;
  15568. end;
  15569. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15570. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15571. begin
  15572. case OpSize of
  15573. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15574. Result := (Val <= $FF) and (Val >= -128);
  15575. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15576. Result := (Val <= $FFFF) and (Val >= -32768);
  15577. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15578. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15579. else
  15580. Result := True;
  15581. end;
  15582. end;
  15583. var
  15584. hp1, hp2 : tai;
  15585. SizeChange: Boolean;
  15586. PreMessage: string;
  15587. begin
  15588. Result := False;
  15589. if (taicpu(p).oper[0]^.typ = top_reg) and
  15590. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15591. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15592. begin
  15593. { Change (using movzbl %al,%eax as an example):
  15594. movzbl %al, %eax movzbl %al, %eax
  15595. cmpl x, %eax testl %eax,%eax
  15596. To:
  15597. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15598. movzbl %al, %eax movzbl %al, %eax
  15599. Smaller instruction and minimises pipeline stall as the CPU
  15600. doesn't have to wait for the register to get zero-extended. [Kit]
  15601. Also allow if the smaller of the two registers is being checked,
  15602. as this still removes the false dependency.
  15603. }
  15604. if
  15605. (
  15606. (
  15607. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15608. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15609. ) or (
  15610. { If MatchOperand returns True, they must both be registers }
  15611. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15612. )
  15613. ) and
  15614. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15615. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15616. begin
  15617. 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);
  15618. asml.Remove(hp1);
  15619. asml.InsertBefore(hp1, p);
  15620. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15621. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15622. begin
  15623. taicpu(hp1).opcode := A_TEST;
  15624. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15625. end;
  15626. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15627. case taicpu(p).opsize of
  15628. S_BW, S_BL:
  15629. begin
  15630. SizeChange := taicpu(hp1).opsize <> S_B;
  15631. taicpu(hp1).changeopsize(S_B);
  15632. end;
  15633. S_WL:
  15634. begin
  15635. SizeChange := taicpu(hp1).opsize <> S_W;
  15636. taicpu(hp1).changeopsize(S_W);
  15637. end
  15638. else
  15639. InternalError(2020112701);
  15640. end;
  15641. UpdateUsedRegs(tai(p.Next));
  15642. { Check if the register is used aferwards - if not, we can
  15643. remove the movzx instruction completely }
  15644. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15645. begin
  15646. { Hp1 is a better position than p for debugging purposes }
  15647. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15648. RemoveCurrentp(p, hp1);
  15649. Result := True;
  15650. end;
  15651. if SizeChange then
  15652. DebugMsg(SPeepholeOptimization + PreMessage +
  15653. 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)
  15654. else
  15655. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15656. Exit;
  15657. end;
  15658. { Change (using movzwl %ax,%eax as an example):
  15659. movzwl %ax, %eax
  15660. movb %al, (dest) (Register is smaller than read register in movz)
  15661. To:
  15662. movb %al, (dest) (Move one back to avoid a false dependency)
  15663. movzwl %ax, %eax
  15664. }
  15665. if (taicpu(hp1).opcode = A_MOV) and
  15666. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15667. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15668. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15669. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15670. begin
  15671. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15672. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15673. asml.Remove(hp1);
  15674. asml.InsertBefore(hp1, p);
  15675. if taicpu(hp1).oper[1]^.typ = top_reg then
  15676. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15677. { Check if the register is used aferwards - if not, we can
  15678. remove the movzx instruction completely }
  15679. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15680. begin
  15681. { Hp1 is a better position than p for debugging purposes }
  15682. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15683. RemoveCurrentp(p, hp1);
  15684. Result := True;
  15685. end;
  15686. Exit;
  15687. end;
  15688. end;
  15689. end;
  15690. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15691. var
  15692. hp1: tai;
  15693. {$ifdef x86_64}
  15694. PreMessage, RegName: string;
  15695. {$endif x86_64}
  15696. begin
  15697. Result := False;
  15698. { If x is a power of 2 (popcnt = 1), change:
  15699. xor $x, %reg/ref
  15700. To:
  15701. btc lb(x), %reg/ref
  15702. }
  15703. if IsBTXAcceptable(p) and
  15704. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15705. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15706. (
  15707. { Don't optimise if a test instruction follows }
  15708. not GetNextInstruction(p, hp1) or
  15709. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15710. ) then
  15711. begin
  15712. 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);
  15713. taicpu(p).opcode := A_BTC;
  15714. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15715. Result := True;
  15716. Exit;
  15717. end;
  15718. {$ifdef x86_64}
  15719. { Code size reduction by J. Gareth "Kit" Moreton }
  15720. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15721. as this removes the REX prefix }
  15722. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15723. Exit;
  15724. if taicpu(p).oper[0]^.typ <> top_reg then
  15725. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15726. InternalError(2018011500);
  15727. case taicpu(p).opsize of
  15728. S_Q:
  15729. begin
  15730. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15731. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15732. { The actual optimization }
  15733. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15734. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15735. taicpu(p).changeopsize(S_L);
  15736. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15737. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15738. end;
  15739. else
  15740. ;
  15741. end;
  15742. {$endif x86_64}
  15743. end;
  15744. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15745. var
  15746. XReg: TRegister;
  15747. begin
  15748. Result := False;
  15749. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15750. Smaller encoding and slightly faster on some platforms (also works for
  15751. ZMM-sized registers) }
  15752. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15753. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15754. begin
  15755. XReg := taicpu(p).oper[0]^.reg;
  15756. if (taicpu(p).oper[1]^.reg = XReg) then
  15757. begin
  15758. taicpu(p).changeopsize(S_XMM);
  15759. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15760. if (cs_opt_size in current_settings.optimizerswitches) then
  15761. begin
  15762. { Change input registers to %xmm0 to reduce size. Note that
  15763. there's a risk of a false dependency doing this, so only
  15764. optimise for size here }
  15765. XReg := NR_XMM0;
  15766. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15767. end
  15768. else
  15769. begin
  15770. setsubreg(XReg, R_SUBMMX);
  15771. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15772. end;
  15773. taicpu(p).oper[0]^.reg := XReg;
  15774. taicpu(p).oper[1]^.reg := XReg;
  15775. Result := True;
  15776. end;
  15777. end;
  15778. end;
  15779. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15780. var
  15781. OperIdx: Integer;
  15782. begin
  15783. for OperIdx := 0 to p.ops - 1 do
  15784. if p.oper[OperIdx]^.typ = top_ref then
  15785. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15786. end;
  15787. end.